code
stringlengths 13
1.2M
| order_type
stringclasses 1
value | original_example
dict | step_ids
listlengths 1
5
|
---|---|---|---|
myDict = {'Friends': ['AP', 'Soham', 'Baba'], 'Likes': ['Math',
'Programming'], 'languages': ['C++', 'Python', 'Java']}
myInt = 123
myFloat = 12.3333
myName = 'Somesh Thakur'
|
normal
|
{
"blob_id": "345967e2aeafda6ce30cbbbbacf976c97b17def7",
"index": 515,
"step-1": "<mask token>\n",
"step-2": "myDict = {'Friends': ['AP', 'Soham', 'Baba'], 'Likes': ['Math',\n 'Programming'], 'languages': ['C++', 'Python', 'Java']}\nmyInt = 123\nmyFloat = 12.3333\nmyName = 'Somesh Thakur'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
#!/usr/bin/env python3
import os
import requests
# This is the main url of the BSE API
# THIS WILL CHANGE TO HTTPS IN THE FUTURE
# HTTPS IS RECOMMENDED
main_bse_url = "http://basissetexchange.org"
# This allows for overriding the URL via an environment variable
# Feel free to just use the base_url below
base_url = os.environ.get('BSE_API_URL', main_bse_url)
def print_results(r):
'''Checks for errors and prints the results of a request'''
# r.text will contain the formatted output as a string
print(r.text)
if r.status_code != 200:
raise RuntimeError("Could not obtain data from the BSE. Check the error information above")
############################################
# Change the user agent and 'from' headers
############################################
# Change these to something more
# descriptive if you would like. This lets us know
# how many different people/groups are using the site
# Valid email is COMPLETELY OPTIONAL. Put whatever
# you would like in there, or leave it as is. If you
# do put your email there, we will never give it
# away or email you, except in case we think errors in
# your script are causing us problems.
headers = {
'User-Agent': 'BSE Example Python Script',
'From': '[email protected]'
}
###############################################################
# Get the def2-QZVP basis for all elements in nwchem format
# Note that basis set names and formats are not case sensitive
###############################################################
r = requests.get(base_url + '/api/basis/def2-qzvpd/format/nwchem',
headers=headers
)
print_results(r)
######################################################################
# Get the cc-pvqz basis for hydrogen and carbon in gaussian94 format
######################################################################
# Elements can be passed a variety of ways. Here, I'm just
# passing a list of Z numbers. See elements.py for other ways
# you can specify elements
params = {'elements': [1, 6, 7]}
r = requests.get(base_url + '/api/basis/cc-pvqz/format/psi4',
params=params,
headers=headers
)
print_results(r)
|
normal
|
{
"blob_id": "168a76fd3bb43afe26a6a217e90f48704b4f2042",
"index": 6738,
"step-1": "<mask token>\n\n\ndef print_results(r):\n \"\"\"Checks for errors and prints the results of a request\"\"\"\n print(r.text)\n if r.status_code != 200:\n raise RuntimeError(\n 'Could not obtain data from the BSE. Check the error information above'\n )\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef print_results(r):\n \"\"\"Checks for errors and prints the results of a request\"\"\"\n print(r.text)\n if r.status_code != 200:\n raise RuntimeError(\n 'Could not obtain data from the BSE. Check the error information above'\n )\n\n\n<mask token>\nprint_results(r)\n<mask token>\nprint_results(r)\n",
"step-3": "<mask token>\nmain_bse_url = 'http://basissetexchange.org'\nbase_url = os.environ.get('BSE_API_URL', main_bse_url)\n\n\ndef print_results(r):\n \"\"\"Checks for errors and prints the results of a request\"\"\"\n print(r.text)\n if r.status_code != 200:\n raise RuntimeError(\n 'Could not obtain data from the BSE. Check the error information above'\n )\n\n\nheaders = {'User-Agent': 'BSE Example Python Script', 'From': '[email protected]'}\nr = requests.get(base_url + '/api/basis/def2-qzvpd/format/nwchem', headers=\n headers)\nprint_results(r)\nparams = {'elements': [1, 6, 7]}\nr = requests.get(base_url + '/api/basis/cc-pvqz/format/psi4', params=params,\n headers=headers)\nprint_results(r)\n",
"step-4": "import os\nimport requests\nmain_bse_url = 'http://basissetexchange.org'\nbase_url = os.environ.get('BSE_API_URL', main_bse_url)\n\n\ndef print_results(r):\n \"\"\"Checks for errors and prints the results of a request\"\"\"\n print(r.text)\n if r.status_code != 200:\n raise RuntimeError(\n 'Could not obtain data from the BSE. Check the error information above'\n )\n\n\nheaders = {'User-Agent': 'BSE Example Python Script', 'From': '[email protected]'}\nr = requests.get(base_url + '/api/basis/def2-qzvpd/format/nwchem', headers=\n headers)\nprint_results(r)\nparams = {'elements': [1, 6, 7]}\nr = requests.get(base_url + '/api/basis/cc-pvqz/format/psi4', params=params,\n headers=headers)\nprint_results(r)\n",
"step-5": "#!/usr/bin/env python3\n\nimport os\nimport requests\n\n# This is the main url of the BSE API\n# THIS WILL CHANGE TO HTTPS IN THE FUTURE\n# HTTPS IS RECOMMENDED\nmain_bse_url = \"http://basissetexchange.org\"\n\n# This allows for overriding the URL via an environment variable\n# Feel free to just use the base_url below\nbase_url = os.environ.get('BSE_API_URL', main_bse_url)\n\n\ndef print_results(r):\n '''Checks for errors and prints the results of a request'''\n\n # r.text will contain the formatted output as a string\n print(r.text)\n if r.status_code != 200:\n raise RuntimeError(\"Could not obtain data from the BSE. Check the error information above\")\n\n\n\n############################################\n# Change the user agent and 'from' headers\n############################################\n\n# Change these to something more\n# descriptive if you would like. This lets us know\n# how many different people/groups are using the site\n\n# Valid email is COMPLETELY OPTIONAL. Put whatever\n# you would like in there, or leave it as is. If you\n# do put your email there, we will never give it\n# away or email you, except in case we think errors in\n# your script are causing us problems.\nheaders = {\n 'User-Agent': 'BSE Example Python Script',\n 'From': '[email protected]'\n}\n\n\n###############################################################\n# Get the def2-QZVP basis for all elements in nwchem format\n# Note that basis set names and formats are not case sensitive\n###############################################################\nr = requests.get(base_url + '/api/basis/def2-qzvpd/format/nwchem',\n headers=headers\n )\n\nprint_results(r)\n\n\n######################################################################\n# Get the cc-pvqz basis for hydrogen and carbon in gaussian94 format\n######################################################################\n# Elements can be passed a variety of ways. Here, I'm just\n# passing a list of Z numbers. See elements.py for other ways\n# you can specify elements\nparams = {'elements': [1, 6, 7]}\nr = requests.get(base_url + '/api/basis/cc-pvqz/format/psi4',\n params=params,\n headers=headers\n )\n\nprint_results(r)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
from pymongo import MongoClient, GEOSPHERE, GEO2D
import os, sys, json, pprint
sys.path.insert(0, '../utils')
import path_functions
client = MongoClient( 'localhost', 27017 )
db = client[ 'nfcdata' ]
json_files_path_list = path_functions.get_json_files('../../ftp-data/geojson-files/quikscat-l2b12')
for json_file in json_files_path_list:
current_collection = 'GeoJSON-quikscat-l2b12-' + path_functions.get_file_name( json_file )
print(current_collection)
collection_list = db.collection_names()
if current_collection not in collection_list:
collection = db[current_collection]
collection.create_index([( "geometry", GEOSPHERE )])
json_docs = json.load( open( json_file ) )
for doc in json_docs['features']:
collection.insert( doc )
# -- DROP COLLECTIONS --
# collection_list = db.collection_names()
# for collection in collection_list:
# db.drop_collection(collection)
# -- PRINT COLLECTIONS --
print( db.collection_names() )
# # -- PRINT INDEXES --
# collection_list = db.collection_names()
# for current_collection in collection_list:
# collection = db[current_collection]
# print( 'Index: ', sorted( list( collection.index_information() ) ) )
# -- PRINT DATA --
# collection = db['GeoJSON-quikscat-l2b12-005']
# cursor = collection.find({})
# for document in cursor:
# print('\n - - - - - - - DOCUMENTO - - - - - - - \n')
# print(document)
# -- SPATIAL QUERYING USING 2D INDEX
collection_list = db.collection_names()
for current_collection in collection_list:
collection = db[ current_collection ]
for doc in collection.find(
{ "geometry": {
"$geoWithin": {
"$geometry" : {
"type": "Polygon" ,
"coordinates" : [
[
[-77.49, -89.70],
[0.00, 0.00],
[10.00, 10.00],
[-77.49, -89.70]
]
]
} } } } ):
pprint.pprint( doc )
# -- TEMPORAL QUERYING USING 2D INDEX
collection_list = db.collection_names()
for current_collection in collection_list:
collection = db[current_collection]
for doc in collection.find( { "properties.time": 2009002 } ).limit(3):
pprint.pprint(doc)
# -- TEMPORAL-SPATIAL QUERYING USING 2D INDEX
collection_list = db.collection_names()
for current_collection in collection_list:
collection = db[ current_collection ]
for doc in collection.find(
{ "geometry": {
"$geoWithin": {
"$geometry" : {
"type": "Polygon" ,
"coordinates" : [
[
[-77.49, -89.70],
[0.00, 0.00],
[10.00, 10.00],
[-77.49, -89.70]
]
]
} } }, "properties.time": 2009003 } ):
pprint.pprint( doc )
# collection = db['quikscat-l2b12-001']
# cursor = collection.find({})
# for document in cursor:
# pprint.pprint( document )
|
normal
|
{
"blob_id": "cceda9a8a0188499ae0aa588701bb8104b5ed313",
"index": 1041,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.insert(0, '../utils')\n<mask token>\nfor json_file in json_files_path_list:\n current_collection = ('GeoJSON-quikscat-l2b12-' + path_functions.\n get_file_name(json_file))\n print(current_collection)\n collection_list = db.collection_names()\n if current_collection not in collection_list:\n collection = db[current_collection]\n collection.create_index([('geometry', GEOSPHERE)])\n json_docs = json.load(open(json_file))\n for doc in json_docs['features']:\n collection.insert(doc)\nprint(db.collection_names())\n<mask token>\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}}):\n pprint.pprint(doc)\n<mask token>\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'properties.time': 2009002}).limit(3):\n pprint.pprint(doc)\n<mask token>\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}, 'properties.time': 2009003}):\n pprint.pprint(doc)\n",
"step-3": "<mask token>\nsys.path.insert(0, '../utils')\n<mask token>\nclient = MongoClient('localhost', 27017)\ndb = client['nfcdata']\njson_files_path_list = path_functions.get_json_files(\n '../../ftp-data/geojson-files/quikscat-l2b12')\nfor json_file in json_files_path_list:\n current_collection = ('GeoJSON-quikscat-l2b12-' + path_functions.\n get_file_name(json_file))\n print(current_collection)\n collection_list = db.collection_names()\n if current_collection not in collection_list:\n collection = db[current_collection]\n collection.create_index([('geometry', GEOSPHERE)])\n json_docs = json.load(open(json_file))\n for doc in json_docs['features']:\n collection.insert(doc)\nprint(db.collection_names())\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}}):\n pprint.pprint(doc)\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'properties.time': 2009002}).limit(3):\n pprint.pprint(doc)\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}, 'properties.time': 2009003}):\n pprint.pprint(doc)\n",
"step-4": "from pymongo import MongoClient, GEOSPHERE, GEO2D\nimport os, sys, json, pprint\nsys.path.insert(0, '../utils')\nimport path_functions\nclient = MongoClient('localhost', 27017)\ndb = client['nfcdata']\njson_files_path_list = path_functions.get_json_files(\n '../../ftp-data/geojson-files/quikscat-l2b12')\nfor json_file in json_files_path_list:\n current_collection = ('GeoJSON-quikscat-l2b12-' + path_functions.\n get_file_name(json_file))\n print(current_collection)\n collection_list = db.collection_names()\n if current_collection not in collection_list:\n collection = db[current_collection]\n collection.create_index([('geometry', GEOSPHERE)])\n json_docs = json.load(open(json_file))\n for doc in json_docs['features']:\n collection.insert(doc)\nprint(db.collection_names())\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}}):\n pprint.pprint(doc)\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'properties.time': 2009002}).limit(3):\n pprint.pprint(doc)\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find({'geometry': {'$geoWithin': {'$geometry': {\n 'type': 'Polygon', 'coordinates': [[[-77.49, -89.7], [0.0, 0.0], [\n 10.0, 10.0], [-77.49, -89.7]]]}}}, 'properties.time': 2009003}):\n pprint.pprint(doc)\n",
"step-5": "\nfrom pymongo import MongoClient, GEOSPHERE, GEO2D\n\nimport os, sys, json, pprint\nsys.path.insert(0, '../utils') \nimport path_functions \n\n\nclient = MongoClient( 'localhost', 27017 )\ndb = client[ 'nfcdata' ]\n\njson_files_path_list = path_functions.get_json_files('../../ftp-data/geojson-files/quikscat-l2b12')\n\nfor json_file in json_files_path_list:\n \n current_collection = 'GeoJSON-quikscat-l2b12-' + path_functions.get_file_name( json_file )\n print(current_collection)\n collection_list = db.collection_names()\n\n if current_collection not in collection_list:\n collection = db[current_collection]\n collection.create_index([( \"geometry\", GEOSPHERE )])\n\n json_docs = json.load( open( json_file ) )\n for doc in json_docs['features']:\n collection.insert( doc )\n\n\n# -- DROP COLLECTIONS --\n# collection_list = db.collection_names()\n# for collection in collection_list:\n# db.drop_collection(collection)\n\n# -- PRINT COLLECTIONS --\nprint( db.collection_names() )\n\n# # -- PRINT INDEXES --\n# collection_list = db.collection_names()\n# for current_collection in collection_list:\n# collection = db[current_collection]\n# print( 'Index: ', sorted( list( collection.index_information() ) ) )\n\n# -- PRINT DATA --\n# collection = db['GeoJSON-quikscat-l2b12-005']\n# cursor = collection.find({})\n# for document in cursor:\n# print('\\n - - - - - - - DOCUMENTO - - - - - - - \\n')\n# print(document) \n\n# -- SPATIAL QUERYING USING 2D INDEX\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[ current_collection ]\n\n for doc in collection.find( \n { \"geometry\": { \n \"$geoWithin\": {\n \"$geometry\" : {\n \"type\": \"Polygon\" , \n \"coordinates\" : [ \n [\n [-77.49, -89.70],\n [0.00, 0.00],\n [10.00, 10.00],\n [-77.49, -89.70]\n ]\n ]\n } } } } ):\n pprint.pprint( doc )\n\n# -- TEMPORAL QUERYING USING 2D INDEX\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[current_collection]\n for doc in collection.find( { \"properties.time\": 2009002 } ).limit(3):\n pprint.pprint(doc)\n\n# -- TEMPORAL-SPATIAL QUERYING USING 2D INDEX\ncollection_list = db.collection_names()\nfor current_collection in collection_list:\n collection = db[ current_collection ]\n\n for doc in collection.find( \n { \"geometry\": { \n \"$geoWithin\": {\n \"$geometry\" : {\n \"type\": \"Polygon\" , \n \"coordinates\" : [ \n [\n [-77.49, -89.70],\n [0.00, 0.00],\n [10.00, 10.00],\n [-77.49, -89.70]\n ]\n ]\n } } }, \"properties.time\": 2009003 } ):\n pprint.pprint( doc )\n\n# collection = db['quikscat-l2b12-001']\n# cursor = collection.find({})\n# for document in cursor:\n# pprint.pprint( document )\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import json
from django.db import models
from django.conf import settings
from django.core.serializers import serialize
# Create your models here.
def upload_updated_image(instance,filename):
return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)
class UpdateQueryset(models.QuerySet):
def serialize(self):
# dot value method
list_value=list(self.values("user","id","name","content","image"))
return json.dumps(list_value)
class UpdateManager(models.Manager):
def get_queryset(self):
return UpdateQueryset(self.model,using=self.db)
class CRUD(models.Model):
user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
name =models.TextField(blank=True,null=True)
content =models.TextField(blank=True,null=True)
image =models.ImageField(upload_to=upload_updated_image,null=True,blank=True)
updated =models.DateTimeField(auto_now=True)
timestamp =models.DateTimeField(auto_now_add=True)
# This is modellistview
objects=UpdateManager()
def __str__(self):
return self.name or ""
#This is for modeldetailview
def serialize(self):
try:
image=self.image.url
except:
image=""
data={
"user":self.user.id,
"id":self.id,
"name":self.name,
"content":self.content,
"image":image
}
return json.dumps(data)
|
normal
|
{
"blob_id": "5749f30d1a1efd5404654d755bca4515adcf4bca",
"index": 1810,
"step-1": "<mask token>\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-2": "<mask token>\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-3": "<mask token>\n\n\ndef upload_updated_image(instance, filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=\n filename)\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-4": "import json\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.serializers import serialize\n\n\ndef upload_updated_image(instance, filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=\n filename)\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-5": "import json\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.serializers import serialize\n\n# Create your models here.\n\ndef upload_updated_image(instance,filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)\n\nclass UpdateQueryset(models.QuerySet):\n def serialize(self):\n # dot value method\n list_value=list(self.values(\"user\",\"id\",\"name\",\"content\",\"image\")) \n return json.dumps(list_value)\n\nclass UpdateManager(models.Manager):\n def get_queryset(self):\n return UpdateQueryset(self.model,using=self.db)\n\nclass CRUD(models.Model):\n user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)\n name =models.TextField(blank=True,null=True)\n content =models.TextField(blank=True,null=True)\n image =models.ImageField(upload_to=upload_updated_image,null=True,blank=True)\n updated =models.DateTimeField(auto_now=True)\n timestamp =models.DateTimeField(auto_now_add=True)\n \n # This is modellistview\n objects=UpdateManager()\n\n def __str__(self):\n return self.name or \"\"\n\n \n #This is for modeldetailview\n def serialize(self):\n try:\n image=self.image.url\n except:\n image=\"\"\n data={\n \"user\":self.user.id,\n \"id\":self.id,\n \"name\":self.name,\n \"content\":self.content,\n \"image\":image\n }\n\n return json.dumps(data)\n",
"step-ids": [
4,
8,
9,
10,
11
]
}
|
[
4,
8,
9,
10,
11
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-08-24 22:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0026_auto_20160712_1541'),
]
operations = [
migrations.CreateModel(
name='Location',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=50, null=True)),
('addr1', models.CharField(blank=True, max_length=50, null=True)),
('addr2', models.CharField(blank=True, max_length=50, null=True)),
('city', models.CharField(blank=True, max_length=50, null=True)),
('state', models.CharField(blank=True, max_length=50, null=True)),
('zip_code', models.CharField(blank=True, max_length=20, null=True)),
('phone_main', models.CharField(blank=True, max_length=20, null=True)),
('phone_other', models.CharField(blank=True, max_length=20, null=True)),
('notes', models.TextField(blank=True, null=True)),
],
),
migrations.RemoveField(
model_name='user',
name='location',
),
migrations.AddField(
model_name='user',
name='location',
field=models.ManyToManyField(blank=True, null=True, related_name='user_location', to='users.Location'),
),
]
|
normal
|
{
"blob_id": "04c1765e6c2302098be2a7f3242dfd536683f742",
"index": 6138,
"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 = [('users', '0026_auto_20160712_1541')]\n operations = [migrations.CreateModel(name='Location', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(blank=True,\n max_length=50, null=True)), ('addr1', models.CharField(blank=True,\n max_length=50, null=True)), ('addr2', models.CharField(blank=True,\n max_length=50, null=True)), ('city', models.CharField(blank=True,\n max_length=50, null=True)), ('state', models.CharField(blank=True,\n max_length=50, null=True)), ('zip_code', models.CharField(blank=\n True, max_length=20, null=True)), ('phone_main', models.CharField(\n blank=True, max_length=20, null=True)), ('phone_other', models.\n CharField(blank=True, max_length=20, null=True)), ('notes', models.\n TextField(blank=True, null=True))]), migrations.RemoveField(\n model_name='user', name='location'), migrations.AddField(model_name\n ='user', name='location', field=models.ManyToManyField(blank=True,\n null=True, related_name='user_location', to='users.Location'))]\n",
"step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('users', '0026_auto_20160712_1541')]\n operations = [migrations.CreateModel(name='Location', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('name', models.CharField(blank=True,\n max_length=50, null=True)), ('addr1', models.CharField(blank=True,\n max_length=50, null=True)), ('addr2', models.CharField(blank=True,\n max_length=50, null=True)), ('city', models.CharField(blank=True,\n max_length=50, null=True)), ('state', models.CharField(blank=True,\n max_length=50, null=True)), ('zip_code', models.CharField(blank=\n True, max_length=20, null=True)), ('phone_main', models.CharField(\n blank=True, max_length=20, null=True)), ('phone_other', models.\n CharField(blank=True, max_length=20, null=True)), ('notes', models.\n TextField(blank=True, null=True))]), migrations.RemoveField(\n model_name='user', name='location'), migrations.AddField(model_name\n ='user', name='location', field=models.ManyToManyField(blank=True,\n null=True, related_name='user_location', to='users.Location'))]\n",
"step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-08-24 22:13\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0026_auto_20160712_1541'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Location',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(blank=True, max_length=50, null=True)),\n ('addr1', models.CharField(blank=True, max_length=50, null=True)),\n ('addr2', models.CharField(blank=True, max_length=50, null=True)),\n ('city', models.CharField(blank=True, max_length=50, null=True)),\n ('state', models.CharField(blank=True, max_length=50, null=True)),\n ('zip_code', models.CharField(blank=True, max_length=20, null=True)),\n ('phone_main', models.CharField(blank=True, max_length=20, null=True)),\n ('phone_other', models.CharField(blank=True, max_length=20, null=True)),\n ('notes', models.TextField(blank=True, null=True)),\n ],\n ),\n migrations.RemoveField(\n model_name='user',\n name='location',\n ),\n migrations.AddField(\n model_name='user',\n name='location',\n field=models.ManyToManyField(blank=True, null=True, related_name='user_location', to='users.Location'),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
elem = driver.find_element_by_xpath('//*[@id="kw"]')
elem.send_keys("python selenium", Keys.ENTER)
print(driver.page_source)
|
normal
|
{
"blob_id": "3c8352ff2fc92ada1b58603df2a1a402e57842be",
"index": 8606,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndriver.get('https://www.baidu.com')\n<mask token>\nelem.send_keys('python selenium', Keys.ENTER)\nprint(driver.page_source)\n",
"step-3": "<mask token>\ndriver = webdriver.Chrome()\ndriver.get('https://www.baidu.com')\nelem = driver.find_element_by_xpath('//*[@id=\"kw\"]')\nelem.send_keys('python selenium', Keys.ENTER)\nprint(driver.page_source)\n",
"step-4": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\ndriver = webdriver.Chrome()\ndriver.get('https://www.baidu.com')\nelem = driver.find_element_by_xpath('//*[@id=\"kw\"]')\nelem.send_keys('python selenium', Keys.ENTER)\nprint(driver.page_source)\n",
"step-5": "# coding: utf-8\r\n\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\ndriver = webdriver.Chrome()\r\ndriver.get(\"https://www.baidu.com\")\r\n\r\nelem = driver.find_element_by_xpath('//*[@id=\"kw\"]')\r\nelem.send_keys(\"python selenium\", Keys.ENTER)\r\n\r\nprint(driver.page_source)\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import uuid
from cqlengine import columns
from cqlengine.models import Model
from datetime import datetime as dt
class MBase(Model):
__abstract__ = True
#__keyspace__ = model_keyspace
class Post(MBase):
id = columns.BigInt(index=True, primary_key=True)
user_id = columns.Integer(required=True, index=True)
text = columns.Text(required=True)
likes = columns.Counter
class Project(MBase):
id = columns.Integer(primary_key=True)
follower_count = columns.Counter
class Channel(MBase):
id = columns.Integer(primary_key=True)
slug = columns.Text(required=True, index=True)
name = columns.Text(required=True)
class User(MBase):
id = columns.Integer(primary_key=True)
nick = columns.Text(required=True, index=True)
follower_count = columns.Counter
following_count = columns.Counter
extended = columns.Map(columns.Text, columns.Text)
class UserTimeLine(MBase):
"""
POSTs that user will see in their timeline
"""
user_id = columns.Integer(primary_key=True)
post_id = columns.BigInt(primary_key=True)
class UserProject(MBase):
"""
Projects that user follows
"""
user_id = columns.Integer(primary_key=True)
project_id = columns.Integer(primary_key=True)
class UserPost(MBase):
"""
All the POSTs of a user
"""
user_id = columns.Integer(primary_key=True)
post_id = columns.BigInt(primary_key=True)
class UserFollower(MBase):
"""
Followers of a user
"""
user_id = columns.Integer(primary_key=True)
follower_id = columns.Integer(primary_key=True)
class UserFollowing(MBase):
"""
A user follows another user
"""
user_id = columns.Integer(primary_key=True)
following_id = columns.Integer(primary_key=True)
class ProjectFollower(MBase):
project_id = columns.Integer(primary_key=True)
user_id = columns.Integer(primary_key=True)
class PostFollower(MBase):
post_id = columns.TimeUUID(primary_key=True)
user_id = columns.Integer(primary_key=True)
class ChannelFollower(MBase):
channel_id = columns.Integer(primary_key=True)
user_id = columns.Integer(primary_key=True)
class ChannelTimeLine(MBase):
channel_id = columns.Integer(primary_key=True)
post_id = columns.BigInt(primary_key=True)
class ProjectTimeLine(MBase):
project_id = columns.Integer(primary_key=True)
post_id = columns.BigInt(primary_key=True)
class PostLike(MBase):
post_id = columns.BigInt(primary_key=True)
user_id = columns.Integer(primary_key=True)
class PostComment(MBase):
post_id = columns.BigInt(primary_key=True)
comment_id = columns.BigInt(primary_key=True)
|
normal
|
{
"blob_id": "9cb734f67d5149b052ff1d412d446aea1654fa69",
"index": 9543,
"step-1": "<mask token>\n\n\nclass User(MBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass UserTimeLine(MBase):\n \"\"\"\n POSTs that user will see in their timeline\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserProject(MBase):\n \"\"\"\n Projects that user follows\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n project_id = columns.Integer(primary_key=True)\n\n\nclass UserPost(MBase):\n \"\"\"\n All the POSTs of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserFollower(MBase):\n \"\"\"\n Followers of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n follower_id = columns.Integer(primary_key=True)\n\n\nclass UserFollowing(MBase):\n \"\"\"\n A user follows another user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n following_id = columns.Integer(primary_key=True)\n\n\nclass ProjectFollower(MBase):\n project_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostFollower(MBase):\n post_id = columns.TimeUUID(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelFollower(MBase):\n channel_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelTimeLine(MBase):\n channel_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass ProjectTimeLine(MBase):\n project_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass PostLike(MBase):\n post_id = columns.BigInt(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostComment(MBase):\n post_id = columns.BigInt(primary_key=True)\n comment_id = columns.BigInt(primary_key=True)\n",
"step-2": "<mask token>\n\n\nclass Channel(MBase):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass User(MBase):\n id = columns.Integer(primary_key=True)\n nick = columns.Text(required=True, index=True)\n follower_count = columns.Counter\n following_count = columns.Counter\n extended = columns.Map(columns.Text, columns.Text)\n\n\nclass UserTimeLine(MBase):\n \"\"\"\n POSTs that user will see in their timeline\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserProject(MBase):\n \"\"\"\n Projects that user follows\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n project_id = columns.Integer(primary_key=True)\n\n\nclass UserPost(MBase):\n \"\"\"\n All the POSTs of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserFollower(MBase):\n \"\"\"\n Followers of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n follower_id = columns.Integer(primary_key=True)\n\n\nclass UserFollowing(MBase):\n \"\"\"\n A user follows another user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n following_id = columns.Integer(primary_key=True)\n\n\nclass ProjectFollower(MBase):\n project_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostFollower(MBase):\n post_id = columns.TimeUUID(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelFollower(MBase):\n channel_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelTimeLine(MBase):\n channel_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass ProjectTimeLine(MBase):\n project_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass PostLike(MBase):\n post_id = columns.BigInt(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostComment(MBase):\n post_id = columns.BigInt(primary_key=True)\n comment_id = columns.BigInt(primary_key=True)\n",
"step-3": "<mask token>\n\n\nclass Project(MBase):\n id = columns.Integer(primary_key=True)\n follower_count = columns.Counter\n\n\nclass Channel(MBase):\n id = columns.Integer(primary_key=True)\n slug = columns.Text(required=True, index=True)\n name = columns.Text(required=True)\n\n\nclass User(MBase):\n id = columns.Integer(primary_key=True)\n nick = columns.Text(required=True, index=True)\n follower_count = columns.Counter\n following_count = columns.Counter\n extended = columns.Map(columns.Text, columns.Text)\n\n\nclass UserTimeLine(MBase):\n \"\"\"\n POSTs that user will see in their timeline\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserProject(MBase):\n \"\"\"\n Projects that user follows\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n project_id = columns.Integer(primary_key=True)\n\n\nclass UserPost(MBase):\n \"\"\"\n All the POSTs of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserFollower(MBase):\n \"\"\"\n Followers of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n follower_id = columns.Integer(primary_key=True)\n\n\nclass UserFollowing(MBase):\n \"\"\"\n A user follows another user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n following_id = columns.Integer(primary_key=True)\n\n\nclass ProjectFollower(MBase):\n project_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostFollower(MBase):\n post_id = columns.TimeUUID(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelFollower(MBase):\n channel_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelTimeLine(MBase):\n channel_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass ProjectTimeLine(MBase):\n project_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass PostLike(MBase):\n post_id = columns.BigInt(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostComment(MBase):\n post_id = columns.BigInt(primary_key=True)\n comment_id = columns.BigInt(primary_key=True)\n",
"step-4": "<mask token>\n\n\nclass Post(MBase):\n id = columns.BigInt(index=True, primary_key=True)\n user_id = columns.Integer(required=True, index=True)\n text = columns.Text(required=True)\n likes = columns.Counter\n\n\nclass Project(MBase):\n id = columns.Integer(primary_key=True)\n follower_count = columns.Counter\n\n\nclass Channel(MBase):\n id = columns.Integer(primary_key=True)\n slug = columns.Text(required=True, index=True)\n name = columns.Text(required=True)\n\n\nclass User(MBase):\n id = columns.Integer(primary_key=True)\n nick = columns.Text(required=True, index=True)\n follower_count = columns.Counter\n following_count = columns.Counter\n extended = columns.Map(columns.Text, columns.Text)\n\n\nclass UserTimeLine(MBase):\n \"\"\"\n POSTs that user will see in their timeline\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserProject(MBase):\n \"\"\"\n Projects that user follows\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n project_id = columns.Integer(primary_key=True)\n\n\nclass UserPost(MBase):\n \"\"\"\n All the POSTs of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserFollower(MBase):\n \"\"\"\n Followers of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n follower_id = columns.Integer(primary_key=True)\n\n\nclass UserFollowing(MBase):\n \"\"\"\n A user follows another user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n following_id = columns.Integer(primary_key=True)\n\n\nclass ProjectFollower(MBase):\n project_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostFollower(MBase):\n post_id = columns.TimeUUID(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelFollower(MBase):\n channel_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelTimeLine(MBase):\n channel_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass ProjectTimeLine(MBase):\n project_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass PostLike(MBase):\n post_id = columns.BigInt(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostComment(MBase):\n post_id = columns.BigInt(primary_key=True)\n comment_id = columns.BigInt(primary_key=True)\n",
"step-5": "import uuid\nfrom cqlengine import columns\nfrom cqlengine.models import Model\nfrom datetime import datetime as dt\n\n\nclass MBase(Model):\n __abstract__ = True\n #__keyspace__ = model_keyspace\n\n\nclass Post(MBase):\n id = columns.BigInt(index=True, primary_key=True)\n user_id = columns.Integer(required=True, index=True)\n text = columns.Text(required=True)\n likes = columns.Counter\n\n\nclass Project(MBase):\n id = columns.Integer(primary_key=True)\n follower_count = columns.Counter\n\n\nclass Channel(MBase):\n id = columns.Integer(primary_key=True)\n slug = columns.Text(required=True, index=True)\n name = columns.Text(required=True)\n\n\nclass User(MBase):\n id = columns.Integer(primary_key=True)\n nick = columns.Text(required=True, index=True)\n follower_count = columns.Counter\n following_count = columns.Counter\n extended = columns.Map(columns.Text, columns.Text)\n\n\nclass UserTimeLine(MBase):\n \"\"\"\n POSTs that user will see in their timeline\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserProject(MBase):\n \"\"\"\n Projects that user follows\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n project_id = columns.Integer(primary_key=True)\n\n\nclass UserPost(MBase):\n \"\"\"\n All the POSTs of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass UserFollower(MBase):\n \"\"\"\n Followers of a user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n follower_id = columns.Integer(primary_key=True)\n\n\nclass UserFollowing(MBase):\n \"\"\"\n A user follows another user\n \"\"\"\n user_id = columns.Integer(primary_key=True)\n following_id = columns.Integer(primary_key=True)\n\n\nclass ProjectFollower(MBase):\n project_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostFollower(MBase):\n post_id = columns.TimeUUID(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelFollower(MBase):\n channel_id = columns.Integer(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass ChannelTimeLine(MBase):\n channel_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass ProjectTimeLine(MBase):\n project_id = columns.Integer(primary_key=True)\n post_id = columns.BigInt(primary_key=True)\n\n\nclass PostLike(MBase):\n post_id = columns.BigInt(primary_key=True)\n user_id = columns.Integer(primary_key=True)\n\n\nclass PostComment(MBase):\n post_id = columns.BigInt(primary_key=True)\n comment_id = columns.BigInt(primary_key=True)\n",
"step-ids": [
30,
32,
35,
37,
41
]
}
|
[
30,
32,
35,
37,
41
] |
# -*- coding: utf-8 -*-
"""overview.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/examples/style_transfer/overview.ipynb
##### Copyright 2019 The TensorFlow Authors.
"""
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL
logging.getLogger('tensorflow').setLevel(logging.FATAL)
import tensorflow as tf
print(tf.__version__)
import IPython.display as display
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (12,12)
mpl.rcParams['axes.grid'] = False
import numpy as np
import time
import functools
import image_grabber
import def_grabber
import cv2
import random
"""Download the content and style images, and the pre-trained TensorFlow Lite models."""
paths = ["data/style01.jpg", "data/style02.jpg", "data/style03.jpg"]
style_path = random.choice(paths)
style_predict_path = tf.keras.utils.get_file('style_predict.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite')
style_transform_path = tf.keras.utils.get_file('style_transform.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite')
"""## Pre-process the inputs
* The content image and the style image must be RGB images with pixel values being float32 numbers between [0..1].
* The style image size must be (1, 256, 256, 3). We central crop the image and resize it.
* The content image must be (1, 384, 384, 3). We central crop the image and resize it.
"""
# Function to load an image from a file, and add a batch dimension.
def load_img(path_to_img):
img = tf.io.read_file(path_to_img)
img = tf.io.decode_image(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
img = img[tf.newaxis, :]
return img
# Function to pre-process by resizing an central cropping it.
def preprocess_image(image, target_dim):
# Resize the image so that the shorter dimension becomes 256px.
shape = tf.cast(tf.shape(image)[1:-1], tf.float32)
short_dim = min(shape)
scale = target_dim / short_dim
new_shape = tf.cast(shape * scale, tf.int32)
image = tf.image.resize(image, new_shape)
# Central crop the image.
image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)
return image
"""## Run style transfer with TensorFlow Lite
### Style prediction
"""
# Function to run style prediction on preprocessed style image.
def run_style_predict(preprocessed_style_image):
# Load the model.
interpreter = tf.lite.Interpreter(model_path=style_predict_path)
# Set model input.
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
interpreter.set_tensor(input_details[0]["index"], preprocessed_style_image)
# Calculate style bottleneck.
interpreter.invoke()
style_bottleneck = interpreter.tensor(
interpreter.get_output_details()[0]["index"]
)()
return style_bottleneck
"""### Style transform"""
# Run style transform on preprocessed style image
def run_style_transform(style_bottleneck, preprocessed_content_image):
# Load the model.
interpreter = tf.lite.Interpreter(model_path=style_transform_path)
# Set model input.
input_details = interpreter.get_input_details()
interpreter.allocate_tensors()
# Set model inputs.
interpreter.set_tensor(input_details[0]["index"], preprocessed_content_image)
interpreter.set_tensor(input_details[1]["index"], style_bottleneck)
interpreter.invoke()
# Transform content image.
stylized_image = interpreter.tensor(
interpreter.get_output_details()[0]["index"]
)()
return stylized_image
def art_grab(term):
content_path = image_grabber.im_grab(term, DISP=0)
# Load the input images.
content_image = load_img(content_path)
style_image = load_img(style_path)
# Preprocess the input images.
preprocessed_content_image = preprocess_image(content_image, 384)
preprocessed_style_image = preprocess_image(style_image, 256)
# Calculate style bottleneck for the preprocessed style image.
style_bottleneck = run_style_predict(preprocessed_style_image)
# Stylize the content image using the style bottleneck.
stylized_image = run_style_transform(style_bottleneck, preprocessed_content_image)
# Visualize the output.
#imshow(stylized_image, 'Stylized Image')
if len(stylized_image.shape) > 3:
stylized_image = tf.squeeze(stylized_image, axis=0)
stylized_image = np.array(stylized_image)
return stylized_image
|
normal
|
{
"blob_id": "36ce0de4cb760632959392a9f982532436bd37b0",
"index": 7272,
"step-1": "<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n",
"step-2": "<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n",
"step-3": "<mask token>\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\n<mask token>\nprint(tf.__version__)\n<mask token>\nmpl.rcParams['figure.figsize'] = 12, 12\nmpl.rcParams['axes.grid'] = False\n<mask token>\npaths = ['data/style01.jpg', 'data/style02.jpg', 'data/style03.jpg']\nstyle_path = random.choice(paths)\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite'\n )\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite'\n )\n<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n",
"step-4": "<mask token>\nimport logging\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\nimport tensorflow as tf\nprint(tf.__version__)\nimport IPython.display as display\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['figure.figsize'] = 12, 12\nmpl.rcParams['axes.grid'] = False\nimport numpy as np\nimport time\nimport functools\nimport image_grabber\nimport def_grabber\nimport cv2\nimport random\n<mask token>\npaths = ['data/style01.jpg', 'data/style02.jpg', 'data/style03.jpg']\nstyle_path = random.choice(paths)\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite'\n )\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite'\n )\n<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n",
"step-5": "# -*- coding: utf-8 -*-\r\n\"\"\"overview.ipynb\r\n\r\nAutomatically generated by Colaboratory.\r\n\r\nOriginal file is located at\r\n https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/examples/style_transfer/overview.ipynb\r\n\r\n##### Copyright 2019 The TensorFlow Authors.\r\n\"\"\"\r\n\r\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# https://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\nimport logging\r\nimport os\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL\r\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\r\n\r\nimport tensorflow as tf\r\nprint(tf.__version__)\r\n\r\nimport IPython.display as display\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nmpl.rcParams['figure.figsize'] = (12,12)\r\nmpl.rcParams['axes.grid'] = False\r\n\r\nimport numpy as np\r\nimport time\r\nimport functools\r\n\r\nimport image_grabber\r\nimport def_grabber\r\nimport cv2\r\n\r\nimport random\r\n\r\n\r\n\"\"\"Download the content and style images, and the pre-trained TensorFlow Lite models.\"\"\"\r\npaths = [\"data/style01.jpg\", \"data/style02.jpg\", \"data/style03.jpg\"]\r\nstyle_path = random.choice(paths)\r\n\r\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite')\r\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite')\r\n\r\n\"\"\"## Pre-process the inputs\r\n\r\n* The content image and the style image must be RGB images with pixel values being float32 numbers between [0..1].\r\n* The style image size must be (1, 256, 256, 3). We central crop the image and resize it.\r\n* The content image must be (1, 384, 384, 3). We central crop the image and resize it.\r\n\"\"\"\r\n\r\n# Function to load an image from a file, and add a batch dimension.\r\ndef load_img(path_to_img):\r\n img = tf.io.read_file(path_to_img)\r\n img = tf.io.decode_image(img, channels=3)\r\n img = tf.image.convert_image_dtype(img, tf.float32)\r\n img = img[tf.newaxis, :]\r\n\r\n return img\r\n\r\n# Function to pre-process by resizing an central cropping it.\r\ndef preprocess_image(image, target_dim):\r\n # Resize the image so that the shorter dimension becomes 256px.\r\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\r\n short_dim = min(shape)\r\n scale = target_dim / short_dim\r\n new_shape = tf.cast(shape * scale, tf.int32)\r\n image = tf.image.resize(image, new_shape)\r\n\r\n # Central crop the image.\r\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\r\n\r\n return image\r\n\r\n\"\"\"## Run style transfer with TensorFlow Lite\r\n\r\n### Style prediction\r\n\"\"\"\r\n# Function to run style prediction on preprocessed style image.\r\ndef run_style_predict(preprocessed_style_image):\r\n # Load the model.\r\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\r\n\r\n # Set model input.\r\n interpreter.allocate_tensors()\r\n input_details = interpreter.get_input_details()\r\n interpreter.set_tensor(input_details[0][\"index\"], preprocessed_style_image)\r\n\r\n # Calculate style bottleneck.\r\n interpreter.invoke()\r\n style_bottleneck = interpreter.tensor(\r\n interpreter.get_output_details()[0][\"index\"]\r\n )()\r\n\r\n return style_bottleneck\r\n\r\n\"\"\"### Style transform\"\"\"\r\n\r\n# Run style transform on preprocessed style image\r\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\r\n # Load the model.\r\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\r\n\r\n # Set model input.\r\n input_details = interpreter.get_input_details()\r\n interpreter.allocate_tensors()\r\n\r\n # Set model inputs.\r\n interpreter.set_tensor(input_details[0][\"index\"], preprocessed_content_image)\r\n interpreter.set_tensor(input_details[1][\"index\"], style_bottleneck)\r\n interpreter.invoke()\r\n\r\n # Transform content image.\r\n stylized_image = interpreter.tensor(\r\n interpreter.get_output_details()[0][\"index\"]\r\n )()\r\n\r\n return stylized_image\r\n\r\ndef art_grab(term):\r\n content_path = image_grabber.im_grab(term, DISP=0)\r\n\r\n # Load the input images.\r\n content_image = load_img(content_path)\r\n style_image = load_img(style_path)\r\n\r\n # Preprocess the input images.\r\n preprocessed_content_image = preprocess_image(content_image, 384)\r\n preprocessed_style_image = preprocess_image(style_image, 256)\r\n\r\n # Calculate style bottleneck for the preprocessed style image.\r\n style_bottleneck = run_style_predict(preprocessed_style_image)\r\n\r\n # Stylize the content image using the style bottleneck.\r\n stylized_image = run_style_transform(style_bottleneck, preprocessed_content_image)\r\n\r\n # Visualize the output.\r\n #imshow(stylized_image, 'Stylized Image')\r\n if len(stylized_image.shape) > 3:\r\n stylized_image = tf.squeeze(stylized_image, axis=0)\r\n stylized_image = np.array(stylized_image)\r\n\r\n return stylized_image\r\n",
"step-ids": [
4,
5,
7,
8,
9
]
}
|
[
4,
5,
7,
8,
9
] |
from __future__ import annotations
import pytest
from pytest import param
import ibis
import ibis.expr.datatypes as dt
from ibis.backends.base.sql.alchemy.geospatial import geospatial_supported
DB_TYPES = [
# Exact numbers
("BIGINT", dt.int64),
("BIT", dt.boolean),
("DECIMAL", dt.Decimal(precision=18, scale=0)),
("DECIMAL(5, 2)", dt.Decimal(precision=5, scale=2)),
("INT", dt.int32),
("MONEY", dt.int64),
("NUMERIC", dt.Decimal(18, 0)),
("NUMERIC(10,5)", dt.Decimal(10, 5)),
("NUMERIC(14,3)", dt.Decimal(14, 3)),
("SMALLINT", dt.int16),
("SMALLMONEY", dt.int32),
("TINYINT", dt.int8),
# Approximate numerics
("REAL", dt.float32),
("FLOAT", dt.float64),
("FLOAT(3)", dt.float32),
("FLOAT(25)", dt.float64),
# Date and time
("DATE", dt.date),
("TIME", dt.time),
("DATETIME2", dt.timestamp(scale=7)),
("DATETIMEOFFSET", dt.timestamp(scale=7, timezone="UTC")),
("SMALLDATETIME", dt.timestamp),
("DATETIME", dt.timestamp),
# Characters strings
("CHAR", dt.string),
("TEXT", dt.string),
("VARCHAR", dt.string),
# Unicode character strings
("NCHAR", dt.string),
("NTEXT", dt.string),
("NVARCHAR", dt.string),
# Binary strings
("BINARY", dt.binary),
("VARBINARY", dt.binary),
("IMAGE", dt.binary),
# Other data types
("UNIQUEIDENTIFIER", dt.uuid),
("TIMESTAMP", dt.binary(nullable=False)),
]
skipif_no_geospatial_deps = pytest.mark.skipif(
not geospatial_supported, reason="geospatial dependencies not installed"
)
broken_sqlalchemy_autoload = pytest.mark.xfail(
reason="scale not inferred by sqlalchemy autoload"
)
@pytest.mark.parametrize(
("server_type", "expected_type"),
DB_TYPES
+ [
param("GEOMETRY", dt.geometry, marks=[skipif_no_geospatial_deps]),
param("GEOGRAPHY", dt.geography, marks=[skipif_no_geospatial_deps]),
]
+ [
param(
"DATETIME2(4)", dt.timestamp(scale=4), marks=[broken_sqlalchemy_autoload]
),
param(
"DATETIMEOFFSET(5)",
dt.timestamp(scale=5, timezone="UTC"),
marks=[broken_sqlalchemy_autoload],
),
],
ids=str,
)
def test_get_schema_from_query(con, server_type, expected_type, temp_table):
expected_schema = ibis.schema(dict(x=expected_type))
with con.begin() as c:
c.exec_driver_sql(f"CREATE TABLE [{temp_table}] (x {server_type})")
expected_schema = ibis.schema(dict(x=expected_type))
result_schema = con._get_schema_using_query(f"SELECT * FROM [{temp_table}]")
assert result_schema == expected_schema
t = con.table(temp_table)
assert t.schema() == expected_schema
|
normal
|
{
"blob_id": "00e9872136e5753364117adbf60793e660c8bef0",
"index": 485,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\[email protected](('server_type', 'expected_type'), DB_TYPES + [\n param('GEOMETRY', dt.geometry, marks=[skipif_no_geospatial_deps]),\n param('GEOGRAPHY', dt.geography, marks=[skipif_no_geospatial_deps])] +\n [param('DATETIME2(4)', dt.timestamp(scale=4), marks=[\n broken_sqlalchemy_autoload]), param('DATETIMEOFFSET(5)', dt.timestamp(\n scale=5, timezone='UTC'), marks=[broken_sqlalchemy_autoload])], ids=str)\ndef test_get_schema_from_query(con, server_type, expected_type, temp_table):\n expected_schema = ibis.schema(dict(x=expected_type))\n with con.begin() as c:\n c.exec_driver_sql(f'CREATE TABLE [{temp_table}] (x {server_type})')\n expected_schema = ibis.schema(dict(x=expected_type))\n result_schema = con._get_schema_using_query(f'SELECT * FROM [{temp_table}]'\n )\n assert result_schema == expected_schema\n t = con.table(temp_table)\n assert t.schema() == expected_schema\n",
"step-3": "<mask token>\nDB_TYPES = [('BIGINT', dt.int64), ('BIT', dt.boolean), ('DECIMAL', dt.\n Decimal(precision=18, scale=0)), ('DECIMAL(5, 2)', dt.Decimal(precision\n =5, scale=2)), ('INT', dt.int32), ('MONEY', dt.int64), ('NUMERIC', dt.\n Decimal(18, 0)), ('NUMERIC(10,5)', dt.Decimal(10, 5)), ('NUMERIC(14,3)',\n dt.Decimal(14, 3)), ('SMALLINT', dt.int16), ('SMALLMONEY', dt.int32), (\n 'TINYINT', dt.int8), ('REAL', dt.float32), ('FLOAT', dt.float64), (\n 'FLOAT(3)', dt.float32), ('FLOAT(25)', dt.float64), ('DATE', dt.date),\n ('TIME', dt.time), ('DATETIME2', dt.timestamp(scale=7)), (\n 'DATETIMEOFFSET', dt.timestamp(scale=7, timezone='UTC')), (\n 'SMALLDATETIME', dt.timestamp), ('DATETIME', dt.timestamp), ('CHAR', dt\n .string), ('TEXT', dt.string), ('VARCHAR', dt.string), ('NCHAR', dt.\n string), ('NTEXT', dt.string), ('NVARCHAR', dt.string), ('BINARY', dt.\n binary), ('VARBINARY', dt.binary), ('IMAGE', dt.binary), (\n 'UNIQUEIDENTIFIER', dt.uuid), ('TIMESTAMP', dt.binary(nullable=False))]\nskipif_no_geospatial_deps = pytest.mark.skipif(not geospatial_supported,\n reason='geospatial dependencies not installed')\nbroken_sqlalchemy_autoload = pytest.mark.xfail(reason=\n 'scale not inferred by sqlalchemy autoload')\n\n\[email protected](('server_type', 'expected_type'), DB_TYPES + [\n param('GEOMETRY', dt.geometry, marks=[skipif_no_geospatial_deps]),\n param('GEOGRAPHY', dt.geography, marks=[skipif_no_geospatial_deps])] +\n [param('DATETIME2(4)', dt.timestamp(scale=4), marks=[\n broken_sqlalchemy_autoload]), param('DATETIMEOFFSET(5)', dt.timestamp(\n scale=5, timezone='UTC'), marks=[broken_sqlalchemy_autoload])], ids=str)\ndef test_get_schema_from_query(con, server_type, expected_type, temp_table):\n expected_schema = ibis.schema(dict(x=expected_type))\n with con.begin() as c:\n c.exec_driver_sql(f'CREATE TABLE [{temp_table}] (x {server_type})')\n expected_schema = ibis.schema(dict(x=expected_type))\n result_schema = con._get_schema_using_query(f'SELECT * FROM [{temp_table}]'\n )\n assert result_schema == expected_schema\n t = con.table(temp_table)\n assert t.schema() == expected_schema\n",
"step-4": "from __future__ import annotations\nimport pytest\nfrom pytest import param\nimport ibis\nimport ibis.expr.datatypes as dt\nfrom ibis.backends.base.sql.alchemy.geospatial import geospatial_supported\nDB_TYPES = [('BIGINT', dt.int64), ('BIT', dt.boolean), ('DECIMAL', dt.\n Decimal(precision=18, scale=0)), ('DECIMAL(5, 2)', dt.Decimal(precision\n =5, scale=2)), ('INT', dt.int32), ('MONEY', dt.int64), ('NUMERIC', dt.\n Decimal(18, 0)), ('NUMERIC(10,5)', dt.Decimal(10, 5)), ('NUMERIC(14,3)',\n dt.Decimal(14, 3)), ('SMALLINT', dt.int16), ('SMALLMONEY', dt.int32), (\n 'TINYINT', dt.int8), ('REAL', dt.float32), ('FLOAT', dt.float64), (\n 'FLOAT(3)', dt.float32), ('FLOAT(25)', dt.float64), ('DATE', dt.date),\n ('TIME', dt.time), ('DATETIME2', dt.timestamp(scale=7)), (\n 'DATETIMEOFFSET', dt.timestamp(scale=7, timezone='UTC')), (\n 'SMALLDATETIME', dt.timestamp), ('DATETIME', dt.timestamp), ('CHAR', dt\n .string), ('TEXT', dt.string), ('VARCHAR', dt.string), ('NCHAR', dt.\n string), ('NTEXT', dt.string), ('NVARCHAR', dt.string), ('BINARY', dt.\n binary), ('VARBINARY', dt.binary), ('IMAGE', dt.binary), (\n 'UNIQUEIDENTIFIER', dt.uuid), ('TIMESTAMP', dt.binary(nullable=False))]\nskipif_no_geospatial_deps = pytest.mark.skipif(not geospatial_supported,\n reason='geospatial dependencies not installed')\nbroken_sqlalchemy_autoload = pytest.mark.xfail(reason=\n 'scale not inferred by sqlalchemy autoload')\n\n\[email protected](('server_type', 'expected_type'), DB_TYPES + [\n param('GEOMETRY', dt.geometry, marks=[skipif_no_geospatial_deps]),\n param('GEOGRAPHY', dt.geography, marks=[skipif_no_geospatial_deps])] +\n [param('DATETIME2(4)', dt.timestamp(scale=4), marks=[\n broken_sqlalchemy_autoload]), param('DATETIMEOFFSET(5)', dt.timestamp(\n scale=5, timezone='UTC'), marks=[broken_sqlalchemy_autoload])], ids=str)\ndef test_get_schema_from_query(con, server_type, expected_type, temp_table):\n expected_schema = ibis.schema(dict(x=expected_type))\n with con.begin() as c:\n c.exec_driver_sql(f'CREATE TABLE [{temp_table}] (x {server_type})')\n expected_schema = ibis.schema(dict(x=expected_type))\n result_schema = con._get_schema_using_query(f'SELECT * FROM [{temp_table}]'\n )\n assert result_schema == expected_schema\n t = con.table(temp_table)\n assert t.schema() == expected_schema\n",
"step-5": "from __future__ import annotations\n\nimport pytest\nfrom pytest import param\n\nimport ibis\nimport ibis.expr.datatypes as dt\nfrom ibis.backends.base.sql.alchemy.geospatial import geospatial_supported\n\nDB_TYPES = [\n # Exact numbers\n (\"BIGINT\", dt.int64),\n (\"BIT\", dt.boolean),\n (\"DECIMAL\", dt.Decimal(precision=18, scale=0)),\n (\"DECIMAL(5, 2)\", dt.Decimal(precision=5, scale=2)),\n (\"INT\", dt.int32),\n (\"MONEY\", dt.int64),\n (\"NUMERIC\", dt.Decimal(18, 0)),\n (\"NUMERIC(10,5)\", dt.Decimal(10, 5)),\n (\"NUMERIC(14,3)\", dt.Decimal(14, 3)),\n (\"SMALLINT\", dt.int16),\n (\"SMALLMONEY\", dt.int32),\n (\"TINYINT\", dt.int8),\n # Approximate numerics\n (\"REAL\", dt.float32),\n (\"FLOAT\", dt.float64),\n (\"FLOAT(3)\", dt.float32),\n (\"FLOAT(25)\", dt.float64),\n # Date and time\n (\"DATE\", dt.date),\n (\"TIME\", dt.time),\n (\"DATETIME2\", dt.timestamp(scale=7)),\n (\"DATETIMEOFFSET\", dt.timestamp(scale=7, timezone=\"UTC\")),\n (\"SMALLDATETIME\", dt.timestamp),\n (\"DATETIME\", dt.timestamp),\n # Characters strings\n (\"CHAR\", dt.string),\n (\"TEXT\", dt.string),\n (\"VARCHAR\", dt.string),\n # Unicode character strings\n (\"NCHAR\", dt.string),\n (\"NTEXT\", dt.string),\n (\"NVARCHAR\", dt.string),\n # Binary strings\n (\"BINARY\", dt.binary),\n (\"VARBINARY\", dt.binary),\n (\"IMAGE\", dt.binary),\n # Other data types\n (\"UNIQUEIDENTIFIER\", dt.uuid),\n (\"TIMESTAMP\", dt.binary(nullable=False)),\n]\n\n\nskipif_no_geospatial_deps = pytest.mark.skipif(\n not geospatial_supported, reason=\"geospatial dependencies not installed\"\n)\n\nbroken_sqlalchemy_autoload = pytest.mark.xfail(\n reason=\"scale not inferred by sqlalchemy autoload\"\n)\n\n\[email protected](\n (\"server_type\", \"expected_type\"),\n DB_TYPES\n + [\n param(\"GEOMETRY\", dt.geometry, marks=[skipif_no_geospatial_deps]),\n param(\"GEOGRAPHY\", dt.geography, marks=[skipif_no_geospatial_deps]),\n ]\n + [\n param(\n \"DATETIME2(4)\", dt.timestamp(scale=4), marks=[broken_sqlalchemy_autoload]\n ),\n param(\n \"DATETIMEOFFSET(5)\",\n dt.timestamp(scale=5, timezone=\"UTC\"),\n marks=[broken_sqlalchemy_autoload],\n ),\n ],\n ids=str,\n)\ndef test_get_schema_from_query(con, server_type, expected_type, temp_table):\n expected_schema = ibis.schema(dict(x=expected_type))\n with con.begin() as c:\n c.exec_driver_sql(f\"CREATE TABLE [{temp_table}] (x {server_type})\")\n expected_schema = ibis.schema(dict(x=expected_type))\n result_schema = con._get_schema_using_query(f\"SELECT * FROM [{temp_table}]\")\n assert result_schema == expected_schema\n t = con.table(temp_table)\n assert t.schema() == expected_schema\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""
======================
@author:小谢学测试
@time:2021/9/8:8:34
@email:[email protected]
======================
"""
import pytest
# @pytest.fixture()
# def login():
# print("登录方法")
# def pytest_conftest(config):
# marker_list = ["search","login"]
# for markers in marker_list:
# config.addinivalue_line("markers",markers)
|
normal
|
{
"blob_id": "b52429f936013ac60659950492b67078fabf3a13",
"index": 4042,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nimport pytest\n",
"step-3": "\"\"\"\n======================\n@author:小谢学测试\n@time:2021/9/8:8:34\n@email:[email protected]\n======================\n\"\"\"\nimport pytest\n# @pytest.fixture()\n# def login():\n# print(\"登录方法\")\n\n# def pytest_conftest(config):\n# marker_list = [\"search\",\"login\"]\n# for markers in marker_list:\n# config.addinivalue_line(\"markers\",markers)",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import os
from distutils.core import Extension
REPROJECT_ROOT = os.path.relpath(os.path.dirname(__file__))
def get_extensions():
libraries = []
sources = []
sources.append(os.path.join(REPROJECT_ROOT, "_overlap.c"))
sources.append(os.path.join(REPROJECT_ROOT, "overlapArea.c"))
sources.append(os.path.join(REPROJECT_ROOT, "reproject_slice_c.c"))
include_dirs = ['numpy']
include_dirs.append(REPROJECT_ROOT)
extension = Extension(
name="reproject.spherical_intersect._overlap",
sources=sources,
include_dirs=include_dirs,
libraries=libraries,
language="c",
extra_compile_args=['-O2'])
return [extension]
def get_package_data():
header_files = ['overlapArea.h', 'reproject_slice_c.h', 'mNaN.h']
return {'reproject.spherical_intersect': header_files}
|
normal
|
{
"blob_id": "ad079876476f6f291ad52aece8d0d5afdd5a8bcf",
"index": 9892,
"step-1": "<mask token>\n\n\ndef get_extensions():\n libraries = []\n sources = []\n sources.append(os.path.join(REPROJECT_ROOT, '_overlap.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'overlapArea.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'reproject_slice_c.c'))\n include_dirs = ['numpy']\n include_dirs.append(REPROJECT_ROOT)\n extension = Extension(name='reproject.spherical_intersect._overlap',\n sources=sources, include_dirs=include_dirs, libraries=libraries,\n language='c', extra_compile_args=['-O2'])\n return [extension]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_extensions():\n libraries = []\n sources = []\n sources.append(os.path.join(REPROJECT_ROOT, '_overlap.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'overlapArea.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'reproject_slice_c.c'))\n include_dirs = ['numpy']\n include_dirs.append(REPROJECT_ROOT)\n extension = Extension(name='reproject.spherical_intersect._overlap',\n sources=sources, include_dirs=include_dirs, libraries=libraries,\n language='c', extra_compile_args=['-O2'])\n return [extension]\n\n\ndef get_package_data():\n header_files = ['overlapArea.h', 'reproject_slice_c.h', 'mNaN.h']\n return {'reproject.spherical_intersect': header_files}\n",
"step-3": "<mask token>\nREPROJECT_ROOT = os.path.relpath(os.path.dirname(__file__))\n\n\ndef get_extensions():\n libraries = []\n sources = []\n sources.append(os.path.join(REPROJECT_ROOT, '_overlap.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'overlapArea.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'reproject_slice_c.c'))\n include_dirs = ['numpy']\n include_dirs.append(REPROJECT_ROOT)\n extension = Extension(name='reproject.spherical_intersect._overlap',\n sources=sources, include_dirs=include_dirs, libraries=libraries,\n language='c', extra_compile_args=['-O2'])\n return [extension]\n\n\ndef get_package_data():\n header_files = ['overlapArea.h', 'reproject_slice_c.h', 'mNaN.h']\n return {'reproject.spherical_intersect': header_files}\n",
"step-4": "import os\nfrom distutils.core import Extension\nREPROJECT_ROOT = os.path.relpath(os.path.dirname(__file__))\n\n\ndef get_extensions():\n libraries = []\n sources = []\n sources.append(os.path.join(REPROJECT_ROOT, '_overlap.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'overlapArea.c'))\n sources.append(os.path.join(REPROJECT_ROOT, 'reproject_slice_c.c'))\n include_dirs = ['numpy']\n include_dirs.append(REPROJECT_ROOT)\n extension = Extension(name='reproject.spherical_intersect._overlap',\n sources=sources, include_dirs=include_dirs, libraries=libraries,\n language='c', extra_compile_args=['-O2'])\n return [extension]\n\n\ndef get_package_data():\n header_files = ['overlapArea.h', 'reproject_slice_c.h', 'mNaN.h']\n return {'reproject.spherical_intersect': header_files}\n",
"step-5": "import os\nfrom distutils.core import Extension\n\nREPROJECT_ROOT = os.path.relpath(os.path.dirname(__file__))\n\n\ndef get_extensions():\n\n libraries = []\n\n sources = []\n sources.append(os.path.join(REPROJECT_ROOT, \"_overlap.c\"))\n sources.append(os.path.join(REPROJECT_ROOT, \"overlapArea.c\"))\n sources.append(os.path.join(REPROJECT_ROOT, \"reproject_slice_c.c\"))\n\n include_dirs = ['numpy']\n include_dirs.append(REPROJECT_ROOT)\n\n extension = Extension(\n name=\"reproject.spherical_intersect._overlap\",\n sources=sources,\n include_dirs=include_dirs,\n libraries=libraries,\n language=\"c\",\n extra_compile_args=['-O2'])\n\n return [extension]\n\n\ndef get_package_data():\n\n header_files = ['overlapArea.h', 'reproject_slice_c.h', 'mNaN.h']\n\n return {'reproject.spherical_intersect': header_files}\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
HORIZONTAL_TABLE = b'\x09'
class ReagentInfoItem():
'''
This class if defined for a single reagent info unit, from the table's view, its a cell of the table.
'''
def __init__(self, reagent_name, reagent_count):
self.reagent_name = reagent_name
self.reagent_count = reagent_count
def __repr__(self):
return 'reagent name: ' + self.reagent_name + HORIZONTAL_TABLE +\
'reagent count: ' + str(self.reagent_count)
class InstrumentReagentInfo():
'''
This class is defined for single instrument,from the table's view, its a column of the reagent info table.
'''
def __init__(self, instr_id, instr_type, time_stamp=None, reagent_info_list=[]):
'''
Instrument_Id: str
Instrument_Type: str
Reagent_Info_List: ReagentInfoItem[]
'''
self.instrument_id = instr_id
self.instrument_type = instr_type
self.time_stamp = time_stamp
self.reagent_info_list = reagent_info_list
def __repr__(self):
return 'instrument id: '+ self.instrument_id + HORIZONTAL_TABLE +\
'instrument type: ' + self.instrument_type + HORIZONTAL_TABLE+\
'updated timestamp: ' + str(self.time_stamp) + HORIZONTAL_TABLE+\
'\nreagent inventory info:\n' + '\n'.join(str(item) for item in self.reagent_info_list)
class SystemReagentInfo():
'''
Reagent information of the whole system
'''
def __init__(self):
self.system_reagent = []
def update_instrument_reagent_inventory(self,instrument_reagent_invemtory):
if isinstance(instrument_reagent_invemtory,InstrumentReagentInfo):
if not self.get_last_update_timestamp_per_instrument(instrument_reagent_invemtory.instrument_id) or \
self.get_last_update_timestamp_per_instrument(instrument_reagent_invemtory.instrument_id)<instrument_reagent_invemtory.time_stamp:
old_record = self.get_instrument_reagent_inventory_item_by_id(instrument_reagent_invemtory.instrument_id)
if old_record:
old_record = instrument_reagent_invemtory
else:
self.system_reagent.append(instrument_reagent_invemtory)
def get_instrument_reagent_inventory_item_by_id(self,instr_id):
for item in self.system_reagent:
if isinstance(item,InstrumentReagentInfo):
if item.instrument_id == instr_id:
return item
def get_last_update_timestamp_per_instrument(self,instr_id):
for item in self.system_reagent:
if isinstance(item,InstrumentReagentInfo):
if item.instrument_id == instr_id:
return item.time_stamp
def __repr__(self):
return 'system reagent info:\n' +'\n'.join(str(item) for item in self.system_reagent)
def test01():
ReagentInfoItem11 = ReagentInfoItem('dai', 12)
ReagentInfoItem12 = ReagentInfoItem('han', 13)
ReagentInfoItem13 = ReagentInfoItem('peng', 14)
ReagentInfoList1 = [ReagentInfoItem11, ReagentInfoItem12, ReagentInfoItem13]
ReagentInfoItem21 = ReagentInfoItem('I', 32)
ReagentInfoItem22 = ReagentInfoItem('love', 33)
ReagentInfoItem23 = ReagentInfoItem('python', 34)
ReagentInfoList2 = [ReagentInfoItem21, ReagentInfoItem22, ReagentInfoItem23]
# 'normal testing, below info should be updated:'
InstrumentInfo1 = InstrumentReagentInfo('5', 'A24', '20160101110909', ReagentInfoList1)
InstrumentInfo2 = InstrumentReagentInfo('7', 'CEN', '20151212090923', ReagentInfoList2)
# 'abnormal testing, below info should not be updated:'
InstrumentInfo3 = InstrumentReagentInfo('5', 'A24', '20150101110909', ReagentInfoList2)
aptioReagentInfo = SystemReagentInfo()
aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo1)
aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo2)
aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo3)
print aptioReagentInfo
def test02():
from datetime import datetime
dt1 = '20141117100340'
dt = datetime.strptime(dt1,'%Y%m%d%H%M%S')
print dt < None
if __name__ == '__main__':
test02()
|
normal
|
{
"blob_id": "994210b3de82af02ec7b1b7bee75ceb88ffb2bd5",
"index": 2491,
"step-1": "\nHORIZONTAL_TABLE = b'\\x09'\n\nclass ReagentInfoItem():\n '''\n This class if defined for a single reagent info unit, from the table's view, its a cell of the table.\n '''\n def __init__(self, reagent_name, reagent_count):\n self.reagent_name = reagent_name\n self.reagent_count = reagent_count\n\n def __repr__(self):\n return 'reagent name: ' + self.reagent_name + HORIZONTAL_TABLE +\\\n 'reagent count: ' + str(self.reagent_count)\n\n\nclass InstrumentReagentInfo():\n '''\n This class is defined for single instrument,from the table's view, its a column of the reagent info table.\n '''\n def __init__(self, instr_id, instr_type, time_stamp=None, reagent_info_list=[]):\n '''\n Instrument_Id: str\n Instrument_Type: str\n Reagent_Info_List: ReagentInfoItem[]\n '''\n self.instrument_id = instr_id\n self.instrument_type = instr_type\n self.time_stamp = time_stamp\n self.reagent_info_list = reagent_info_list\n\n def __repr__(self):\n return 'instrument id: '+ self.instrument_id + HORIZONTAL_TABLE +\\\n 'instrument type: ' + self.instrument_type + HORIZONTAL_TABLE+\\\n 'updated timestamp: ' + str(self.time_stamp) + HORIZONTAL_TABLE+\\\n '\\nreagent inventory info:\\n' + '\\n'.join(str(item) for item in self.reagent_info_list)\n\n\nclass SystemReagentInfo():\n '''\n Reagent information of the whole system\n '''\n def __init__(self):\n self.system_reagent = []\n\n def update_instrument_reagent_inventory(self,instrument_reagent_invemtory):\n if isinstance(instrument_reagent_invemtory,InstrumentReagentInfo):\n if not self.get_last_update_timestamp_per_instrument(instrument_reagent_invemtory.instrument_id) or \\\n self.get_last_update_timestamp_per_instrument(instrument_reagent_invemtory.instrument_id)<instrument_reagent_invemtory.time_stamp:\n old_record = self.get_instrument_reagent_inventory_item_by_id(instrument_reagent_invemtory.instrument_id)\n if old_record:\n old_record = instrument_reagent_invemtory\n else:\n self.system_reagent.append(instrument_reagent_invemtory)\n\n def get_instrument_reagent_inventory_item_by_id(self,instr_id):\n for item in self.system_reagent:\n if isinstance(item,InstrumentReagentInfo):\n if item.instrument_id == instr_id:\n return item\n\n def get_last_update_timestamp_per_instrument(self,instr_id):\n for item in self.system_reagent:\n if isinstance(item,InstrumentReagentInfo):\n if item.instrument_id == instr_id:\n return item.time_stamp\n\n def __repr__(self):\n return 'system reagent info:\\n' +'\\n'.join(str(item) for item in self.system_reagent)\n\n\ndef test01():\n ReagentInfoItem11 = ReagentInfoItem('dai', 12)\n ReagentInfoItem12 = ReagentInfoItem('han', 13)\n ReagentInfoItem13 = ReagentInfoItem('peng', 14)\n ReagentInfoList1 = [ReagentInfoItem11, ReagentInfoItem12, ReagentInfoItem13]\n\n ReagentInfoItem21 = ReagentInfoItem('I', 32)\n ReagentInfoItem22 = ReagentInfoItem('love', 33)\n ReagentInfoItem23 = ReagentInfoItem('python', 34)\n ReagentInfoList2 = [ReagentInfoItem21, ReagentInfoItem22, ReagentInfoItem23]\n\n # 'normal testing, below info should be updated:'\n InstrumentInfo1 = InstrumentReagentInfo('5', 'A24', '20160101110909', ReagentInfoList1)\n InstrumentInfo2 = InstrumentReagentInfo('7', 'CEN', '20151212090923', ReagentInfoList2)\n # 'abnormal testing, below info should not be updated:'\n InstrumentInfo3 = InstrumentReagentInfo('5', 'A24', '20150101110909', ReagentInfoList2)\n\n aptioReagentInfo = SystemReagentInfo()\n\n aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo1)\n aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo2)\n\n aptioReagentInfo.update_instrument_reagent_inventory(InstrumentInfo3)\n\n print aptioReagentInfo\n\ndef test02():\n from datetime import datetime\n dt1 = '20141117100340'\n dt = datetime.strptime(dt1,'%Y%m%d%H%M%S')\n print dt < None\n\nif __name__ == '__main__':\n test02()",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
# TODO - let user input file name on command line
level_file = 'level.txt'
# read characters in level.txt into
# terrain map
# which is array of columns
f = open(level_file)
terrain_map = []
for row in f:
col_index = 0
row_index = 0
for tile in row.rstrip():
if col_index == len(terrain_map):
terrain_map.append([])
terrain_map[col_index].append(tile)
col_index += 1
row_index += 1
f.close()
# print(terrain_map)
def map_tile_char_to_terrain(tile):
if tile == 'M':
return "dirt"
if tile == 'R':
return "rock"
if tile == 'D':
return "data"
if tile == 'B':
return "empty"
if tile == "P":
return "solar"
return "dirt"
def output_terrain_column(column):
n = len(column)
print('[')
for i, tile in enumerate(column):
print(' {')
print(' "tex": "' + map_tile_char_to_terrain(tile) + '"')
if i + 1 < n:
print(' },')
else:
print(' }')
print(']')
def print_entities():
print """\
"entities": [
{
"x": 0,
"y": 0,
"rot": 0,
"tex": "rover",
"name": "rover",
"inherits": {
"Accessible": [
"Bots"
],
"Rover": {
"moveSFX": "move"
}
}
}
],
"""
def print_footer():
# TODO add other textures
print """
"tex": {
"rover": "/images/rover.png",
"dirt": "/images/mars.png",
"rock": "/images/mars_rock.png",
"blank": "/images/blank.png",
"solar": "/images/panel.png",
"data": "/images/data_drive.png"
},
"sfx": {
"botMove": "/audio/"
},
"meta": {
"title": "Getting started",
"desc": "Learn the basics of javascript and how to control a bot"
}
"""
# output terrain map by columns
print("{")
print(' "tests": [')
print(' {')
print_entities()
print(' "terrain": [')
num_cols = len(terrain_map)
for i, column in enumerate(terrain_map):
output_terrain_column(column)
if i + 1 < num_cols:
print(',')
print(' ]')
print(' }')
print(' ]')
print(',')
print_footer()
print("}")
|
normal
|
{
"blob_id": "fe1cc7660396071172c1ec65ba685e677e497646",
"index": 6354,
"step-1": "# TODO - let user input file name on command line\n\nlevel_file = 'level.txt'\n\n# read characters in level.txt into\n# terrain map\n# which is array of columns\nf = open(level_file)\nterrain_map = []\nfor row in f:\n\tcol_index = 0\n\trow_index = 0\n\tfor tile in row.rstrip():\n\t\tif col_index == len(terrain_map):\n\t\t\tterrain_map.append([])\n\t\tterrain_map[col_index].append(tile)\n\t\tcol_index += 1\n\trow_index += 1\nf.close()\n\n# print(terrain_map)\n\ndef map_tile_char_to_terrain(tile):\n\tif tile == 'M':\n\t\treturn \"dirt\"\n\tif tile == 'R':\n\t\treturn \"rock\"\n\tif tile == 'D':\n\t\treturn \"data\"\n\tif tile == 'B':\n\t\treturn \"empty\"\n\tif tile == \"P\":\n\t\treturn \"solar\"\n\treturn \"dirt\"\n\ndef output_terrain_column(column):\n\tn = len(column)\n\tprint('[')\n\tfor i, tile in enumerate(column):\n\t\tprint(' {')\n\t\tprint(' \"tex\": \"' + map_tile_char_to_terrain(tile) + '\"')\n\t\tif i + 1 < n:\n\t\t\tprint(' },')\n\t\telse:\n\t\t\tprint(' }')\n\tprint(']')\n\ndef print_entities():\n\tprint \"\"\"\\\n\t\"entities\": [\n {\n \"x\": 0,\n \"y\": 0,\n \"rot\": 0,\n \"tex\": \"rover\",\n \"name\": \"rover\",\n \"inherits\": {\n\t\t\t\"Accessible\": [\n\t\t\t\t\"Bots\"\n\t\t\t],\n \"Rover\": {\n \"moveSFX\": \"move\"\n }\n }\n }\n ],\n\t \"\"\"\n\ndef print_footer():\n\t# TODO add other textures\n\tprint \"\"\"\n\t\"tex\": {\n\t\t\"rover\": \"/images/rover.png\",\n \"dirt\": \"/images/mars.png\",\n \"rock\": \"/images/mars_rock.png\",\n \"blank\": \"/images/blank.png\",\n \"solar\": \"/images/panel.png\",\n \"data\": \"/images/data_drive.png\"\n\t},\n\t\"sfx\": {\n\t\t\"botMove\": \"/audio/\"\n\t},\n\t\"meta\": {\n\t\t\"title\": \"Getting started\",\n\t\t\"desc\": \"Learn the basics of javascript and how to control a bot\"\n\t}\n\t\"\"\"\n\n\n# output terrain map by columns\nprint(\"{\")\nprint(' \"tests\": [')\nprint(' {')\n\nprint_entities()\n\nprint(' \"terrain\": [')\n\nnum_cols = len(terrain_map)\nfor i, column in enumerate(terrain_map):\n\toutput_terrain_column(column)\n\tif i + 1 < num_cols:\n\t\tprint(',')\n\nprint(' ]')\nprint(' }')\nprint(' ]')\n\nprint(',')\n\nprint_footer()\n\nprint(\"}\")",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from scipy.misc import imread
import os
import numpy as np
files = [ "oracle.PNG",
"SQL.jpg" ]
def plotImage(f):
folder = "C:/temp/"
im = imread(os.path.join(folder, f)).astype(np.float32) / 255
plt.imshow(im)
a = plt.gca()
a.get_xaxis().set_visible(False) # We don't need axis ticks
a.get_yaxis().set_visible(False)
pp = PdfPages("c:/temp/page1.pdf")
plt.subplot(121)
plotImage(files[0])
plt.subplot(122)
plotImage(files[1])
pp.savefig(plt.gcf()) # This generates page 1
pp.savefig(plt.gcf()) # This generates page 2
pp.close()
|
normal
|
{
"blob_id": "146db68fb84569b914fa741457c595108088dc63",
"index": 7199,
"step-1": "<mask token>\n\n\ndef plotImage(f):\n folder = 'C:/temp/'\n im = imread(os.path.join(folder, f)).astype(np.float32) / 255\n plt.imshow(im)\n a = plt.gca()\n a.get_xaxis().set_visible(False)\n a.get_yaxis().set_visible(False)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef plotImage(f):\n folder = 'C:/temp/'\n im = imread(os.path.join(folder, f)).astype(np.float32) / 255\n plt.imshow(im)\n a = plt.gca()\n a.get_xaxis().set_visible(False)\n a.get_yaxis().set_visible(False)\n\n\n<mask token>\nplt.subplot(121)\nplotImage(files[0])\nplt.subplot(122)\nplotImage(files[1])\npp.savefig(plt.gcf())\npp.savefig(plt.gcf())\npp.close()\n",
"step-3": "<mask token>\nfiles = ['oracle.PNG', 'SQL.jpg']\n\n\ndef plotImage(f):\n folder = 'C:/temp/'\n im = imread(os.path.join(folder, f)).astype(np.float32) / 255\n plt.imshow(im)\n a = plt.gca()\n a.get_xaxis().set_visible(False)\n a.get_yaxis().set_visible(False)\n\n\npp = PdfPages('c:/temp/page1.pdf')\nplt.subplot(121)\nplotImage(files[0])\nplt.subplot(122)\nplotImage(files[1])\npp.savefig(plt.gcf())\npp.savefig(plt.gcf())\npp.close()\n",
"step-4": "from matplotlib.backends.backend_pdf import PdfPages\nimport matplotlib.pyplot as plt\nfrom scipy.misc import imread\nimport os\nimport numpy as np\nfiles = ['oracle.PNG', 'SQL.jpg']\n\n\ndef plotImage(f):\n folder = 'C:/temp/'\n im = imread(os.path.join(folder, f)).astype(np.float32) / 255\n plt.imshow(im)\n a = plt.gca()\n a.get_xaxis().set_visible(False)\n a.get_yaxis().set_visible(False)\n\n\npp = PdfPages('c:/temp/page1.pdf')\nplt.subplot(121)\nplotImage(files[0])\nplt.subplot(122)\nplotImage(files[1])\npp.savefig(plt.gcf())\npp.savefig(plt.gcf())\npp.close()\n",
"step-5": "from matplotlib.backends.backend_pdf import PdfPages\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.misc import imread\r\nimport os\r\nimport numpy as np\r\n\r\nfiles = [ \"oracle.PNG\",\r\n \"SQL.jpg\" ]\r\ndef plotImage(f):\r\n folder = \"C:/temp/\"\r\n im = imread(os.path.join(folder, f)).astype(np.float32) / 255\r\n plt.imshow(im)\r\n a = plt.gca()\r\n a.get_xaxis().set_visible(False) # We don't need axis ticks\r\n a.get_yaxis().set_visible(False)\r\n\r\npp = PdfPages(\"c:/temp/page1.pdf\")\r\nplt.subplot(121)\r\nplotImage(files[0])\r\nplt.subplot(122)\r\nplotImage(files[1])\r\npp.savefig(plt.gcf()) # This generates page 1\r\npp.savefig(plt.gcf()) # This generates page 2\r\n\r\npp.close()\r\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# coding=utf8
# encoding: utf-8
import os
import platform
import re
import signal
import sys
import traceback
from subprocess import Popen, PIPE
from threading import Thread, current_thread
from Queue import Queue
from util.log import get_logger, log
from video.models import Video, KeywordVideoId
from django.db.models import Max
from collect_video import G_GEN_IMAGE
MAX_THREAD_NUM = 4
THREAD_STOP_FLAGS = []
THUMB_DIR = './static/thumb'
THUMB_SIZE = '180x135'
COVER_DIR = './static/cover'
FLIP_DIR = './static/flip'
FLIP_NUM = 10
task_queue = Queue(maxsize=2000)
def register_int_signal_handler():
def stop_thread_handler(signum, frame):
log.info("Received signal {0}. Will stop all task threads".format(signum))
for _ in range(len(THREAD_STOP_FLAGS)):
THREAD_STOP_FLAGS[_] = True
if platform.platform().startswith('Windows'):
signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)
else:
signal.signal(signal.SIGINT, stop_thread_handler)
def next_video_id(current, path):
existing = Video.objects.filter(path=path)
if existing:
return existing[0].video_id, current
current += 1
return current, current
def create_task_list(path_list):
"""
Walks path recursively, and create a task list
:param path_list: a list of (path, rating)
:return: a list of ImportTask objects
"""
current_video_id = Video.objects.all().aggregate(Max('video_id'))['video_id__max']
if not current_video_id:
current_video_id = 0
task_list = []
for (path, rating) in path_list:
base_path = os.path.split(path)[0]
if os.path.isfile(path):
file_name = os.path.basename(path)
if is_valid_video_file(path, file_name):
video_id, current_video_id = next_video_id(current_video_id, path)
task_list.append(ImportTask(video_id, base_path, path, rating))
continue
for (root, dirs, files) in os.walk(path):
for file_name in files:
try:
file_path = os.path.join(root, file_name)
if os.path.isdir(file_path):
continue
if is_valid_video_file(file_path, file_name):
video_id, current_video_id = next_video_id(current_video_id, file_path)
task_list.append(ImportTask(video_id, base_path, file_path, rating))
except:
log.error('#Error while proceeding: {0}'.format(file_name))
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
return task_list
def start_tasks(task_list):
global task_queue
for task in task_list:
task_queue.put(task)
if not THREAD_STOP_FLAGS:
for _ in range(MAX_THREAD_NUM):
THREAD_STOP_FLAGS.append(True)
if not os.path.isdir(COVER_DIR):
os.mkdir(COVER_DIR)
if not os.path.isdir(THUMB_DIR):
os.mkdir(THUMB_DIR)
if not os.path.isdir(FLIP_DIR):
os.mkdir(FLIP_DIR)
for _ in range(MAX_THREAD_NUM):
if THREAD_STOP_FLAGS[_]:
t = Thread(target=import_worker, kwargs={'thread_index': _})
t.name = str(_)
t.daemon = False
t.start()
task_queue.join()
def add_keywords_to_db(task_list):
blacklist = load_keyword_blacklist_from_file()
for task in task_list:
base_path = task.base_path
file_path = task.file_path
video_id = task.video_id
keywords = get_keywords(base_path, file_path, blacklist)
log.info('#Keywords:'.format(keywords))
for key in keywords:
try:
if KeywordVideoId.objects.filter(keyword=key, video_id=video_id):
log.info("Existing keyword {0} for {1}".format(key, video_id))
continue
keyword_record = KeywordVideoId()
keyword_record.keyword = key
keyword_record.video = Video.objects.get(video_id=video_id)
keyword_record.save()
log.info('#Added keyword:{0} for video_id: {1}'.format(key, video_id))
except Exception as e:
log.error("Error while adding keyword {0} to video {1}: {2}".format(key, video_id, e))
class ImportTask(object):
def __init__(self, video_id, base_path, path, rating=Video.P):
"""
Create an import task object.
:param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.
:param base_path: path prefix that will be ignored when creating keywords from path.
:param path: path of the file
:param rating: rating of the video, highest by default.
"""
self.video_id = video_id
self.base_path = base_path
self.file_path = path
self.rating = rating
def import_worker(thread_index):
"""
Thread worker that deals with tasks.
:return:
"""
THREAD_STOP_FLAGS[thread_index] = False
while not (THREAD_STOP_FLAGS[thread_index] or task_queue.empty()):
task = task_queue.get()
do_import_video_task(task)
task_queue.task_done()
THREAD_STOP_FLAGS[thread_index] = True
def do_import_video_task(task):
video_id = task.video_id
file_path = task.file_path
rating = task.rating
file_name = os.path.basename(file_path)[:-4]
tlog = get_logger(current_thread().name)
videos = Video.objects.filter(path=file_path)
if videos:
tlog.info("Existing video: {0}".format(task.file_path))
return
video = Video()
video.video_id = video_id
video.rating = rating
thumb_path = get_thumb_path(video.video_id)
cover_path = get_cover_path(video.video_id)
if not gen_cover(task.file_path, cover_path):
tlog.error("Failed to gen cover for {0}".format(file_path))
return
success, duration = gen_thumb(file_path, thumb_path)
if success:
if not gen_flips(file_path, video.video_id, duration, FLIP_DIR, FLIP_NUM):
tlog.error("Failed to gen flips for {0}".format(file_path))
else:
tlog.error("Failed to gen thumb for {0}".format(file_path))
video.title = file_name
video.path = file_path
video.duration = duration
video.save()
tlog.info('#Video: {0} [{1}] {2}'.format(video.title, video.duration, video.path))
def is_valid_video_file(file_path, file_name):
# skip hidden files (possibly not valid video files)
if file_name.startswith('.') or (not file_name.endswith('.mp4')):
return False
if os.path.getsize(file_path) == 0:
log.info('Remove invalid video file: {0}'.format(file_path))
os.remove(file_path)
return False
return True
def load_keyword_blacklist_from_file():
blacklist = set()
keyword_file = 'keywords.blacklist'
try:
with open(keyword_file, 'r') as kfp:
for line in kfp:
line = line.strip('\n')
if line:
blacklist.add(line)
log.info("Keywords blacklist: {0}".format(blacklist))
except Exception as e:
log.error("Error while processing {0}:{1}".format(keyword_file, e))
return blacklist
def get_keywords(prefix, file_path, blacklist):
"""
Get keywords from file path
:param prefix: Prefix of the dir path, so we can ignore them
:param file_path: full path of the video file
:param blacklist: A set of words/symbols that should be ignored
:return: a list of keywords
"""
file_path = str(file_path).replace(prefix, '') # remove base_dir from file_path
file_path = os.path.splitext(file_path)[0] # Only keep the part without extension
file_path = str(file_path).lower()
for bad_keyword in blacklist:
file_path = file_path.replace(bad_keyword, ' ')
file_path = re.sub(r'\s+', ' ', file_path) # Replace multiple spaces to single one
keywords = file_path.split(' ')
keywords = [k for k in keywords if k]
return keywords
class KeywordDictDataObj(object):
def __init__(self):
self.count = 0
self.files = set()
def get_thumb_path(fn):
return './static/thumb/' + str(fn) + '.png'
def get_cover_path(fn):
return './static/cover/' + str(fn) + '.png'
def gen_thumb(video_path, thumb_path):
"""
Generate thumb image for the given video, and grabs duration from output
:return: (success, duration)
"""
if os.path.isfile(thumb_path):
os.remove(thumb_path)
global THUMB_SIZE
cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1', '-f', 'apng', '-s', THUMB_SIZE, thumb_path]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output = p.communicate()[1]
duration = search_duration_from_text(output)
if not duration:
tlog = get_logger(current_thread().name)
tlog.error("Failed to find duration for {0}".format(video_path))
duration = 0
return p.returncode == 0, duration
def gen_flips(video_path, video_id, duration, flip_path, flip_num):
"""
Generate flips for the given video
:param video_path: path of the video
:param video_id: id of the file
:param duration: duration of video in seconds
:param flip_path: path dir to put the flips
:param flip_num: number of flips to generate
:return: True on success, False otherwise
"""
if not G_GEN_IMAGE:
return True
duration = float(duration)
flip_num = float(flip_num)
interval = duration / flip_num
if interval <= 0.0:
tlog = get_logger(current_thread().name)
tlog.error("Cannot generate flips. Duration: {0} FlipNum:{1}".format(duration, flip_num))
return False
fps = 'fps=1/' + str(interval)
global THUMB_SIZE
flip_path = os.path.join(flip_path, str(video_id))
for _ in range(FLIP_NUM+3):
flip_file = "{0}-{1}.png".format(flip_path, _)
if os.path.isfile(flip_file):
os.remove(flip_file)
flip_path_template = flip_path + '-%d.png'
cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE, flip_path_template]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
def gen_cover(video_path, cover_path):
if not G_GEN_IMAGE:
return True
if os.path.isfile(cover_path):
os.remove(cover_path)
cmd = ['ffmpeg', '-itsoffset', '-1', '-i', video_path, '-vframes', '1', '-f', 'apng', cover_path]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
# Convert video to mp4
def convert_video_to_mp4(video_path, dest_path):
tlog = get_logger(current_thread().name)
if os.path.isfile(dest_path):
tlog.info('#Already converted, skip: {0}'.format(dest_path))
return True
tlog.info('#Converting: {0} => {1}\n', video_path, dest_path)
cmd = ['ffmpeg', '-i', video_path, '-vcodec', 'h264', '-acodec', 'aac', dest_path]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
# Search the duration from given text
def search_duration_from_text(text):
# Match pattern like Duration: 00:24:14.91, s
regExp = re.compile(r'Duration: (\d{2}):(\d{2}):(\d{2})')
result = regExp.search(text, re.M | re.U)
if result is not None:
(hour, min, sec) = result.groups()
duration = int(hour) * 3600 + int(min) * 60 + int(sec)
return duration
return None
|
normal
|
{
"blob_id": "fbd5400823a8148adf358a2acc58fde146a25313",
"index": 2275,
"step-1": "<mask token>\n\n\ndef register_int_signal_handler():\n\n def stop_thread_handler(signum, frame):\n log.info('Received signal {0}. Will stop all task threads'.format(\n signum))\n for _ in range(len(THREAD_STOP_FLAGS)):\n THREAD_STOP_FLAGS[_] = True\n if platform.platform().startswith('Windows'):\n signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)\n else:\n signal.signal(signal.SIGINT, stop_thread_handler)\n\n\n<mask token>\n\n\ndef create_task_list(path_list):\n \"\"\"\n Walks path recursively, and create a task list\n :param path_list: a list of (path, rating)\n :return: a list of ImportTask objects\n \"\"\"\n current_video_id = Video.objects.all().aggregate(Max('video_id'))[\n 'video_id__max']\n if not current_video_id:\n current_video_id = 0\n task_list = []\n for path, rating in path_list:\n base_path = os.path.split(path)[0]\n if os.path.isfile(path):\n file_name = os.path.basename(path)\n if is_valid_video_file(path, file_name):\n video_id, current_video_id = next_video_id(current_video_id,\n path)\n task_list.append(ImportTask(video_id, base_path, path, rating))\n continue\n for root, dirs, files in os.walk(path):\n for file_name in files:\n try:\n file_path = os.path.join(root, file_name)\n if os.path.isdir(file_path):\n continue\n if is_valid_video_file(file_path, file_name):\n video_id, current_video_id = next_video_id(\n current_video_id, file_path)\n task_list.append(ImportTask(video_id, base_path,\n file_path, rating))\n except:\n log.error('#Error while proceeding: {0}'.format(file_name))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value,\n exc_traceback, limit=2, file=sys.stdout)\n return task_list\n\n\ndef start_tasks(task_list):\n global task_queue\n for task in task_list:\n task_queue.put(task)\n if not THREAD_STOP_FLAGS:\n for _ in range(MAX_THREAD_NUM):\n THREAD_STOP_FLAGS.append(True)\n if not os.path.isdir(COVER_DIR):\n os.mkdir(COVER_DIR)\n if not os.path.isdir(THUMB_DIR):\n os.mkdir(THUMB_DIR)\n if not os.path.isdir(FLIP_DIR):\n os.mkdir(FLIP_DIR)\n for _ in range(MAX_THREAD_NUM):\n if THREAD_STOP_FLAGS[_]:\n t = Thread(target=import_worker, kwargs={'thread_index': _})\n t.name = str(_)\n t.daemon = False\n t.start()\n task_queue.join()\n\n\n<mask token>\n\n\nclass ImportTask(object):\n\n def __init__(self, video_id, base_path, path, rating=Video.P):\n \"\"\"\n Create an import task object.\n :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.\n :param base_path: path prefix that will be ignored when creating keywords from path.\n :param path: path of the file\n :param rating: rating of the video, highest by default.\n \"\"\"\n self.video_id = video_id\n self.base_path = base_path\n self.file_path = path\n self.rating = rating\n\n\n<mask token>\n\n\ndef is_valid_video_file(file_path, file_name):\n if file_name.startswith('.') or not file_name.endswith('.mp4'):\n return False\n if os.path.getsize(file_path) == 0:\n log.info('Remove invalid video file: {0}'.format(file_path))\n os.remove(file_path)\n return False\n return True\n\n\ndef load_keyword_blacklist_from_file():\n blacklist = set()\n keyword_file = 'keywords.blacklist'\n try:\n with open(keyword_file, 'r') as kfp:\n for line in kfp:\n line = line.strip('\\n')\n if line:\n blacklist.add(line)\n log.info('Keywords blacklist: {0}'.format(blacklist))\n except Exception as e:\n log.error('Error while processing {0}:{1}'.format(keyword_file, e))\n return blacklist\n\n\ndef get_keywords(prefix, file_path, blacklist):\n \"\"\"\n Get keywords from file path\n :param prefix: Prefix of the dir path, so we can ignore them\n :param file_path: full path of the video file\n :param blacklist: A set of words/symbols that should be ignored\n :return: a list of keywords\n \"\"\"\n file_path = str(file_path).replace(prefix, '')\n file_path = os.path.splitext(file_path)[0]\n file_path = str(file_path).lower()\n for bad_keyword in blacklist:\n file_path = file_path.replace(bad_keyword, ' ')\n file_path = re.sub('\\\\s+', ' ', file_path)\n keywords = file_path.split(' ')\n keywords = [k for k in keywords if k]\n return keywords\n\n\nclass KeywordDictDataObj(object):\n\n def __init__(self):\n self.count = 0\n self.files = set()\n\n\n<mask token>\n\n\ndef gen_thumb(video_path, thumb_path):\n \"\"\"\n Generate thumb image for the given video, and grabs duration from output\n :return: (success, duration)\n \"\"\"\n if os.path.isfile(thumb_path):\n os.remove(thumb_path)\n global THUMB_SIZE\n cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1',\n '-f', 'apng', '-s', THUMB_SIZE, thumb_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output = p.communicate()[1]\n duration = search_duration_from_text(output)\n if not duration:\n tlog = get_logger(current_thread().name)\n tlog.error('Failed to find duration for {0}'.format(video_path))\n duration = 0\n return p.returncode == 0, duration\n\n\ndef gen_flips(video_path, video_id, duration, flip_path, flip_num):\n \"\"\"\n Generate flips for the given video\n :param video_path: path of the video\n :param video_id: id of the file\n :param duration: duration of video in seconds\n :param flip_path: path dir to put the flips\n :param flip_num: number of flips to generate\n :return: True on success, False otherwise\n \"\"\"\n if not G_GEN_IMAGE:\n return True\n duration = float(duration)\n flip_num = float(flip_num)\n interval = duration / flip_num\n if interval <= 0.0:\n tlog = get_logger(current_thread().name)\n tlog.error('Cannot generate flips. Duration: {0} FlipNum:{1}'.\n format(duration, flip_num))\n return False\n fps = 'fps=1/' + str(interval)\n global THUMB_SIZE\n flip_path = os.path.join(flip_path, str(video_id))\n for _ in range(FLIP_NUM + 3):\n flip_file = '{0}-{1}.png'.format(flip_path, _)\n if os.path.isfile(flip_file):\n os.remove(flip_file)\n flip_path_template = flip_path + '-%d.png'\n cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE,\n flip_path_template]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\n<mask token>\n\n\ndef search_duration_from_text(text):\n regExp = re.compile('Duration: (\\\\d{2}):(\\\\d{2}):(\\\\d{2})')\n result = regExp.search(text, re.M | re.U)\n if result is not None:\n hour, min, sec = result.groups()\n duration = int(hour) * 3600 + int(min) * 60 + int(sec)\n return duration\n return None\n",
"step-2": "<mask token>\n\n\ndef register_int_signal_handler():\n\n def stop_thread_handler(signum, frame):\n log.info('Received signal {0}. Will stop all task threads'.format(\n signum))\n for _ in range(len(THREAD_STOP_FLAGS)):\n THREAD_STOP_FLAGS[_] = True\n if platform.platform().startswith('Windows'):\n signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)\n else:\n signal.signal(signal.SIGINT, stop_thread_handler)\n\n\ndef next_video_id(current, path):\n existing = Video.objects.filter(path=path)\n if existing:\n return existing[0].video_id, current\n current += 1\n return current, current\n\n\ndef create_task_list(path_list):\n \"\"\"\n Walks path recursively, and create a task list\n :param path_list: a list of (path, rating)\n :return: a list of ImportTask objects\n \"\"\"\n current_video_id = Video.objects.all().aggregate(Max('video_id'))[\n 'video_id__max']\n if not current_video_id:\n current_video_id = 0\n task_list = []\n for path, rating in path_list:\n base_path = os.path.split(path)[0]\n if os.path.isfile(path):\n file_name = os.path.basename(path)\n if is_valid_video_file(path, file_name):\n video_id, current_video_id = next_video_id(current_video_id,\n path)\n task_list.append(ImportTask(video_id, base_path, path, rating))\n continue\n for root, dirs, files in os.walk(path):\n for file_name in files:\n try:\n file_path = os.path.join(root, file_name)\n if os.path.isdir(file_path):\n continue\n if is_valid_video_file(file_path, file_name):\n video_id, current_video_id = next_video_id(\n current_video_id, file_path)\n task_list.append(ImportTask(video_id, base_path,\n file_path, rating))\n except:\n log.error('#Error while proceeding: {0}'.format(file_name))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value,\n exc_traceback, limit=2, file=sys.stdout)\n return task_list\n\n\ndef start_tasks(task_list):\n global task_queue\n for task in task_list:\n task_queue.put(task)\n if not THREAD_STOP_FLAGS:\n for _ in range(MAX_THREAD_NUM):\n THREAD_STOP_FLAGS.append(True)\n if not os.path.isdir(COVER_DIR):\n os.mkdir(COVER_DIR)\n if not os.path.isdir(THUMB_DIR):\n os.mkdir(THUMB_DIR)\n if not os.path.isdir(FLIP_DIR):\n os.mkdir(FLIP_DIR)\n for _ in range(MAX_THREAD_NUM):\n if THREAD_STOP_FLAGS[_]:\n t = Thread(target=import_worker, kwargs={'thread_index': _})\n t.name = str(_)\n t.daemon = False\n t.start()\n task_queue.join()\n\n\n<mask token>\n\n\nclass ImportTask(object):\n\n def __init__(self, video_id, base_path, path, rating=Video.P):\n \"\"\"\n Create an import task object.\n :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.\n :param base_path: path prefix that will be ignored when creating keywords from path.\n :param path: path of the file\n :param rating: rating of the video, highest by default.\n \"\"\"\n self.video_id = video_id\n self.base_path = base_path\n self.file_path = path\n self.rating = rating\n\n\n<mask token>\n\n\ndef is_valid_video_file(file_path, file_name):\n if file_name.startswith('.') or not file_name.endswith('.mp4'):\n return False\n if os.path.getsize(file_path) == 0:\n log.info('Remove invalid video file: {0}'.format(file_path))\n os.remove(file_path)\n return False\n return True\n\n\ndef load_keyword_blacklist_from_file():\n blacklist = set()\n keyword_file = 'keywords.blacklist'\n try:\n with open(keyword_file, 'r') as kfp:\n for line in kfp:\n line = line.strip('\\n')\n if line:\n blacklist.add(line)\n log.info('Keywords blacklist: {0}'.format(blacklist))\n except Exception as e:\n log.error('Error while processing {0}:{1}'.format(keyword_file, e))\n return blacklist\n\n\ndef get_keywords(prefix, file_path, blacklist):\n \"\"\"\n Get keywords from file path\n :param prefix: Prefix of the dir path, so we can ignore them\n :param file_path: full path of the video file\n :param blacklist: A set of words/symbols that should be ignored\n :return: a list of keywords\n \"\"\"\n file_path = str(file_path).replace(prefix, '')\n file_path = os.path.splitext(file_path)[0]\n file_path = str(file_path).lower()\n for bad_keyword in blacklist:\n file_path = file_path.replace(bad_keyword, ' ')\n file_path = re.sub('\\\\s+', ' ', file_path)\n keywords = file_path.split(' ')\n keywords = [k for k in keywords if k]\n return keywords\n\n\nclass KeywordDictDataObj(object):\n\n def __init__(self):\n self.count = 0\n self.files = set()\n\n\ndef get_thumb_path(fn):\n return './static/thumb/' + str(fn) + '.png'\n\n\n<mask token>\n\n\ndef gen_thumb(video_path, thumb_path):\n \"\"\"\n Generate thumb image for the given video, and grabs duration from output\n :return: (success, duration)\n \"\"\"\n if os.path.isfile(thumb_path):\n os.remove(thumb_path)\n global THUMB_SIZE\n cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1',\n '-f', 'apng', '-s', THUMB_SIZE, thumb_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output = p.communicate()[1]\n duration = search_duration_from_text(output)\n if not duration:\n tlog = get_logger(current_thread().name)\n tlog.error('Failed to find duration for {0}'.format(video_path))\n duration = 0\n return p.returncode == 0, duration\n\n\ndef gen_flips(video_path, video_id, duration, flip_path, flip_num):\n \"\"\"\n Generate flips for the given video\n :param video_path: path of the video\n :param video_id: id of the file\n :param duration: duration of video in seconds\n :param flip_path: path dir to put the flips\n :param flip_num: number of flips to generate\n :return: True on success, False otherwise\n \"\"\"\n if not G_GEN_IMAGE:\n return True\n duration = float(duration)\n flip_num = float(flip_num)\n interval = duration / flip_num\n if interval <= 0.0:\n tlog = get_logger(current_thread().name)\n tlog.error('Cannot generate flips. Duration: {0} FlipNum:{1}'.\n format(duration, flip_num))\n return False\n fps = 'fps=1/' + str(interval)\n global THUMB_SIZE\n flip_path = os.path.join(flip_path, str(video_id))\n for _ in range(FLIP_NUM + 3):\n flip_file = '{0}-{1}.png'.format(flip_path, _)\n if os.path.isfile(flip_file):\n os.remove(flip_file)\n flip_path_template = flip_path + '-%d.png'\n cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE,\n flip_path_template]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef gen_cover(video_path, cover_path):\n if not G_GEN_IMAGE:\n return True\n if os.path.isfile(cover_path):\n os.remove(cover_path)\n cmd = ['ffmpeg', '-itsoffset', '-1', '-i', video_path, '-vframes', '1',\n '-f', 'apng', cover_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\n<mask token>\n\n\ndef search_duration_from_text(text):\n regExp = re.compile('Duration: (\\\\d{2}):(\\\\d{2}):(\\\\d{2})')\n result = regExp.search(text, re.M | re.U)\n if result is not None:\n hour, min, sec = result.groups()\n duration = int(hour) * 3600 + int(min) * 60 + int(sec)\n return duration\n return None\n",
"step-3": "<mask token>\n\n\ndef register_int_signal_handler():\n\n def stop_thread_handler(signum, frame):\n log.info('Received signal {0}. Will stop all task threads'.format(\n signum))\n for _ in range(len(THREAD_STOP_FLAGS)):\n THREAD_STOP_FLAGS[_] = True\n if platform.platform().startswith('Windows'):\n signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)\n else:\n signal.signal(signal.SIGINT, stop_thread_handler)\n\n\ndef next_video_id(current, path):\n existing = Video.objects.filter(path=path)\n if existing:\n return existing[0].video_id, current\n current += 1\n return current, current\n\n\ndef create_task_list(path_list):\n \"\"\"\n Walks path recursively, and create a task list\n :param path_list: a list of (path, rating)\n :return: a list of ImportTask objects\n \"\"\"\n current_video_id = Video.objects.all().aggregate(Max('video_id'))[\n 'video_id__max']\n if not current_video_id:\n current_video_id = 0\n task_list = []\n for path, rating in path_list:\n base_path = os.path.split(path)[0]\n if os.path.isfile(path):\n file_name = os.path.basename(path)\n if is_valid_video_file(path, file_name):\n video_id, current_video_id = next_video_id(current_video_id,\n path)\n task_list.append(ImportTask(video_id, base_path, path, rating))\n continue\n for root, dirs, files in os.walk(path):\n for file_name in files:\n try:\n file_path = os.path.join(root, file_name)\n if os.path.isdir(file_path):\n continue\n if is_valid_video_file(file_path, file_name):\n video_id, current_video_id = next_video_id(\n current_video_id, file_path)\n task_list.append(ImportTask(video_id, base_path,\n file_path, rating))\n except:\n log.error('#Error while proceeding: {0}'.format(file_name))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value,\n exc_traceback, limit=2, file=sys.stdout)\n return task_list\n\n\ndef start_tasks(task_list):\n global task_queue\n for task in task_list:\n task_queue.put(task)\n if not THREAD_STOP_FLAGS:\n for _ in range(MAX_THREAD_NUM):\n THREAD_STOP_FLAGS.append(True)\n if not os.path.isdir(COVER_DIR):\n os.mkdir(COVER_DIR)\n if not os.path.isdir(THUMB_DIR):\n os.mkdir(THUMB_DIR)\n if not os.path.isdir(FLIP_DIR):\n os.mkdir(FLIP_DIR)\n for _ in range(MAX_THREAD_NUM):\n if THREAD_STOP_FLAGS[_]:\n t = Thread(target=import_worker, kwargs={'thread_index': _})\n t.name = str(_)\n t.daemon = False\n t.start()\n task_queue.join()\n\n\n<mask token>\n\n\nclass ImportTask(object):\n\n def __init__(self, video_id, base_path, path, rating=Video.P):\n \"\"\"\n Create an import task object.\n :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.\n :param base_path: path prefix that will be ignored when creating keywords from path.\n :param path: path of the file\n :param rating: rating of the video, highest by default.\n \"\"\"\n self.video_id = video_id\n self.base_path = base_path\n self.file_path = path\n self.rating = rating\n\n\ndef import_worker(thread_index):\n \"\"\"\n Thread worker that deals with tasks.\n :return:\n \"\"\"\n THREAD_STOP_FLAGS[thread_index] = False\n while not (THREAD_STOP_FLAGS[thread_index] or task_queue.empty()):\n task = task_queue.get()\n do_import_video_task(task)\n task_queue.task_done()\n THREAD_STOP_FLAGS[thread_index] = True\n\n\ndef do_import_video_task(task):\n video_id = task.video_id\n file_path = task.file_path\n rating = task.rating\n file_name = os.path.basename(file_path)[:-4]\n tlog = get_logger(current_thread().name)\n videos = Video.objects.filter(path=file_path)\n if videos:\n tlog.info('Existing video: {0}'.format(task.file_path))\n return\n video = Video()\n video.video_id = video_id\n video.rating = rating\n thumb_path = get_thumb_path(video.video_id)\n cover_path = get_cover_path(video.video_id)\n if not gen_cover(task.file_path, cover_path):\n tlog.error('Failed to gen cover for {0}'.format(file_path))\n return\n success, duration = gen_thumb(file_path, thumb_path)\n if success:\n if not gen_flips(file_path, video.video_id, duration, FLIP_DIR,\n FLIP_NUM):\n tlog.error('Failed to gen flips for {0}'.format(file_path))\n else:\n tlog.error('Failed to gen thumb for {0}'.format(file_path))\n video.title = file_name\n video.path = file_path\n video.duration = duration\n video.save()\n tlog.info('#Video: {0} [{1}] {2}'.format(video.title, video.duration,\n video.path))\n\n\ndef is_valid_video_file(file_path, file_name):\n if file_name.startswith('.') or not file_name.endswith('.mp4'):\n return False\n if os.path.getsize(file_path) == 0:\n log.info('Remove invalid video file: {0}'.format(file_path))\n os.remove(file_path)\n return False\n return True\n\n\ndef load_keyword_blacklist_from_file():\n blacklist = set()\n keyword_file = 'keywords.blacklist'\n try:\n with open(keyword_file, 'r') as kfp:\n for line in kfp:\n line = line.strip('\\n')\n if line:\n blacklist.add(line)\n log.info('Keywords blacklist: {0}'.format(blacklist))\n except Exception as e:\n log.error('Error while processing {0}:{1}'.format(keyword_file, e))\n return blacklist\n\n\ndef get_keywords(prefix, file_path, blacklist):\n \"\"\"\n Get keywords from file path\n :param prefix: Prefix of the dir path, so we can ignore them\n :param file_path: full path of the video file\n :param blacklist: A set of words/symbols that should be ignored\n :return: a list of keywords\n \"\"\"\n file_path = str(file_path).replace(prefix, '')\n file_path = os.path.splitext(file_path)[0]\n file_path = str(file_path).lower()\n for bad_keyword in blacklist:\n file_path = file_path.replace(bad_keyword, ' ')\n file_path = re.sub('\\\\s+', ' ', file_path)\n keywords = file_path.split(' ')\n keywords = [k for k in keywords if k]\n return keywords\n\n\nclass KeywordDictDataObj(object):\n\n def __init__(self):\n self.count = 0\n self.files = set()\n\n\ndef get_thumb_path(fn):\n return './static/thumb/' + str(fn) + '.png'\n\n\n<mask token>\n\n\ndef gen_thumb(video_path, thumb_path):\n \"\"\"\n Generate thumb image for the given video, and grabs duration from output\n :return: (success, duration)\n \"\"\"\n if os.path.isfile(thumb_path):\n os.remove(thumb_path)\n global THUMB_SIZE\n cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1',\n '-f', 'apng', '-s', THUMB_SIZE, thumb_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output = p.communicate()[1]\n duration = search_duration_from_text(output)\n if not duration:\n tlog = get_logger(current_thread().name)\n tlog.error('Failed to find duration for {0}'.format(video_path))\n duration = 0\n return p.returncode == 0, duration\n\n\ndef gen_flips(video_path, video_id, duration, flip_path, flip_num):\n \"\"\"\n Generate flips for the given video\n :param video_path: path of the video\n :param video_id: id of the file\n :param duration: duration of video in seconds\n :param flip_path: path dir to put the flips\n :param flip_num: number of flips to generate\n :return: True on success, False otherwise\n \"\"\"\n if not G_GEN_IMAGE:\n return True\n duration = float(duration)\n flip_num = float(flip_num)\n interval = duration / flip_num\n if interval <= 0.0:\n tlog = get_logger(current_thread().name)\n tlog.error('Cannot generate flips. Duration: {0} FlipNum:{1}'.\n format(duration, flip_num))\n return False\n fps = 'fps=1/' + str(interval)\n global THUMB_SIZE\n flip_path = os.path.join(flip_path, str(video_id))\n for _ in range(FLIP_NUM + 3):\n flip_file = '{0}-{1}.png'.format(flip_path, _)\n if os.path.isfile(flip_file):\n os.remove(flip_file)\n flip_path_template = flip_path + '-%d.png'\n cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE,\n flip_path_template]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef gen_cover(video_path, cover_path):\n if not G_GEN_IMAGE:\n return True\n if os.path.isfile(cover_path):\n os.remove(cover_path)\n cmd = ['ffmpeg', '-itsoffset', '-1', '-i', video_path, '-vframes', '1',\n '-f', 'apng', cover_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef convert_video_to_mp4(video_path, dest_path):\n tlog = get_logger(current_thread().name)\n if os.path.isfile(dest_path):\n tlog.info('#Already converted, skip: {0}'.format(dest_path))\n return True\n tlog.info('#Converting: {0} => {1}\\n', video_path, dest_path)\n cmd = ['ffmpeg', '-i', video_path, '-vcodec', 'h264', '-acodec', 'aac',\n dest_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef search_duration_from_text(text):\n regExp = re.compile('Duration: (\\\\d{2}):(\\\\d{2}):(\\\\d{2})')\n result = regExp.search(text, re.M | re.U)\n if result is not None:\n hour, min, sec = result.groups()\n duration = int(hour) * 3600 + int(min) * 60 + int(sec)\n return duration\n return None\n",
"step-4": "<mask token>\n\n\ndef register_int_signal_handler():\n\n def stop_thread_handler(signum, frame):\n log.info('Received signal {0}. Will stop all task threads'.format(\n signum))\n for _ in range(len(THREAD_STOP_FLAGS)):\n THREAD_STOP_FLAGS[_] = True\n if platform.platform().startswith('Windows'):\n signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)\n else:\n signal.signal(signal.SIGINT, stop_thread_handler)\n\n\ndef next_video_id(current, path):\n existing = Video.objects.filter(path=path)\n if existing:\n return existing[0].video_id, current\n current += 1\n return current, current\n\n\ndef create_task_list(path_list):\n \"\"\"\n Walks path recursively, and create a task list\n :param path_list: a list of (path, rating)\n :return: a list of ImportTask objects\n \"\"\"\n current_video_id = Video.objects.all().aggregate(Max('video_id'))[\n 'video_id__max']\n if not current_video_id:\n current_video_id = 0\n task_list = []\n for path, rating in path_list:\n base_path = os.path.split(path)[0]\n if os.path.isfile(path):\n file_name = os.path.basename(path)\n if is_valid_video_file(path, file_name):\n video_id, current_video_id = next_video_id(current_video_id,\n path)\n task_list.append(ImportTask(video_id, base_path, path, rating))\n continue\n for root, dirs, files in os.walk(path):\n for file_name in files:\n try:\n file_path = os.path.join(root, file_name)\n if os.path.isdir(file_path):\n continue\n if is_valid_video_file(file_path, file_name):\n video_id, current_video_id = next_video_id(\n current_video_id, file_path)\n task_list.append(ImportTask(video_id, base_path,\n file_path, rating))\n except:\n log.error('#Error while proceeding: {0}'.format(file_name))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value,\n exc_traceback, limit=2, file=sys.stdout)\n return task_list\n\n\ndef start_tasks(task_list):\n global task_queue\n for task in task_list:\n task_queue.put(task)\n if not THREAD_STOP_FLAGS:\n for _ in range(MAX_THREAD_NUM):\n THREAD_STOP_FLAGS.append(True)\n if not os.path.isdir(COVER_DIR):\n os.mkdir(COVER_DIR)\n if not os.path.isdir(THUMB_DIR):\n os.mkdir(THUMB_DIR)\n if not os.path.isdir(FLIP_DIR):\n os.mkdir(FLIP_DIR)\n for _ in range(MAX_THREAD_NUM):\n if THREAD_STOP_FLAGS[_]:\n t = Thread(target=import_worker, kwargs={'thread_index': _})\n t.name = str(_)\n t.daemon = False\n t.start()\n task_queue.join()\n\n\n<mask token>\n\n\nclass ImportTask(object):\n\n def __init__(self, video_id, base_path, path, rating=Video.P):\n \"\"\"\n Create an import task object.\n :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.\n :param base_path: path prefix that will be ignored when creating keywords from path.\n :param path: path of the file\n :param rating: rating of the video, highest by default.\n \"\"\"\n self.video_id = video_id\n self.base_path = base_path\n self.file_path = path\n self.rating = rating\n\n\ndef import_worker(thread_index):\n \"\"\"\n Thread worker that deals with tasks.\n :return:\n \"\"\"\n THREAD_STOP_FLAGS[thread_index] = False\n while not (THREAD_STOP_FLAGS[thread_index] or task_queue.empty()):\n task = task_queue.get()\n do_import_video_task(task)\n task_queue.task_done()\n THREAD_STOP_FLAGS[thread_index] = True\n\n\ndef do_import_video_task(task):\n video_id = task.video_id\n file_path = task.file_path\n rating = task.rating\n file_name = os.path.basename(file_path)[:-4]\n tlog = get_logger(current_thread().name)\n videos = Video.objects.filter(path=file_path)\n if videos:\n tlog.info('Existing video: {0}'.format(task.file_path))\n return\n video = Video()\n video.video_id = video_id\n video.rating = rating\n thumb_path = get_thumb_path(video.video_id)\n cover_path = get_cover_path(video.video_id)\n if not gen_cover(task.file_path, cover_path):\n tlog.error('Failed to gen cover for {0}'.format(file_path))\n return\n success, duration = gen_thumb(file_path, thumb_path)\n if success:\n if not gen_flips(file_path, video.video_id, duration, FLIP_DIR,\n FLIP_NUM):\n tlog.error('Failed to gen flips for {0}'.format(file_path))\n else:\n tlog.error('Failed to gen thumb for {0}'.format(file_path))\n video.title = file_name\n video.path = file_path\n video.duration = duration\n video.save()\n tlog.info('#Video: {0} [{1}] {2}'.format(video.title, video.duration,\n video.path))\n\n\ndef is_valid_video_file(file_path, file_name):\n if file_name.startswith('.') or not file_name.endswith('.mp4'):\n return False\n if os.path.getsize(file_path) == 0:\n log.info('Remove invalid video file: {0}'.format(file_path))\n os.remove(file_path)\n return False\n return True\n\n\ndef load_keyword_blacklist_from_file():\n blacklist = set()\n keyword_file = 'keywords.blacklist'\n try:\n with open(keyword_file, 'r') as kfp:\n for line in kfp:\n line = line.strip('\\n')\n if line:\n blacklist.add(line)\n log.info('Keywords blacklist: {0}'.format(blacklist))\n except Exception as e:\n log.error('Error while processing {0}:{1}'.format(keyword_file, e))\n return blacklist\n\n\ndef get_keywords(prefix, file_path, blacklist):\n \"\"\"\n Get keywords from file path\n :param prefix: Prefix of the dir path, so we can ignore them\n :param file_path: full path of the video file\n :param blacklist: A set of words/symbols that should be ignored\n :return: a list of keywords\n \"\"\"\n file_path = str(file_path).replace(prefix, '')\n file_path = os.path.splitext(file_path)[0]\n file_path = str(file_path).lower()\n for bad_keyword in blacklist:\n file_path = file_path.replace(bad_keyword, ' ')\n file_path = re.sub('\\\\s+', ' ', file_path)\n keywords = file_path.split(' ')\n keywords = [k for k in keywords if k]\n return keywords\n\n\nclass KeywordDictDataObj(object):\n\n def __init__(self):\n self.count = 0\n self.files = set()\n\n\ndef get_thumb_path(fn):\n return './static/thumb/' + str(fn) + '.png'\n\n\ndef get_cover_path(fn):\n return './static/cover/' + str(fn) + '.png'\n\n\ndef gen_thumb(video_path, thumb_path):\n \"\"\"\n Generate thumb image for the given video, and grabs duration from output\n :return: (success, duration)\n \"\"\"\n if os.path.isfile(thumb_path):\n os.remove(thumb_path)\n global THUMB_SIZE\n cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1',\n '-f', 'apng', '-s', THUMB_SIZE, thumb_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output = p.communicate()[1]\n duration = search_duration_from_text(output)\n if not duration:\n tlog = get_logger(current_thread().name)\n tlog.error('Failed to find duration for {0}'.format(video_path))\n duration = 0\n return p.returncode == 0, duration\n\n\ndef gen_flips(video_path, video_id, duration, flip_path, flip_num):\n \"\"\"\n Generate flips for the given video\n :param video_path: path of the video\n :param video_id: id of the file\n :param duration: duration of video in seconds\n :param flip_path: path dir to put the flips\n :param flip_num: number of flips to generate\n :return: True on success, False otherwise\n \"\"\"\n if not G_GEN_IMAGE:\n return True\n duration = float(duration)\n flip_num = float(flip_num)\n interval = duration / flip_num\n if interval <= 0.0:\n tlog = get_logger(current_thread().name)\n tlog.error('Cannot generate flips. Duration: {0} FlipNum:{1}'.\n format(duration, flip_num))\n return False\n fps = 'fps=1/' + str(interval)\n global THUMB_SIZE\n flip_path = os.path.join(flip_path, str(video_id))\n for _ in range(FLIP_NUM + 3):\n flip_file = '{0}-{1}.png'.format(flip_path, _)\n if os.path.isfile(flip_file):\n os.remove(flip_file)\n flip_path_template = flip_path + '-%d.png'\n cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE,\n flip_path_template]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef gen_cover(video_path, cover_path):\n if not G_GEN_IMAGE:\n return True\n if os.path.isfile(cover_path):\n os.remove(cover_path)\n cmd = ['ffmpeg', '-itsoffset', '-1', '-i', video_path, '-vframes', '1',\n '-f', 'apng', cover_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef convert_video_to_mp4(video_path, dest_path):\n tlog = get_logger(current_thread().name)\n if os.path.isfile(dest_path):\n tlog.info('#Already converted, skip: {0}'.format(dest_path))\n return True\n tlog.info('#Converting: {0} => {1}\\n', video_path, dest_path)\n cmd = ['ffmpeg', '-i', video_path, '-vcodec', 'h264', '-acodec', 'aac',\n dest_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n\ndef search_duration_from_text(text):\n regExp = re.compile('Duration: (\\\\d{2}):(\\\\d{2}):(\\\\d{2})')\n result = regExp.search(text, re.M | re.U)\n if result is not None:\n hour, min, sec = result.groups()\n duration = int(hour) * 3600 + int(min) * 60 + int(sec)\n return duration\n return None\n",
"step-5": "# coding=utf8\n# encoding: utf-8\n\nimport os\nimport platform\nimport re\nimport signal\nimport sys\nimport traceback\nfrom subprocess import Popen, PIPE\nfrom threading import Thread, current_thread\n\nfrom Queue import Queue\n\nfrom util.log import get_logger, log\nfrom video.models import Video, KeywordVideoId\nfrom django.db.models import Max\nfrom collect_video import G_GEN_IMAGE\n\nMAX_THREAD_NUM = 4\nTHREAD_STOP_FLAGS = []\n\nTHUMB_DIR = './static/thumb'\nTHUMB_SIZE = '180x135'\nCOVER_DIR = './static/cover'\nFLIP_DIR = './static/flip'\n\nFLIP_NUM = 10\n\ntask_queue = Queue(maxsize=2000)\n\n\ndef register_int_signal_handler():\n def stop_thread_handler(signum, frame):\n log.info(\"Received signal {0}. Will stop all task threads\".format(signum))\n for _ in range(len(THREAD_STOP_FLAGS)):\n THREAD_STOP_FLAGS[_] = True\n\n if platform.platform().startswith('Windows'):\n signal.signal(signal.CTRL_C_EVENT, stop_thread_handler)\n else:\n signal.signal(signal.SIGINT, stop_thread_handler)\n\n\ndef next_video_id(current, path):\n existing = Video.objects.filter(path=path)\n if existing:\n return existing[0].video_id, current\n current += 1\n return current, current\n\ndef create_task_list(path_list):\n \"\"\"\n Walks path recursively, and create a task list\n :param path_list: a list of (path, rating)\n :return: a list of ImportTask objects\n \"\"\"\n current_video_id = Video.objects.all().aggregate(Max('video_id'))['video_id__max']\n if not current_video_id:\n current_video_id = 0\n\n task_list = []\n for (path, rating) in path_list:\n base_path = os.path.split(path)[0]\n if os.path.isfile(path):\n file_name = os.path.basename(path)\n if is_valid_video_file(path, file_name):\n video_id, current_video_id = next_video_id(current_video_id, path)\n task_list.append(ImportTask(video_id, base_path, path, rating))\n continue\n for (root, dirs, files) in os.walk(path):\n for file_name in files:\n try:\n file_path = os.path.join(root, file_name)\n if os.path.isdir(file_path):\n continue\n if is_valid_video_file(file_path, file_name):\n video_id, current_video_id = next_video_id(current_video_id, file_path)\n task_list.append(ImportTask(video_id, base_path, file_path, rating))\n except:\n log.error('#Error while proceeding: {0}'.format(file_name))\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)\n return task_list\n\n\ndef start_tasks(task_list):\n global task_queue\n for task in task_list:\n task_queue.put(task)\n\n if not THREAD_STOP_FLAGS:\n for _ in range(MAX_THREAD_NUM):\n THREAD_STOP_FLAGS.append(True)\n\n if not os.path.isdir(COVER_DIR):\n os.mkdir(COVER_DIR)\n if not os.path.isdir(THUMB_DIR):\n os.mkdir(THUMB_DIR)\n if not os.path.isdir(FLIP_DIR):\n os.mkdir(FLIP_DIR)\n for _ in range(MAX_THREAD_NUM):\n if THREAD_STOP_FLAGS[_]:\n t = Thread(target=import_worker, kwargs={'thread_index': _})\n t.name = str(_)\n t.daemon = False\n t.start()\n\n task_queue.join()\n\n\ndef add_keywords_to_db(task_list):\n blacklist = load_keyword_blacklist_from_file()\n for task in task_list:\n base_path = task.base_path\n file_path = task.file_path\n video_id = task.video_id\n\n keywords = get_keywords(base_path, file_path, blacklist)\n\n log.info('#Keywords:'.format(keywords))\n for key in keywords:\n try:\n if KeywordVideoId.objects.filter(keyword=key, video_id=video_id):\n log.info(\"Existing keyword {0} for {1}\".format(key, video_id))\n continue\n keyword_record = KeywordVideoId()\n keyword_record.keyword = key\n keyword_record.video = Video.objects.get(video_id=video_id)\n keyword_record.save()\n log.info('#Added keyword:{0} for video_id: {1}'.format(key, video_id))\n except Exception as e:\n log.error(\"Error while adding keyword {0} to video {1}: {2}\".format(key, video_id, e))\n\n\nclass ImportTask(object):\n def __init__(self, video_id, base_path, path, rating=Video.P):\n \"\"\"\n Create an import task object.\n :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread.\n :param base_path: path prefix that will be ignored when creating keywords from path.\n :param path: path of the file\n :param rating: rating of the video, highest by default.\n \"\"\"\n self.video_id = video_id\n self.base_path = base_path\n self.file_path = path\n self.rating = rating\n\n\ndef import_worker(thread_index):\n \"\"\"\n Thread worker that deals with tasks.\n :return:\n \"\"\"\n THREAD_STOP_FLAGS[thread_index] = False\n while not (THREAD_STOP_FLAGS[thread_index] or task_queue.empty()):\n task = task_queue.get()\n do_import_video_task(task)\n task_queue.task_done()\n THREAD_STOP_FLAGS[thread_index] = True\n\n\ndef do_import_video_task(task):\n video_id = task.video_id\n file_path = task.file_path\n rating = task.rating\n file_name = os.path.basename(file_path)[:-4]\n\n tlog = get_logger(current_thread().name)\n videos = Video.objects.filter(path=file_path)\n if videos:\n tlog.info(\"Existing video: {0}\".format(task.file_path))\n return\n video = Video()\n video.video_id = video_id\n video.rating = rating\n\n thumb_path = get_thumb_path(video.video_id)\n cover_path = get_cover_path(video.video_id)\n if not gen_cover(task.file_path, cover_path):\n tlog.error(\"Failed to gen cover for {0}\".format(file_path))\n return\n\n success, duration = gen_thumb(file_path, thumb_path)\n if success:\n if not gen_flips(file_path, video.video_id, duration, FLIP_DIR, FLIP_NUM):\n tlog.error(\"Failed to gen flips for {0}\".format(file_path))\n else:\n tlog.error(\"Failed to gen thumb for {0}\".format(file_path))\n\n video.title = file_name\n video.path = file_path\n video.duration = duration\n video.save()\n tlog.info('#Video: {0} [{1}] {2}'.format(video.title, video.duration, video.path))\n\n\ndef is_valid_video_file(file_path, file_name):\n # skip hidden files (possibly not valid video files)\n if file_name.startswith('.') or (not file_name.endswith('.mp4')):\n return False\n if os.path.getsize(file_path) == 0:\n log.info('Remove invalid video file: {0}'.format(file_path))\n os.remove(file_path)\n return False\n return True\n\n\ndef load_keyword_blacklist_from_file():\n blacklist = set()\n keyword_file = 'keywords.blacklist'\n try:\n with open(keyword_file, 'r') as kfp:\n for line in kfp:\n line = line.strip('\\n')\n if line:\n blacklist.add(line)\n log.info(\"Keywords blacklist: {0}\".format(blacklist))\n except Exception as e:\n log.error(\"Error while processing {0}:{1}\".format(keyword_file, e))\n return blacklist\n\n\ndef get_keywords(prefix, file_path, blacklist):\n \"\"\"\n Get keywords from file path\n :param prefix: Prefix of the dir path, so we can ignore them\n :param file_path: full path of the video file\n :param blacklist: A set of words/symbols that should be ignored\n :return: a list of keywords\n \"\"\"\n file_path = str(file_path).replace(prefix, '') # remove base_dir from file_path\n file_path = os.path.splitext(file_path)[0] # Only keep the part without extension\n file_path = str(file_path).lower()\n for bad_keyword in blacklist:\n file_path = file_path.replace(bad_keyword, ' ')\n file_path = re.sub(r'\\s+', ' ', file_path) # Replace multiple spaces to single one\n keywords = file_path.split(' ')\n keywords = [k for k in keywords if k]\n\n return keywords\n\n\n\nclass KeywordDictDataObj(object):\n def __init__(self):\n self.count = 0\n self.files = set()\n\n\ndef get_thumb_path(fn):\n return './static/thumb/' + str(fn) + '.png'\n\n\ndef get_cover_path(fn):\n return './static/cover/' + str(fn) + '.png'\n\n\ndef gen_thumb(video_path, thumb_path):\n \"\"\"\n Generate thumb image for the given video, and grabs duration from output\n :return: (success, duration)\n \"\"\"\n if os.path.isfile(thumb_path):\n os.remove(thumb_path)\n\n global THUMB_SIZE\n cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vframes', '1', '-f', 'apng', '-s', THUMB_SIZE, thumb_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output = p.communicate()[1]\n\n duration = search_duration_from_text(output)\n if not duration:\n tlog = get_logger(current_thread().name)\n tlog.error(\"Failed to find duration for {0}\".format(video_path))\n duration = 0\n\n return p.returncode == 0, duration\n\n\ndef gen_flips(video_path, video_id, duration, flip_path, flip_num):\n \"\"\"\n Generate flips for the given video\n :param video_path: path of the video\n :param video_id: id of the file\n :param duration: duration of video in seconds\n :param flip_path: path dir to put the flips\n :param flip_num: number of flips to generate\n :return: True on success, False otherwise\n \"\"\"\n if not G_GEN_IMAGE:\n return True\n\n duration = float(duration)\n flip_num = float(flip_num)\n interval = duration / flip_num\n if interval <= 0.0:\n tlog = get_logger(current_thread().name)\n tlog.error(\"Cannot generate flips. Duration: {0} FlipNum:{1}\".format(duration, flip_num))\n return False\n fps = 'fps=1/' + str(interval)\n global THUMB_SIZE\n flip_path = os.path.join(flip_path, str(video_id))\n for _ in range(FLIP_NUM+3):\n flip_file = \"{0}-{1}.png\".format(flip_path, _)\n if os.path.isfile(flip_file):\n os.remove(flip_file)\n flip_path_template = flip_path + '-%d.png'\n cmd = ['ffmpeg', '-i', video_path, '-vf', fps, '-s', THUMB_SIZE, flip_path_template]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n\n return p.returncode == 0\n\n\ndef gen_cover(video_path, cover_path):\n if not G_GEN_IMAGE:\n return True\n if os.path.isfile(cover_path):\n os.remove(cover_path)\n\n cmd = ['ffmpeg', '-itsoffset', '-1', '-i', video_path, '-vframes', '1', '-f', 'apng', cover_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n\n return p.returncode == 0\n\n\n# Convert video to mp4\ndef convert_video_to_mp4(video_path, dest_path):\n tlog = get_logger(current_thread().name)\n if os.path.isfile(dest_path):\n tlog.info('#Already converted, skip: {0}'.format(dest_path))\n return True\n tlog.info('#Converting: {0} => {1}\\n', video_path, dest_path)\n\n cmd = ['ffmpeg', '-i', video_path, '-vcodec', 'h264', '-acodec', 'aac', dest_path]\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n p.communicate()\n\n return p.returncode == 0\n\n\n# Search the duration from given text\ndef search_duration_from_text(text):\n # Match pattern like Duration: 00:24:14.91, s\n regExp = re.compile(r'Duration: (\\d{2}):(\\d{2}):(\\d{2})')\n result = regExp.search(text, re.M | re.U)\n\n if result is not None:\n (hour, min, sec) = result.groups()\n duration = int(hour) * 3600 + int(min) * 60 + int(sec)\n return duration\n return None\n",
"step-ids": [
13,
16,
19,
20,
24
]
}
|
[
13,
16,
19,
20,
24
] |
# Generated by Django 3.0.5 on 2020-05-18 12:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0010_auto_20200518_1718'),
]
operations = [
migrations.AlterField(
model_name='order',
name='fianl_code',
field=models.PositiveIntegerField(blank=True, null=True),
),
]
|
normal
|
{
"blob_id": "da783355c5f888a66f623fa7eeeaf0e4e9fcfa48",
"index": 4982,
"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 = [('cart', '0010_auto_20200518_1718')]\n operations = [migrations.AlterField(model_name='order', name=\n 'fianl_code', field=models.PositiveIntegerField(blank=True, null=True))\n ]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('cart', '0010_auto_20200518_1718')]\n operations = [migrations.AlterField(model_name='order', name=\n 'fianl_code', field=models.PositiveIntegerField(blank=True, null=True))\n ]\n",
"step-5": "# Generated by Django 3.0.5 on 2020-05-18 12:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cart', '0010_auto_20200518_1718'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='order',\n name='fianl_code',\n field=models.PositiveIntegerField(blank=True, null=True),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from flask_socketio import SocketIO
socket = SocketIO()
@socket.on('test')
def on_test(msg):
print 'got message'
|
normal
|
{
"blob_id": "7435aa6cd4eec5582be9f4a1dd75b0dfcadc4409",
"index": 5137,
"step-1": "from flask_socketio import SocketIO\n\nsocket = SocketIO()\n\[email protected]('test')\ndef on_test(msg):\n print 'got message'\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
import datetime
class Document(models.Model):
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.document)
class Assignment(models.Model):
name= models.CharField(max_length=250)
technology= models.CharField(max_length=100)
directory= models.CharField(max_length=500, default="NA")
def __str__(self):
return self.name + '-' + self.technology
class Assestment(models.Model):
name= models.CharField(max_length=250)
technology= models.CharField(max_length=100)
username= models.CharField(max_length=100, default="NA")
date = models.DateTimeField(default=datetime.datetime.now, blank=True)
def __str__(self):
return self.name + '-' + self.technology
class UserProfile(models.Model):
user = models.OneToOneField(User)
email = models.CharField(max_length=100)
phone = models.IntegerField(default=0)
city = models.CharField(max_length=100)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
|
normal
|
{
"blob_id": "01b14da7d081a67bab6f9921bb1a6a4c3d5ac216",
"index": 3003,
"step-1": "<mask token>\n\n\nclass Assignment(models.Model):\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n",
"step-4": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.core.urlresolvers import reverse\nimport datetime\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\ndef create_profile(sender, **kwargs):\n if kwargs['created']:\n user_profile = UserProfile.objects.create(user=kwargs['instance'])\n\n\npost_save.connect(create_profile, sender=User)\n",
"step-5": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.core.urlresolvers import reverse\nimport datetime\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name= models.CharField(max_length=250)\n technology= models.CharField(max_length=100)\n directory= models.CharField(max_length=500, default=\"NA\")\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name= models.CharField(max_length=250)\n technology= models.CharField(max_length=100)\n username= models.CharField(max_length=100, default=\"NA\")\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n\n def __str__(self):\n return self.name + '-' + self.technology\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n\ndef create_profile(sender, **kwargs):\n if kwargs['created']:\n user_profile = UserProfile.objects.create(user=kwargs['instance'])\n\n\npost_save.connect(create_profile, sender=User)",
"step-ids": [
7,
8,
11,
14,
15
]
}
|
[
7,
8,
11,
14,
15
] |
"""
Copyright (c) 2017 - Philip Paquette
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# Modified from https://raw.githubusercontent.com/Newmu/dcgan_code/master/lib/rng.py
# MIT License
import numpy as np
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import theano.tensor.shared_randomstreams
from random import Random
seed = 42
py_rng = Random(seed)
np_rng = np.random.RandomState(seed)
t_rng = RandomStreams(seed)
t_rng_2 = theano.tensor.shared_randomstreams.RandomStreams(seed)
def set_seed(n):
global seed, py_rng, np_rng, t_rng
seed = n
py_rng = Random(seed)
np_rng = np.random.RandomState(seed)
t_rng = RandomStreams(seed)
|
normal
|
{
"blob_id": "9a183b1f81681b3dec1132a27b17e389438ab725",
"index": 6045,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef set_seed(n):\n global seed, py_rng, np_rng, t_rng\n seed = n\n py_rng = Random(seed)\n np_rng = np.random.RandomState(seed)\n\n\n<mask token>\n",
"step-3": "<mask token>\nseed = 42\npy_rng = Random(seed)\nnp_rng = np.random.RandomState(seed)\nt_rng = RandomStreams(seed)\nt_rng_2 = theano.tensor.shared_randomstreams.RandomStreams(seed)\n\n\ndef set_seed(n):\n global seed, py_rng, np_rng, t_rng\n seed = n\n py_rng = Random(seed)\n np_rng = np.random.RandomState(seed)\n\n\nt_rng = RandomStreams(seed)\n",
"step-4": "<mask token>\nimport numpy as np\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nimport theano.tensor.shared_randomstreams\nfrom random import Random\nseed = 42\npy_rng = Random(seed)\nnp_rng = np.random.RandomState(seed)\nt_rng = RandomStreams(seed)\nt_rng_2 = theano.tensor.shared_randomstreams.RandomStreams(seed)\n\n\ndef set_seed(n):\n global seed, py_rng, np_rng, t_rng\n seed = n\n py_rng = Random(seed)\n np_rng = np.random.RandomState(seed)\n\n\nt_rng = RandomStreams(seed)\n",
"step-5": "\"\"\"\nCopyright (c) 2017 - Philip Paquette\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\n# Modified from https://raw.githubusercontent.com/Newmu/dcgan_code/master/lib/rng.py\n# MIT License\nimport numpy as np\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nimport theano.tensor.shared_randomstreams\nfrom random import Random\n\nseed = 42\n\npy_rng = Random(seed)\nnp_rng = np.random.RandomState(seed)\nt_rng = RandomStreams(seed)\nt_rng_2 = theano.tensor.shared_randomstreams.RandomStreams(seed)\n\ndef set_seed(n):\n global seed, py_rng, np_rng, t_rng\n\n seed = n\n py_rng = Random(seed)\n np_rng = np.random.RandomState(seed)\n\nt_rng = RandomStreams(seed)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
# All rights reserved. This program and the accompanying materials #
# are made available under the terms of the Apache License, Version 2.0 #
# which accompanies this distribution, and is available at #
# http://www.apache.org/licenses/LICENSE-2.0 #
###############################################################################
from unittest.mock import MagicMock, patch
from scan.fetchers.kube.kube_fetch_containers import KubeFetchContainers
from scan.test.fetch.kube_fetch.kube_test_base import KubeTestBase
from scan.test.fetch.kube_fetch.test_data.kube_access import KUBE_CONFIG
from scan.test.fetch.kube_fetch.test_data.kube_fetch_containers import \
POD_DOCUMENT, CONTAINERS_FOLDER_ID, PODS_RESPONSE_NO_MATCH, \
EXPECTED_CONTAINER_DOC
from scan.test.fetch.kube_fetch.test_data.kube_fetch_pods import PODS_RESPONSE, \
EMPTY_RESPONSE
class TestKubeFetchContainers(KubeTestBase):
class DummyConfig(object):
def __init__(self, _environment):
self.environment = _environment
def setUp(self):
super().setUp()
self.conf_patcher = patch(
'utils.cli_access.Configuration'
)
self.conf_class = self.conf_patcher.start()
self.fetcher = KubeFetchContainers(KUBE_CONFIG)
self.fetcher.configuration = TestKubeFetchContainers.DummyConfig({
'environment_type': 'Kubernetes'
})
@staticmethod
def _get_by_id(environment, item_id):
if environment:
pass
if item_id == POD_DOCUMENT['id']:
return POD_DOCUMENT
return None
def test_get_flannel(self):
self.fetcher.configuration.environment['mechanism_drivers'] = \
['Flannel']
self.inv.get_by_id.side_effect = self._get_by_id
self.fetcher.run = MagicMock(return_value="[]")
response = self._get_response(payload=PODS_RESPONSE,
response_type='V1PodList')
self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)
containers = self.fetcher.get(CONTAINERS_FOLDER_ID)
self.assertEqual(1, len(containers))
self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])
def test_get_no_db_pod(self):
self.inv.get_by_id.return_value = None
containers = self.fetcher.get(CONTAINERS_FOLDER_ID)
self.assertEqual(0, len(containers))
def test_get_no_kube_pods(self):
self.inv.get_by_id.side_effect = self._get_by_id
response = self._get_response(payload=EMPTY_RESPONSE,
response_type='V1PodList')
self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)
containers = self.fetcher.get(CONTAINERS_FOLDER_ID)
self.assertEqual(0, len(containers))
def test_get_no_matching_pod(self):
self.inv.get_by_id.side_effect = self._get_by_id
response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,
response_type='V1PodList')
self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)
containers = self.fetcher.get(CONTAINERS_FOLDER_ID)
self.assertEqual(0, len(containers))
def tearDown(self):
self.conf_patcher.stop()
super().tearDown()
|
normal
|
{
"blob_id": "d60810ea0b19cc9163ce526e6a5a54da9c8b3f68",
"index": 3595,
"step-1": "<mask token>\n\n\nclass TestKubeFetchContainers(KubeTestBase):\n\n\n class DummyConfig(object):\n\n def __init__(self, _environment):\n self.environment = _environment\n <mask token>\n <mask token>\n\n def test_get_flannel(self):\n self.fetcher.configuration.environment['mechanism_drivers'] = [\n 'Flannel']\n self.inv.get_by_id.side_effect = self._get_by_id\n self.fetcher.run = MagicMock(return_value='[]')\n response = self._get_response(payload=PODS_RESPONSE, response_type=\n 'V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(1, len(containers))\n self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])\n\n def test_get_no_db_pod(self):\n self.inv.get_by_id.return_value = None\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_kube_pods(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=EMPTY_RESPONSE, response_type\n ='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_matching_pod(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestKubeFetchContainers(KubeTestBase):\n\n\n class DummyConfig(object):\n\n def __init__(self, _environment):\n self.environment = _environment\n <mask token>\n\n @staticmethod\n def _get_by_id(environment, item_id):\n if environment:\n pass\n if item_id == POD_DOCUMENT['id']:\n return POD_DOCUMENT\n return None\n\n def test_get_flannel(self):\n self.fetcher.configuration.environment['mechanism_drivers'] = [\n 'Flannel']\n self.inv.get_by_id.side_effect = self._get_by_id\n self.fetcher.run = MagicMock(return_value='[]')\n response = self._get_response(payload=PODS_RESPONSE, response_type=\n 'V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(1, len(containers))\n self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])\n\n def test_get_no_db_pod(self):\n self.inv.get_by_id.return_value = None\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_kube_pods(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=EMPTY_RESPONSE, response_type\n ='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_matching_pod(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TestKubeFetchContainers(KubeTestBase):\n\n\n class DummyConfig(object):\n\n def __init__(self, _environment):\n self.environment = _environment\n <mask token>\n\n @staticmethod\n def _get_by_id(environment, item_id):\n if environment:\n pass\n if item_id == POD_DOCUMENT['id']:\n return POD_DOCUMENT\n return None\n\n def test_get_flannel(self):\n self.fetcher.configuration.environment['mechanism_drivers'] = [\n 'Flannel']\n self.inv.get_by_id.side_effect = self._get_by_id\n self.fetcher.run = MagicMock(return_value='[]')\n response = self._get_response(payload=PODS_RESPONSE, response_type=\n 'V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(1, len(containers))\n self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])\n\n def test_get_no_db_pod(self):\n self.inv.get_by_id.return_value = None\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_kube_pods(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=EMPTY_RESPONSE, response_type\n ='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_matching_pod(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def tearDown(self):\n self.conf_patcher.stop()\n super().tearDown()\n",
"step-4": "<mask token>\n\n\nclass TestKubeFetchContainers(KubeTestBase):\n\n\n class DummyConfig(object):\n\n def __init__(self, _environment):\n self.environment = _environment\n\n def setUp(self):\n super().setUp()\n self.conf_patcher = patch('utils.cli_access.Configuration')\n self.conf_class = self.conf_patcher.start()\n self.fetcher = KubeFetchContainers(KUBE_CONFIG)\n self.fetcher.configuration = TestKubeFetchContainers.DummyConfig({\n 'environment_type': 'Kubernetes'})\n\n @staticmethod\n def _get_by_id(environment, item_id):\n if environment:\n pass\n if item_id == POD_DOCUMENT['id']:\n return POD_DOCUMENT\n return None\n\n def test_get_flannel(self):\n self.fetcher.configuration.environment['mechanism_drivers'] = [\n 'Flannel']\n self.inv.get_by_id.side_effect = self._get_by_id\n self.fetcher.run = MagicMock(return_value='[]')\n response = self._get_response(payload=PODS_RESPONSE, response_type=\n 'V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(1, len(containers))\n self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])\n\n def test_get_no_db_pod(self):\n self.inv.get_by_id.return_value = None\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_kube_pods(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=EMPTY_RESPONSE, response_type\n ='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_matching_pod(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def tearDown(self):\n self.conf_patcher.stop()\n super().tearDown()\n",
"step-5": "###############################################################################\n# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #\n# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #\n# #\n# All rights reserved. This program and the accompanying materials #\n# are made available under the terms of the Apache License, Version 2.0 #\n# which accompanies this distribution, and is available at #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n###############################################################################\nfrom unittest.mock import MagicMock, patch\n\nfrom scan.fetchers.kube.kube_fetch_containers import KubeFetchContainers\nfrom scan.test.fetch.kube_fetch.kube_test_base import KubeTestBase\nfrom scan.test.fetch.kube_fetch.test_data.kube_access import KUBE_CONFIG\nfrom scan.test.fetch.kube_fetch.test_data.kube_fetch_containers import \\\n POD_DOCUMENT, CONTAINERS_FOLDER_ID, PODS_RESPONSE_NO_MATCH, \\\n EXPECTED_CONTAINER_DOC\nfrom scan.test.fetch.kube_fetch.test_data.kube_fetch_pods import PODS_RESPONSE, \\\n EMPTY_RESPONSE\n\n\nclass TestKubeFetchContainers(KubeTestBase):\n\n class DummyConfig(object):\n def __init__(self, _environment):\n self.environment = _environment\n\n def setUp(self):\n super().setUp()\n\n self.conf_patcher = patch(\n 'utils.cli_access.Configuration'\n )\n self.conf_class = self.conf_patcher.start()\n\n self.fetcher = KubeFetchContainers(KUBE_CONFIG)\n self.fetcher.configuration = TestKubeFetchContainers.DummyConfig({\n 'environment_type': 'Kubernetes'\n })\n\n @staticmethod\n def _get_by_id(environment, item_id):\n if environment:\n pass\n if item_id == POD_DOCUMENT['id']:\n return POD_DOCUMENT\n return None\n\n def test_get_flannel(self):\n self.fetcher.configuration.environment['mechanism_drivers'] = \\\n ['Flannel']\n self.inv.get_by_id.side_effect = self._get_by_id\n self.fetcher.run = MagicMock(return_value=\"[]\")\n response = self._get_response(payload=PODS_RESPONSE,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(1, len(containers))\n self.assertDictContains(EXPECTED_CONTAINER_DOC, containers[0])\n\n def test_get_no_db_pod(self):\n self.inv.get_by_id.return_value = None\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_kube_pods(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=EMPTY_RESPONSE,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def test_get_no_matching_pod(self):\n self.inv.get_by_id.side_effect = self._get_by_id\n response = self._get_response(payload=PODS_RESPONSE_NO_MATCH,\n response_type='V1PodList')\n self.api.list_pod_for_all_namespaces = MagicMock(return_value=response)\n\n containers = self.fetcher.get(CONTAINERS_FOLDER_ID)\n self.assertEqual(0, len(containers))\n\n def tearDown(self):\n self.conf_patcher.stop()\n super().tearDown()\n",
"step-ids": [
5,
6,
7,
8,
10
]
}
|
[
5,
6,
7,
8,
10
] |
import os
import xml.etree.ElementTree as Et
import copy
from .common import CommonRouteExchangeService
class DataRoutes(CommonRouteExchangeService):
"""Класс для работы с данными аршрутов"""
def get_route_from_file(self, path_route):
"""Считывание маршрута из файла
:param path_route: Путь до маршрута в формате XML
:return: ElementTree
"""
path_file = os.path.join(os.getcwd(), path_route)
return Et.parse(path_file)
def change_uvid_in_route(self, tree_route, uvid):
"""Замена UVID в маршруте
:param tree_route: Маршрут в формате XML
:param uvid: UVID
:return: ElementTree
"""
tree_route_copy = copy.deepcopy(tree_route)
root = tree_route_copy.getroot()
root.find('.//*[@vesselVoyage]').attrib.update({'vesselVoyage': uvid})
return tree_route_copy
def change_status_in_route(self, tree_route, status):
"""Замена статуса маршрута в маршруте
:param tree_route: Маршрут в формате XML
:param status: Cтатус маршрута 1 - ORIGINAL
2 - PLANNED_FOR_VOYAGE
3 - OPTIMIZED
4 - CROSS_CHECKED
5 - SAFETY_CHECKED
6 - APPROVED
7 - USED_FOR_MONITORING
8 - INACTIVE
:return: ElementTree
"""
tree_route_copy = copy.deepcopy(tree_route)
root = tree_route_copy.getroot()
root.find('.//*[@routeStatus]').attrib.update({'routeStatus': str(
status)})
return tree_route_copy
def change_route_name_in_route(self, tree_route, route_name):
"""Замена routeName в маршруте
:param tree_route: Маршрут в формате XML
:param route_name: Имя маршрута
:return: ElementTree
"""
tree_route_copy = copy.deepcopy(tree_route)
root = tree_route_copy.getroot()
root.find('.//*[@routeName]').attrib.update({'routeName': route_name})
return tree_route_copy
def convert_route_to_str(self, tree_route):
return Et.tostring(tree_route.getroot(), encoding='UTF-8')
|
normal
|
{
"blob_id": "63069f03d17862b8ea6aa74d0acd1370bbea0dcb",
"index": 836,
"step-1": "<mask token>\n\n\nclass DataRoutes(CommonRouteExchangeService):\n <mask token>\n <mask token>\n <mask token>\n\n def change_status_in_route(self, tree_route, status):\n \"\"\"Замена статуса маршрута в маршруте\n :param tree_route: Маршрут в формате XML\n :param status: Cтатус маршрута 1 - ORIGINAL\n 2 - PLANNED_FOR_VOYAGE\n 3 - OPTIMIZED\n 4 - CROSS_CHECKED\n 5 - SAFETY_CHECKED\n 6 - APPROVED\n 7 - USED_FOR_MONITORING\n 8 - INACTIVE\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeStatus]').attrib.update({'routeStatus': str(\n status)})\n return tree_route_copy\n <mask token>\n\n def convert_route_to_str(self, tree_route):\n return Et.tostring(tree_route.getroot(), encoding='UTF-8')\n",
"step-2": "<mask token>\n\n\nclass DataRoutes(CommonRouteExchangeService):\n <mask token>\n\n def get_route_from_file(self, path_route):\n \"\"\"Считывание маршрута из файла\n :param path_route: Путь до маршрута в формате XML\n :return: ElementTree\n \"\"\"\n path_file = os.path.join(os.getcwd(), path_route)\n return Et.parse(path_file)\n\n def change_uvid_in_route(self, tree_route, uvid):\n \"\"\"Замена UVID в маршруте\n :param tree_route: Маршрут в формате XML\n :param uvid: UVID\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@vesselVoyage]').attrib.update({'vesselVoyage': uvid})\n return tree_route_copy\n\n def change_status_in_route(self, tree_route, status):\n \"\"\"Замена статуса маршрута в маршруте\n :param tree_route: Маршрут в формате XML\n :param status: Cтатус маршрута 1 - ORIGINAL\n 2 - PLANNED_FOR_VOYAGE\n 3 - OPTIMIZED\n 4 - CROSS_CHECKED\n 5 - SAFETY_CHECKED\n 6 - APPROVED\n 7 - USED_FOR_MONITORING\n 8 - INACTIVE\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeStatus]').attrib.update({'routeStatus': str(\n status)})\n return tree_route_copy\n <mask token>\n\n def convert_route_to_str(self, tree_route):\n return Et.tostring(tree_route.getroot(), encoding='UTF-8')\n",
"step-3": "<mask token>\n\n\nclass DataRoutes(CommonRouteExchangeService):\n \"\"\"Класс для работы с данными аршрутов\"\"\"\n\n def get_route_from_file(self, path_route):\n \"\"\"Считывание маршрута из файла\n :param path_route: Путь до маршрута в формате XML\n :return: ElementTree\n \"\"\"\n path_file = os.path.join(os.getcwd(), path_route)\n return Et.parse(path_file)\n\n def change_uvid_in_route(self, tree_route, uvid):\n \"\"\"Замена UVID в маршруте\n :param tree_route: Маршрут в формате XML\n :param uvid: UVID\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@vesselVoyage]').attrib.update({'vesselVoyage': uvid})\n return tree_route_copy\n\n def change_status_in_route(self, tree_route, status):\n \"\"\"Замена статуса маршрута в маршруте\n :param tree_route: Маршрут в формате XML\n :param status: Cтатус маршрута 1 - ORIGINAL\n 2 - PLANNED_FOR_VOYAGE\n 3 - OPTIMIZED\n 4 - CROSS_CHECKED\n 5 - SAFETY_CHECKED\n 6 - APPROVED\n 7 - USED_FOR_MONITORING\n 8 - INACTIVE\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeStatus]').attrib.update({'routeStatus': str(\n status)})\n return tree_route_copy\n\n def change_route_name_in_route(self, tree_route, route_name):\n \"\"\"Замена routeName в маршруте\n :param tree_route: Маршрут в формате XML\n :param route_name: Имя маршрута\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeName]').attrib.update({'routeName': route_name})\n return tree_route_copy\n\n def convert_route_to_str(self, tree_route):\n return Et.tostring(tree_route.getroot(), encoding='UTF-8')\n",
"step-4": "import os\nimport xml.etree.ElementTree as Et\nimport copy\nfrom .common import CommonRouteExchangeService\n\n\nclass DataRoutes(CommonRouteExchangeService):\n \"\"\"Класс для работы с данными аршрутов\"\"\"\n\n def get_route_from_file(self, path_route):\n \"\"\"Считывание маршрута из файла\n :param path_route: Путь до маршрута в формате XML\n :return: ElementTree\n \"\"\"\n path_file = os.path.join(os.getcwd(), path_route)\n return Et.parse(path_file)\n\n def change_uvid_in_route(self, tree_route, uvid):\n \"\"\"Замена UVID в маршруте\n :param tree_route: Маршрут в формате XML\n :param uvid: UVID\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@vesselVoyage]').attrib.update({'vesselVoyage': uvid})\n return tree_route_copy\n\n def change_status_in_route(self, tree_route, status):\n \"\"\"Замена статуса маршрута в маршруте\n :param tree_route: Маршрут в формате XML\n :param status: Cтатус маршрута 1 - ORIGINAL\n 2 - PLANNED_FOR_VOYAGE\n 3 - OPTIMIZED\n 4 - CROSS_CHECKED\n 5 - SAFETY_CHECKED\n 6 - APPROVED\n 7 - USED_FOR_MONITORING\n 8 - INACTIVE\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeStatus]').attrib.update({'routeStatus': str(\n status)})\n return tree_route_copy\n\n def change_route_name_in_route(self, tree_route, route_name):\n \"\"\"Замена routeName в маршруте\n :param tree_route: Маршрут в формате XML\n :param route_name: Имя маршрута\n :return: ElementTree\n \"\"\"\n tree_route_copy = copy.deepcopy(tree_route)\n root = tree_route_copy.getroot()\n root.find('.//*[@routeName]').attrib.update({'routeName': route_name})\n return tree_route_copy\n\n def convert_route_to_str(self, tree_route):\n return Et.tostring(tree_route.getroot(), encoding='UTF-8')\n",
"step-5": null,
"step-ids": [
3,
5,
7,
8
]
}
|
[
3,
5,
7,
8
] |
import bz2
import json
import os
from pyspark.context import SparkContext
from pyspark.accumulators import AccumulatorParam
import numpy as np
from scipy import spatial
import pandas as pd
import re
import operator
import csv
CACHE_DIR = "D:\TwitterDatastream\PYTHONCACHE_SMALL"
EDU_DATA = 'merged.csv'
TRAIN_FEAT_CSV = 'testFeat.csv'
TRAIN_LABS_CSV = 'testLabs.csv'
TRAIN_FEAT_LABS_CSV = 'testFeatLabs.csv'
FEATURE_NAMES_CSV = 'featureNames.csv'
sc = SparkContext('local', 'test')
# location_data = pd.read_csv('new_merged.csv')
class WordsSetAccumulatorParam(AccumulatorParam):
def zero(self, v):
return set()
def addInPlace(self, acc1, acc2):
return acc1.union(acc2)
# An accumulator used to build the word vocabulary
class WordsDictAccumulatorParam(AccumulatorParam):
def zero(self, v):
return dict()
def addInPlace(self, acc1, acc2):
for key in acc2.keys():
try:
acc1[key] += acc2[key]
except:
acc1[key] = acc2[key]
return acc1
# An accumulator used to build the word vocabulary
# vocabulary = sc.accumulator(set(), WordsSetAccumulatorParam())
vocabulary = sc.accumulator(dict(), WordsDictAccumulatorParam())
# load Education census data
location_data = pd.read_csv(EDU_DATA)
area_dict = dict(zip(location_data['city'], location_data[['fips', 'without_hsd','with_hsd', 'somecollege', 'bachelors']].values.tolist()))
county_dict = dict(zip(location_data['county'], location_data[['fips', 'without_hsd','with_hsd', 'somecollege', 'bachelors']].values.tolist()))
coord_dict = {tuple(x[:2]):x[2] for x in location_data[['lat', 'lng', 'county']].values}
# create a KD tree of known county center locations to be used to map a tweet coordinate to a county
latlon = list()
for index, row in location_data.iterrows():
latlon.append([location_data['lat'][index], location_data['lng'][index]])
latlon = np.array(latlon)
latlonKDT = spatial.KDTree(latlon)
# function to map place, location or coordinate data from a tweet to a FIPS code of the county and the education
# level distribution of that county
def mapToCounty(place, location, coordinates):
# coordr_dict = {tuple(x[:2]):x[2] for x in location_data[['lat_r', 'lng_r', 'county']].values}
if place:
place = (place.split(",")[0]).lower()
# country = (place.split(",")[1]).lower()
try:
if area_dict[place]: return area_dict[place]
except: None
if location:
location = (location.split(",")[0]).lower()
try:
if area_dict[location]: return area_dict[location]
except: None
if coordinates:
closestLoc = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9)[1]
try:
closest = latlon[closestLoc]
except:
return None
# closest = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9)
# if closest[0] != float('inf') and latlon[closest[1]][0] != 0. and latlon[closest[1]][1] != 0.:
# print(coordinates, closest, latlon[closest[1]])
# return closest[0], closest[1]
if coord_dict[closest[0], closest[1]]:
county_k = coord_dict[(closest[0], closest[1])]
return county_dict[county_k]
return None
# Load Tweets from each file (.bz2 or .json)
def load_bz2_json(filename):
if '.bz2' in filename:
with bz2.open(filename, 'rt') as f:
lines = str(f.read()).split('\n')
else:
with open(filename) as f:
lines = str(f.readlines()).split('\\n')
num_lines = len(lines)
tweets = []
for line in lines:
try:
if line == "":
num_lines -= 1
continue
tweets.append(json.loads(line))
except:
continue
# print(filename, len(tweets))
return tweets
# strip each tweet object and keep only whats necessary in a dictonary
def load_tweet(tweet, tweets_saved):
try:
# tweet_id = tweet['id']
tweet_text = tweet['text']
tweet_user_id = tweet['user']['id']
tweet_user_location = tweet['user']['location']
tweet_user_lang = tweet['user']['lang']
try: tweet_coordinates = tweet['coordinates']['coordinates']
except: tweet_coordinates = None
try: tweet_place = tweet['place']['full_name']
except: tweet_place = None
map_to_county = mapToCounty(tweet_place, tweet_user_location, tweet_coordinates)
if map_to_county:
tweet_county = int(map_to_county[0])
tweet_education_level = tuple(map_to_county[1:])
else:
tweet_county = None
tweet_education_level = None
# created_at = tweet['created_at']
except KeyError:
return {}, tweets_saved
data = {'tweet_text': tweet_text,
# 'tweet_id': tweet_id,
'tweet_user_id': tweet_user_id,
# 'tweet_user_location': tweet_user_location,
'tweet_user_lang': tweet_user_lang,
# 'tweet_place': tweet_place,
# 'tweet_coordinates': tweet_coordinates,
'tweet_county': tweet_county,
'tweet_education_level': tweet_education_level}
# 'date_loaded': datetime.datetime.now(),
# 'tweet_json': json.dumps(tweet)}
tweets_saved += 1
return data, tweets_saved
wordPattern = re.compile(r"\b[A-Za-z_.,!\"']+\b", re.IGNORECASE)
httpPattern = re.compile(r"^RT |@\S+|http\S+", re.IGNORECASE)
# Function that uses regular expressions to remove unwanted characters, URLs, etc. and split tweet_text
# into meaningful words
def parseTweetText(tweet):
text = tweet['tweet_text']
text = httpPattern.sub(r"", text)
words = wordPattern.findall(text)
tweet['tweet_text'] = words #list(zip(words, [1]*len(words)))
# print(tweet)
return tweet
# function to combine word lists and count frequency of each word locally
def combineWordLists(x ,y):
global vocabulary
if isinstance(x, dict):
wordDict = x
xny = y
else:
wordDict = dict()
xny = x + y
for w in xny:
# vocabulary +=[w]
vocabulary += {w: 1}
try:
wordDict[w] += 1
except:
wordDict[w] = 1
return wordDict
# function to add words to the vocabulary and count frequency of each word globally
def genVocabulary(x):
global vocabulary
arr = x[1]
if isinstance(arr, dict):
return x
else:
wordDict = dict()
for w in arr:
vocabulary += {w: 1}
try:
wordDict[w] += 1
except:
wordDict[w] = 1
x = (x[0],wordDict)
return x
# read tweets from each file and parse them into dictionaries with only relevant data
def handle_file(filename):
tweets = load_bz2_json(filename)
tweet_dicts = []
tweets_saved = 0
for tweet in tweets:
tweet_dict, tweets_saved = load_tweet(tweet, tweets_saved)
if tweet_dict:
tweet_dicts.append(tweet_dict)
return tweet_dicts
# filter only tweets that have text, land, education and are written in english
def filterTweets(tweet):
# location = tweet['tweet_user_location']
# coordinates = tweet['tweet_place']
# place = tweet['tweet_coordinates']
text = tweet['tweet_text']
lang = tweet['tweet_user_lang']
education = tweet['tweet_education_level']
county = tweet['tweet_county']
# if location or coordinates or place: ret = True
# else: return False
if not text or text == []: return False
if lang != 'en': return False
if education is None or county is None: return False
return True
# store all data into CSV files
def storeResults(traindata, vocab):
columnIdx = {vocab[voc][0]: voc for voc in range(len(vocab))}
with open(TRAIN_FEAT_CSV, 'wt') as trainFeatFile, open(TRAIN_LABS_CSV, 'wt') as trainLabsFile, open(TRAIN_FEAT_LABS_CSV, 'wt') as trainFeatLabsFile:
trainFeatwriter = csv.writer(trainFeatFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
trainLabswriter = csv.writer(trainLabsFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
trainFeatLabswriter = csv.writer(trainFeatLabsFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for row in traindata:
edu = row[0][1]
featDict = row[1]
feats = np.zeros(len(columnIdx))
for key in featDict:
try:
feats[columnIdx[key]] = featDict[key]
except:
continue
trainFeatwriter.writerow(feats.tolist())
trainLabswriter.writerow(list(edu))
combList = list(edu) + feats.tolist()
trainFeatLabswriter.writerow(combList)
# main function with all the Spark code
def main():
fileNames = sc.parallelize([])
# generate a list of all files in the data directory
for root, dirs, files in os.walk(CACHE_DIR):
subFileNames = sc.parallelize(files).map(lambda file: os.path.join(root, file))
fileNames = sc.union([fileNames, subFileNames])
# load all tweets and filter
tweetsRdd = fileNames.flatMap(lambda file: handle_file(file)).filter(lambda tweet: filterTweets(tweet))
# clean, parse and filter tweets and map each to county and education level
wordsRdd = tweetsRdd.map(lambda tweet: parseTweetText(tweet)).filter(lambda tweet: filterTweets(tweet))
# set county and education level as the key for each tweet and keep only the text as value
countyEduRdd = wordsRdd.map(lambda tweet: ((tweet['tweet_county'], tweet['tweet_education_level']), tweet['tweet_text']))
# aggregate tweets based on county level and generate vocabulary
countyEduRdd = countyEduRdd.reduceByKey(lambda x, y: combineWordLists(x, y)).map(lambda z: genVocabulary(z))
tempRes = countyEduRdd.collect()
# print(tempRes)
print(len(tempRes))
vocabRDD = sc.parallelize(vocabulary.value.items())
# filter out words that only occur once in the entire dataset (mainly noise)
vocabRDD = vocabRDD.filter(lambda voc: True if voc[1] > 1 else False)
# print("vocabulary = ", sorted(vocabulary.value.items(), key=operator.itemgetter(1)))
vocab = sorted(vocabRDD.collect(), key=operator.itemgetter(1), reverse=True)
# print("vocabulary = ", vocab)
print("vocabulary size = ", len(vocab))
storeResults(tempRes, vocab)
if __name__ == "__main__":
main()
|
normal
|
{
"blob_id": "ee58ed68d2f3c43f9611f6c6e4cd2b99adcb43d2",
"index": 2616,
"step-1": "<mask token>\n\n\nclass WordsSetAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return set()\n\n def addInPlace(self, acc1, acc2):\n return acc1.union(acc2)\n\n\nclass WordsDictAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return dict()\n\n def addInPlace(self, acc1, acc2):\n for key in acc2.keys():\n try:\n acc1[key] += acc2[key]\n except:\n acc1[key] = acc2[key]\n return acc1\n\n\n<mask token>\n\n\ndef mapToCounty(place, location, coordinates):\n if place:\n place = place.split(',')[0].lower()\n try:\n if area_dict[place]:\n return area_dict[place]\n except:\n None\n if location:\n location = location.split(',')[0].lower()\n try:\n if area_dict[location]:\n return area_dict[location]\n except:\n None\n if coordinates:\n closestLoc = spatial.KDTree(latlon).query(coordinates, k=1,\n distance_upper_bound=9)[1]\n try:\n closest = latlon[closestLoc]\n except:\n return None\n if coord_dict[closest[0], closest[1]]:\n county_k = coord_dict[closest[0], closest[1]]\n return county_dict[county_k]\n return None\n\n\ndef load_bz2_json(filename):\n if '.bz2' in filename:\n with bz2.open(filename, 'rt') as f:\n lines = str(f.read()).split('\\n')\n else:\n with open(filename) as f:\n lines = str(f.readlines()).split('\\\\n')\n num_lines = len(lines)\n tweets = []\n for line in lines:\n try:\n if line == '':\n num_lines -= 1\n continue\n tweets.append(json.loads(line))\n except:\n continue\n return tweets\n\n\n<mask token>\n\n\ndef parseTweetText(tweet):\n text = tweet['tweet_text']\n text = httpPattern.sub('', text)\n words = wordPattern.findall(text)\n tweet['tweet_text'] = words\n return tweet\n\n\n<mask token>\n\n\ndef genVocabulary(x):\n global vocabulary\n arr = x[1]\n if isinstance(arr, dict):\n return x\n else:\n wordDict = dict()\n for w in arr:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n x = x[0], wordDict\n return x\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass WordsSetAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return set()\n\n def addInPlace(self, acc1, acc2):\n return acc1.union(acc2)\n\n\nclass WordsDictAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return dict()\n\n def addInPlace(self, acc1, acc2):\n for key in acc2.keys():\n try:\n acc1[key] += acc2[key]\n except:\n acc1[key] = acc2[key]\n return acc1\n\n\n<mask token>\n\n\ndef mapToCounty(place, location, coordinates):\n if place:\n place = place.split(',')[0].lower()\n try:\n if area_dict[place]:\n return area_dict[place]\n except:\n None\n if location:\n location = location.split(',')[0].lower()\n try:\n if area_dict[location]:\n return area_dict[location]\n except:\n None\n if coordinates:\n closestLoc = spatial.KDTree(latlon).query(coordinates, k=1,\n distance_upper_bound=9)[1]\n try:\n closest = latlon[closestLoc]\n except:\n return None\n if coord_dict[closest[0], closest[1]]:\n county_k = coord_dict[closest[0], closest[1]]\n return county_dict[county_k]\n return None\n\n\ndef load_bz2_json(filename):\n if '.bz2' in filename:\n with bz2.open(filename, 'rt') as f:\n lines = str(f.read()).split('\\n')\n else:\n with open(filename) as f:\n lines = str(f.readlines()).split('\\\\n')\n num_lines = len(lines)\n tweets = []\n for line in lines:\n try:\n if line == '':\n num_lines -= 1\n continue\n tweets.append(json.loads(line))\n except:\n continue\n return tweets\n\n\ndef load_tweet(tweet, tweets_saved):\n try:\n tweet_text = tweet['text']\n tweet_user_id = tweet['user']['id']\n tweet_user_location = tweet['user']['location']\n tweet_user_lang = tweet['user']['lang']\n try:\n tweet_coordinates = tweet['coordinates']['coordinates']\n except:\n tweet_coordinates = None\n try:\n tweet_place = tweet['place']['full_name']\n except:\n tweet_place = None\n map_to_county = mapToCounty(tweet_place, tweet_user_location,\n tweet_coordinates)\n if map_to_county:\n tweet_county = int(map_to_county[0])\n tweet_education_level = tuple(map_to_county[1:])\n else:\n tweet_county = None\n tweet_education_level = None\n except KeyError:\n return {}, tweets_saved\n data = {'tweet_text': tweet_text, 'tweet_user_id': tweet_user_id,\n 'tweet_user_lang': tweet_user_lang, 'tweet_county': tweet_county,\n 'tweet_education_level': tweet_education_level}\n tweets_saved += 1\n return data, tweets_saved\n\n\n<mask token>\n\n\ndef parseTweetText(tweet):\n text = tweet['tweet_text']\n text = httpPattern.sub('', text)\n words = wordPattern.findall(text)\n tweet['tweet_text'] = words\n return tweet\n\n\n<mask token>\n\n\ndef genVocabulary(x):\n global vocabulary\n arr = x[1]\n if isinstance(arr, dict):\n return x\n else:\n wordDict = dict()\n for w in arr:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n x = x[0], wordDict\n return x\n\n\ndef handle_file(filename):\n tweets = load_bz2_json(filename)\n tweet_dicts = []\n tweets_saved = 0\n for tweet in tweets:\n tweet_dict, tweets_saved = load_tweet(tweet, tweets_saved)\n if tweet_dict:\n tweet_dicts.append(tweet_dict)\n return tweet_dicts\n\n\ndef filterTweets(tweet):\n text = tweet['tweet_text']\n lang = tweet['tweet_user_lang']\n education = tweet['tweet_education_level']\n county = tweet['tweet_county']\n if not text or text == []:\n return False\n if lang != 'en':\n return False\n if education is None or county is None:\n return False\n return True\n\n\n<mask token>\n\n\ndef main():\n fileNames = sc.parallelize([])\n for root, dirs, files in os.walk(CACHE_DIR):\n subFileNames = sc.parallelize(files).map(lambda file: os.path.join(\n root, file))\n fileNames = sc.union([fileNames, subFileNames])\n tweetsRdd = fileNames.flatMap(lambda file: handle_file(file)).filter(lambda\n tweet: filterTweets(tweet))\n wordsRdd = tweetsRdd.map(lambda tweet: parseTweetText(tweet)).filter(lambda\n tweet: filterTweets(tweet))\n countyEduRdd = wordsRdd.map(lambda tweet: ((tweet['tweet_county'],\n tweet['tweet_education_level']), tweet['tweet_text']))\n countyEduRdd = countyEduRdd.reduceByKey(lambda x, y: combineWordLists(x, y)\n ).map(lambda z: genVocabulary(z))\n tempRes = countyEduRdd.collect()\n print(len(tempRes))\n vocabRDD = sc.parallelize(vocabulary.value.items())\n vocabRDD = vocabRDD.filter(lambda voc: True if voc[1] > 1 else False)\n vocab = sorted(vocabRDD.collect(), key=operator.itemgetter(1), reverse=True\n )\n print('vocabulary size = ', len(vocab))\n storeResults(tempRes, vocab)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass WordsSetAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return set()\n\n def addInPlace(self, acc1, acc2):\n return acc1.union(acc2)\n\n\nclass WordsDictAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return dict()\n\n def addInPlace(self, acc1, acc2):\n for key in acc2.keys():\n try:\n acc1[key] += acc2[key]\n except:\n acc1[key] = acc2[key]\n return acc1\n\n\n<mask token>\n\n\ndef mapToCounty(place, location, coordinates):\n if place:\n place = place.split(',')[0].lower()\n try:\n if area_dict[place]:\n return area_dict[place]\n except:\n None\n if location:\n location = location.split(',')[0].lower()\n try:\n if area_dict[location]:\n return area_dict[location]\n except:\n None\n if coordinates:\n closestLoc = spatial.KDTree(latlon).query(coordinates, k=1,\n distance_upper_bound=9)[1]\n try:\n closest = latlon[closestLoc]\n except:\n return None\n if coord_dict[closest[0], closest[1]]:\n county_k = coord_dict[closest[0], closest[1]]\n return county_dict[county_k]\n return None\n\n\ndef load_bz2_json(filename):\n if '.bz2' in filename:\n with bz2.open(filename, 'rt') as f:\n lines = str(f.read()).split('\\n')\n else:\n with open(filename) as f:\n lines = str(f.readlines()).split('\\\\n')\n num_lines = len(lines)\n tweets = []\n for line in lines:\n try:\n if line == '':\n num_lines -= 1\n continue\n tweets.append(json.loads(line))\n except:\n continue\n return tweets\n\n\ndef load_tweet(tweet, tweets_saved):\n try:\n tweet_text = tweet['text']\n tweet_user_id = tweet['user']['id']\n tweet_user_location = tweet['user']['location']\n tweet_user_lang = tweet['user']['lang']\n try:\n tweet_coordinates = tweet['coordinates']['coordinates']\n except:\n tweet_coordinates = None\n try:\n tweet_place = tweet['place']['full_name']\n except:\n tweet_place = None\n map_to_county = mapToCounty(tweet_place, tweet_user_location,\n tweet_coordinates)\n if map_to_county:\n tweet_county = int(map_to_county[0])\n tweet_education_level = tuple(map_to_county[1:])\n else:\n tweet_county = None\n tweet_education_level = None\n except KeyError:\n return {}, tweets_saved\n data = {'tweet_text': tweet_text, 'tweet_user_id': tweet_user_id,\n 'tweet_user_lang': tweet_user_lang, 'tweet_county': tweet_county,\n 'tweet_education_level': tweet_education_level}\n tweets_saved += 1\n return data, tweets_saved\n\n\n<mask token>\n\n\ndef parseTweetText(tweet):\n text = tweet['tweet_text']\n text = httpPattern.sub('', text)\n words = wordPattern.findall(text)\n tweet['tweet_text'] = words\n return tweet\n\n\ndef combineWordLists(x, y):\n global vocabulary\n if isinstance(x, dict):\n wordDict = x\n xny = y\n else:\n wordDict = dict()\n xny = x + y\n for w in xny:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n return wordDict\n\n\ndef genVocabulary(x):\n global vocabulary\n arr = x[1]\n if isinstance(arr, dict):\n return x\n else:\n wordDict = dict()\n for w in arr:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n x = x[0], wordDict\n return x\n\n\ndef handle_file(filename):\n tweets = load_bz2_json(filename)\n tweet_dicts = []\n tweets_saved = 0\n for tweet in tweets:\n tweet_dict, tweets_saved = load_tweet(tweet, tweets_saved)\n if tweet_dict:\n tweet_dicts.append(tweet_dict)\n return tweet_dicts\n\n\ndef filterTweets(tweet):\n text = tweet['tweet_text']\n lang = tweet['tweet_user_lang']\n education = tweet['tweet_education_level']\n county = tweet['tweet_county']\n if not text or text == []:\n return False\n if lang != 'en':\n return False\n if education is None or county is None:\n return False\n return True\n\n\n<mask token>\n\n\ndef main():\n fileNames = sc.parallelize([])\n for root, dirs, files in os.walk(CACHE_DIR):\n subFileNames = sc.parallelize(files).map(lambda file: os.path.join(\n root, file))\n fileNames = sc.union([fileNames, subFileNames])\n tweetsRdd = fileNames.flatMap(lambda file: handle_file(file)).filter(lambda\n tweet: filterTweets(tweet))\n wordsRdd = tweetsRdd.map(lambda tweet: parseTweetText(tweet)).filter(lambda\n tweet: filterTweets(tweet))\n countyEduRdd = wordsRdd.map(lambda tweet: ((tweet['tweet_county'],\n tweet['tweet_education_level']), tweet['tweet_text']))\n countyEduRdd = countyEduRdd.reduceByKey(lambda x, y: combineWordLists(x, y)\n ).map(lambda z: genVocabulary(z))\n tempRes = countyEduRdd.collect()\n print(len(tempRes))\n vocabRDD = sc.parallelize(vocabulary.value.items())\n vocabRDD = vocabRDD.filter(lambda voc: True if voc[1] > 1 else False)\n vocab = sorted(vocabRDD.collect(), key=operator.itemgetter(1), reverse=True\n )\n print('vocabulary size = ', len(vocab))\n storeResults(tempRes, vocab)\n\n\n<mask token>\n",
"step-4": "<mask token>\nCACHE_DIR = 'D:\\\\TwitterDatastream\\\\PYTHONCACHE_SMALL'\nEDU_DATA = 'merged.csv'\nTRAIN_FEAT_CSV = 'testFeat.csv'\nTRAIN_LABS_CSV = 'testLabs.csv'\nTRAIN_FEAT_LABS_CSV = 'testFeatLabs.csv'\nFEATURE_NAMES_CSV = 'featureNames.csv'\nsc = SparkContext('local', 'test')\n\n\nclass WordsSetAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return set()\n\n def addInPlace(self, acc1, acc2):\n return acc1.union(acc2)\n\n\nclass WordsDictAccumulatorParam(AccumulatorParam):\n\n def zero(self, v):\n return dict()\n\n def addInPlace(self, acc1, acc2):\n for key in acc2.keys():\n try:\n acc1[key] += acc2[key]\n except:\n acc1[key] = acc2[key]\n return acc1\n\n\nvocabulary = sc.accumulator(dict(), WordsDictAccumulatorParam())\nlocation_data = pd.read_csv(EDU_DATA)\narea_dict = dict(zip(location_data['city'], location_data[['fips',\n 'without_hsd', 'with_hsd', 'somecollege', 'bachelors']].values.tolist()))\ncounty_dict = dict(zip(location_data['county'], location_data[['fips',\n 'without_hsd', 'with_hsd', 'somecollege', 'bachelors']].values.tolist()))\ncoord_dict = {tuple(x[:2]): x[2] for x in location_data[['lat', 'lng',\n 'county']].values}\nlatlon = list()\nfor index, row in location_data.iterrows():\n latlon.append([location_data['lat'][index], location_data['lng'][index]])\nlatlon = np.array(latlon)\nlatlonKDT = spatial.KDTree(latlon)\n\n\ndef mapToCounty(place, location, coordinates):\n if place:\n place = place.split(',')[0].lower()\n try:\n if area_dict[place]:\n return area_dict[place]\n except:\n None\n if location:\n location = location.split(',')[0].lower()\n try:\n if area_dict[location]:\n return area_dict[location]\n except:\n None\n if coordinates:\n closestLoc = spatial.KDTree(latlon).query(coordinates, k=1,\n distance_upper_bound=9)[1]\n try:\n closest = latlon[closestLoc]\n except:\n return None\n if coord_dict[closest[0], closest[1]]:\n county_k = coord_dict[closest[0], closest[1]]\n return county_dict[county_k]\n return None\n\n\ndef load_bz2_json(filename):\n if '.bz2' in filename:\n with bz2.open(filename, 'rt') as f:\n lines = str(f.read()).split('\\n')\n else:\n with open(filename) as f:\n lines = str(f.readlines()).split('\\\\n')\n num_lines = len(lines)\n tweets = []\n for line in lines:\n try:\n if line == '':\n num_lines -= 1\n continue\n tweets.append(json.loads(line))\n except:\n continue\n return tweets\n\n\ndef load_tweet(tweet, tweets_saved):\n try:\n tweet_text = tweet['text']\n tweet_user_id = tweet['user']['id']\n tweet_user_location = tweet['user']['location']\n tweet_user_lang = tweet['user']['lang']\n try:\n tweet_coordinates = tweet['coordinates']['coordinates']\n except:\n tweet_coordinates = None\n try:\n tweet_place = tweet['place']['full_name']\n except:\n tweet_place = None\n map_to_county = mapToCounty(tweet_place, tweet_user_location,\n tweet_coordinates)\n if map_to_county:\n tweet_county = int(map_to_county[0])\n tweet_education_level = tuple(map_to_county[1:])\n else:\n tweet_county = None\n tweet_education_level = None\n except KeyError:\n return {}, tweets_saved\n data = {'tweet_text': tweet_text, 'tweet_user_id': tweet_user_id,\n 'tweet_user_lang': tweet_user_lang, 'tweet_county': tweet_county,\n 'tweet_education_level': tweet_education_level}\n tweets_saved += 1\n return data, tweets_saved\n\n\nwordPattern = re.compile('\\\\b[A-Za-z_.,!\\\\\"\\']+\\\\b', re.IGNORECASE)\nhttpPattern = re.compile('^RT |@\\\\S+|http\\\\S+', re.IGNORECASE)\n\n\ndef parseTweetText(tweet):\n text = tweet['tweet_text']\n text = httpPattern.sub('', text)\n words = wordPattern.findall(text)\n tweet['tweet_text'] = words\n return tweet\n\n\ndef combineWordLists(x, y):\n global vocabulary\n if isinstance(x, dict):\n wordDict = x\n xny = y\n else:\n wordDict = dict()\n xny = x + y\n for w in xny:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n return wordDict\n\n\ndef genVocabulary(x):\n global vocabulary\n arr = x[1]\n if isinstance(arr, dict):\n return x\n else:\n wordDict = dict()\n for w in arr:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n x = x[0], wordDict\n return x\n\n\ndef handle_file(filename):\n tweets = load_bz2_json(filename)\n tweet_dicts = []\n tweets_saved = 0\n for tweet in tweets:\n tweet_dict, tweets_saved = load_tweet(tweet, tweets_saved)\n if tweet_dict:\n tweet_dicts.append(tweet_dict)\n return tweet_dicts\n\n\ndef filterTweets(tweet):\n text = tweet['tweet_text']\n lang = tweet['tweet_user_lang']\n education = tweet['tweet_education_level']\n county = tweet['tweet_county']\n if not text or text == []:\n return False\n if lang != 'en':\n return False\n if education is None or county is None:\n return False\n return True\n\n\ndef storeResults(traindata, vocab):\n columnIdx = {vocab[voc][0]: voc for voc in range(len(vocab))}\n with open(TRAIN_FEAT_CSV, 'wt') as trainFeatFile, open(TRAIN_LABS_CSV, 'wt'\n ) as trainLabsFile, open(TRAIN_FEAT_LABS_CSV, 'wt'\n ) as trainFeatLabsFile:\n trainFeatwriter = csv.writer(trainFeatFile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n trainLabswriter = csv.writer(trainLabsFile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n trainFeatLabswriter = csv.writer(trainFeatLabsFile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n for row in traindata:\n edu = row[0][1]\n featDict = row[1]\n feats = np.zeros(len(columnIdx))\n for key in featDict:\n try:\n feats[columnIdx[key]] = featDict[key]\n except:\n continue\n trainFeatwriter.writerow(feats.tolist())\n trainLabswriter.writerow(list(edu))\n combList = list(edu) + feats.tolist()\n trainFeatLabswriter.writerow(combList)\n\n\ndef main():\n fileNames = sc.parallelize([])\n for root, dirs, files in os.walk(CACHE_DIR):\n subFileNames = sc.parallelize(files).map(lambda file: os.path.join(\n root, file))\n fileNames = sc.union([fileNames, subFileNames])\n tweetsRdd = fileNames.flatMap(lambda file: handle_file(file)).filter(lambda\n tweet: filterTweets(tweet))\n wordsRdd = tweetsRdd.map(lambda tweet: parseTweetText(tweet)).filter(lambda\n tweet: filterTweets(tweet))\n countyEduRdd = wordsRdd.map(lambda tweet: ((tweet['tweet_county'],\n tweet['tweet_education_level']), tweet['tweet_text']))\n countyEduRdd = countyEduRdd.reduceByKey(lambda x, y: combineWordLists(x, y)\n ).map(lambda z: genVocabulary(z))\n tempRes = countyEduRdd.collect()\n print(len(tempRes))\n vocabRDD = sc.parallelize(vocabulary.value.items())\n vocabRDD = vocabRDD.filter(lambda voc: True if voc[1] > 1 else False)\n vocab = sorted(vocabRDD.collect(), key=operator.itemgetter(1), reverse=True\n )\n print('vocabulary size = ', len(vocab))\n storeResults(tempRes, vocab)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import bz2\nimport json\nimport os\nfrom pyspark.context import SparkContext\nfrom pyspark.accumulators import AccumulatorParam\nimport numpy as np\nfrom scipy import spatial\nimport pandas as pd\nimport re\nimport operator\nimport csv\n\nCACHE_DIR = \"D:\\TwitterDatastream\\PYTHONCACHE_SMALL\"\nEDU_DATA = 'merged.csv'\nTRAIN_FEAT_CSV = 'testFeat.csv'\nTRAIN_LABS_CSV = 'testLabs.csv'\nTRAIN_FEAT_LABS_CSV = 'testFeatLabs.csv'\nFEATURE_NAMES_CSV = 'featureNames.csv'\nsc = SparkContext('local', 'test')\n# location_data = pd.read_csv('new_merged.csv')\n\nclass WordsSetAccumulatorParam(AccumulatorParam):\n def zero(self, v):\n return set()\n def addInPlace(self, acc1, acc2):\n return acc1.union(acc2)\n\n# An accumulator used to build the word vocabulary\nclass WordsDictAccumulatorParam(AccumulatorParam):\n def zero(self, v):\n return dict()\n def addInPlace(self, acc1, acc2):\n for key in acc2.keys():\n try:\n acc1[key] += acc2[key]\n except:\n acc1[key] = acc2[key]\n return acc1\n\n# An accumulator used to build the word vocabulary\n# vocabulary = sc.accumulator(set(), WordsSetAccumulatorParam())\nvocabulary = sc.accumulator(dict(), WordsDictAccumulatorParam())\n\n# load Education census data\nlocation_data = pd.read_csv(EDU_DATA)\narea_dict = dict(zip(location_data['city'], location_data[['fips', 'without_hsd','with_hsd', 'somecollege', 'bachelors']].values.tolist()))\ncounty_dict = dict(zip(location_data['county'], location_data[['fips', 'without_hsd','with_hsd', 'somecollege', 'bachelors']].values.tolist()))\ncoord_dict = {tuple(x[:2]):x[2] for x in location_data[['lat', 'lng', 'county']].values}\n\n# create a KD tree of known county center locations to be used to map a tweet coordinate to a county\nlatlon = list()\nfor index, row in location_data.iterrows():\n latlon.append([location_data['lat'][index], location_data['lng'][index]])\n\nlatlon = np.array(latlon)\nlatlonKDT = spatial.KDTree(latlon)\n\n# function to map place, location or coordinate data from a tweet to a FIPS code of the county and the education\n# level distribution of that county\ndef mapToCounty(place, location, coordinates):\n # coordr_dict = {tuple(x[:2]):x[2] for x in location_data[['lat_r', 'lng_r', 'county']].values}\n if place:\n place = (place.split(\",\")[0]).lower()\n # country = (place.split(\",\")[1]).lower()\n try:\n if area_dict[place]: return area_dict[place]\n except: None\n if location:\n location = (location.split(\",\")[0]).lower()\n try:\n if area_dict[location]: return area_dict[location]\n except: None\n if coordinates:\n closestLoc = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9)[1]\n try:\n closest = latlon[closestLoc]\n except:\n return None\n # closest = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9)\n # if closest[0] != float('inf') and latlon[closest[1]][0] != 0. and latlon[closest[1]][1] != 0.:\n # print(coordinates, closest, latlon[closest[1]])\n # return closest[0], closest[1]\n if coord_dict[closest[0], closest[1]]:\n county_k = coord_dict[(closest[0], closest[1])]\n return county_dict[county_k]\n\n return None\n\n# Load Tweets from each file (.bz2 or .json)\ndef load_bz2_json(filename):\n if '.bz2' in filename:\n with bz2.open(filename, 'rt') as f:\n lines = str(f.read()).split('\\n')\n else:\n with open(filename) as f:\n lines = str(f.readlines()).split('\\\\n')\n num_lines = len(lines)\n tweets = []\n for line in lines:\n try:\n if line == \"\":\n num_lines -= 1\n continue\n tweets.append(json.loads(line))\n except:\n continue\n # print(filename, len(tweets))\n return tweets\n\n# strip each tweet object and keep only whats necessary in a dictonary\ndef load_tweet(tweet, tweets_saved):\n try:\n # tweet_id = tweet['id']\n tweet_text = tweet['text']\n tweet_user_id = tweet['user']['id']\n tweet_user_location = tweet['user']['location']\n tweet_user_lang = tweet['user']['lang']\n try: tweet_coordinates = tweet['coordinates']['coordinates']\n except: tweet_coordinates = None\n try: tweet_place = tweet['place']['full_name']\n except: tweet_place = None\n map_to_county = mapToCounty(tweet_place, tweet_user_location, tweet_coordinates)\n if map_to_county:\n tweet_county = int(map_to_county[0])\n tweet_education_level = tuple(map_to_county[1:])\n else:\n tweet_county = None\n tweet_education_level = None\n # created_at = tweet['created_at']\n except KeyError:\n return {}, tweets_saved\n\n data = {'tweet_text': tweet_text,\n # 'tweet_id': tweet_id,\n 'tweet_user_id': tweet_user_id,\n # 'tweet_user_location': tweet_user_location,\n 'tweet_user_lang': tweet_user_lang,\n # 'tweet_place': tweet_place,\n # 'tweet_coordinates': tweet_coordinates,\n 'tweet_county': tweet_county,\n 'tweet_education_level': tweet_education_level}\n # 'date_loaded': datetime.datetime.now(),\n # 'tweet_json': json.dumps(tweet)}\n\n tweets_saved += 1\n return data, tweets_saved\n\nwordPattern = re.compile(r\"\\b[A-Za-z_.,!\\\"']+\\b\", re.IGNORECASE)\nhttpPattern = re.compile(r\"^RT |@\\S+|http\\S+\", re.IGNORECASE)\n\n# Function that uses regular expressions to remove unwanted characters, URLs, etc. and split tweet_text\n# into meaningful words\ndef parseTweetText(tweet):\n text = tweet['tweet_text']\n text = httpPattern.sub(r\"\", text)\n words = wordPattern.findall(text)\n tweet['tweet_text'] = words #list(zip(words, [1]*len(words)))\n # print(tweet)\n return tweet\n\n# function to combine word lists and count frequency of each word locally\ndef combineWordLists(x ,y):\n global vocabulary\n if isinstance(x, dict):\n wordDict = x\n xny = y\n else:\n wordDict = dict()\n xny = x + y\n for w in xny:\n # vocabulary +=[w]\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n\n return wordDict\n\n# function to add words to the vocabulary and count frequency of each word globally\ndef genVocabulary(x):\n global vocabulary\n arr = x[1]\n if isinstance(arr, dict):\n return x\n else:\n wordDict = dict()\n for w in arr:\n vocabulary += {w: 1}\n try:\n wordDict[w] += 1\n except:\n wordDict[w] = 1\n x = (x[0],wordDict)\n return x\n\n# read tweets from each file and parse them into dictionaries with only relevant data\ndef handle_file(filename):\n tweets = load_bz2_json(filename)\n tweet_dicts = []\n tweets_saved = 0\n for tweet in tweets:\n tweet_dict, tweets_saved = load_tweet(tweet, tweets_saved)\n if tweet_dict:\n tweet_dicts.append(tweet_dict)\n\n return tweet_dicts\n\n# filter only tweets that have text, land, education and are written in english\ndef filterTweets(tweet):\n # location = tweet['tweet_user_location']\n # coordinates = tweet['tweet_place']\n # place = tweet['tweet_coordinates']\n text = tweet['tweet_text']\n lang = tweet['tweet_user_lang']\n education = tweet['tweet_education_level']\n county = tweet['tweet_county']\n # if location or coordinates or place: ret = True\n # else: return False\n if not text or text == []: return False\n if lang != 'en': return False\n if education is None or county is None: return False\n\n return True\n\n# store all data into CSV files\ndef storeResults(traindata, vocab):\n columnIdx = {vocab[voc][0]: voc for voc in range(len(vocab))}\n\n with open(TRAIN_FEAT_CSV, 'wt') as trainFeatFile, open(TRAIN_LABS_CSV, 'wt') as trainLabsFile, open(TRAIN_FEAT_LABS_CSV, 'wt') as trainFeatLabsFile:\n trainFeatwriter = csv.writer(trainFeatFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n trainLabswriter = csv.writer(trainLabsFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n trainFeatLabswriter = csv.writer(trainFeatLabsFile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n for row in traindata:\n edu = row[0][1]\n featDict = row[1]\n feats = np.zeros(len(columnIdx))\n for key in featDict:\n try:\n feats[columnIdx[key]] = featDict[key]\n except:\n continue\n trainFeatwriter.writerow(feats.tolist())\n trainLabswriter.writerow(list(edu))\n combList = list(edu) + feats.tolist()\n trainFeatLabswriter.writerow(combList)\n\n# main function with all the Spark code\ndef main():\n fileNames = sc.parallelize([])\n\n # generate a list of all files in the data directory\n for root, dirs, files in os.walk(CACHE_DIR):\n subFileNames = sc.parallelize(files).map(lambda file: os.path.join(root, file))\n fileNames = sc.union([fileNames, subFileNames])\n # load all tweets and filter\n tweetsRdd = fileNames.flatMap(lambda file: handle_file(file)).filter(lambda tweet: filterTweets(tweet))\n # clean, parse and filter tweets and map each to county and education level\n wordsRdd = tweetsRdd.map(lambda tweet: parseTweetText(tweet)).filter(lambda tweet: filterTweets(tweet))\n # set county and education level as the key for each tweet and keep only the text as value\n countyEduRdd = wordsRdd.map(lambda tweet: ((tweet['tweet_county'], tweet['tweet_education_level']), tweet['tweet_text']))\n # aggregate tweets based on county level and generate vocabulary\n countyEduRdd = countyEduRdd.reduceByKey(lambda x, y: combineWordLists(x, y)).map(lambda z: genVocabulary(z))\n tempRes = countyEduRdd.collect()\n # print(tempRes)\n print(len(tempRes))\n vocabRDD = sc.parallelize(vocabulary.value.items())\n # filter out words that only occur once in the entire dataset (mainly noise)\n vocabRDD = vocabRDD.filter(lambda voc: True if voc[1] > 1 else False)\n # print(\"vocabulary = \", sorted(vocabulary.value.items(), key=operator.itemgetter(1)))\n vocab = sorted(vocabRDD.collect(), key=operator.itemgetter(1), reverse=True)\n # print(\"vocabulary = \", vocab)\n print(\"vocabulary size = \", len(vocab))\n storeResults(tempRes, vocab)\n\nif __name__ == \"__main__\":\n main()",
"step-ids": [
10,
14,
15,
18,
20
]
}
|
[
10,
14,
15,
18,
20
] |
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Meta-class for creating regression tests.
#
import reframe.core.namespaces as namespaces
import reframe.core.parameters as parameters
import reframe.core.variables as variables
from reframe.core.exceptions import ReframeSyntaxError
from reframe.core.hooks import HookRegistry
class RegressionTestMeta(type):
class MetaNamespace(namespaces.LocalNamespace):
'''Custom namespace to control the cls attribute assignment.
Regular Python class attributes can be overriden by either
parameters or variables respecting the order of execution.
A variable or a parameter may not be declared more than once in the
same class body. Overriding a variable with a parameter or the other
way around has an undefined behaviour. A variable's value may be
updated multiple times within the same class body. A parameter's
value may not be updated more than once within the same class body.
'''
def __setitem__(self, key, value):
if isinstance(value, variables.TestVar):
# Insert the attribute in the variable namespace
self['_rfm_local_var_space'][key] = value
value.__set_name__(self, key)
# Override the regular class attribute (if present)
self._namespace.pop(key, None)
elif isinstance(value, parameters.TestParam):
# Insert the attribute in the parameter namespace
self['_rfm_local_param_space'][key] = value
# Override the regular class attribute (if present)
self._namespace.pop(key, None)
elif key in self['_rfm_local_param_space']:
raise ValueError(
f'cannot override parameter {key!r}'
)
else:
# Insert the items manually to overide the namespace clash
# check from the base namespace.
self._namespace[key] = value
def __getitem__(self, key):
'''Expose and control access to the local namespaces.
Variables may only be retrieved if their value has been previously
set. Accessing a parameter in the class body is disallowed (the
actual test parameter is set during the class instantiation).
'''
try:
return super().__getitem__(key)
except KeyError as err:
try:
# Handle variable access
return self['_rfm_local_var_space'][key]
except KeyError:
# Handle parameter access
if key in self['_rfm_local_param_space']:
raise ValueError(
'accessing a test parameter from the class '
'body is disallowed'
) from None
else:
# As the last resource, look if key is a variable in
# any of the base classes. If so, make its value
# available in the current class' namespace.
for b in self['_rfm_bases']:
if key in b._rfm_var_space:
# Store a deep-copy of the variable's
# value and return.
v = b._rfm_var_space[key].default_value
self._namespace[key] = v
return self._namespace[key]
# If 'key' is neither a variable nor a parameter,
# raise the exception from the base __getitem__.
raise err from None
@classmethod
def __prepare__(metacls, name, bases, **kwargs):
namespace = super().__prepare__(name, bases, **kwargs)
# Keep reference to the bases inside the namespace
namespace['_rfm_bases'] = [
b for b in bases if hasattr(b, '_rfm_var_space')
]
# Regression test parameter space defined at the class level
local_param_space = namespaces.LocalNamespace()
namespace['_rfm_local_param_space'] = local_param_space
# Directive to insert a regression test parameter directly in the
# class body as: `P0 = parameter([0,1,2,3])`.
namespace['parameter'] = parameters.TestParam
# Regression test var space defined at the class level
local_var_space = namespaces.LocalNamespace()
namespace['_rfm_local_var_space'] = local_var_space
# Directives to add/modify a regression test variable
namespace['variable'] = variables.TestVar
namespace['required'] = variables.Undefined
return metacls.MetaNamespace(namespace)
def __new__(metacls, name, bases, namespace, **kwargs):
return super().__new__(metacls, name, bases, dict(namespace), **kwargs)
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
# Create a set with the attribute names already in use.
cls._rfm_dir = set()
for base in bases:
if hasattr(base, '_rfm_dir'):
cls._rfm_dir.update(base._rfm_dir)
used_attribute_names = set(cls._rfm_dir)
# Build the var space and extend the target namespace
variables.VarSpace(cls, used_attribute_names)
used_attribute_names.update(cls._rfm_var_space.vars)
# Build the parameter space
parameters.ParamSpace(cls, used_attribute_names)
# Update used names set with the local __dict__
cls._rfm_dir.update(cls.__dict__)
# Set up the hooks for the pipeline stages based on the _rfm_attach
# attribute; all dependencies will be resolved first in the post-setup
# phase if not assigned elsewhere
hooks = HookRegistry.create(namespace)
for b in bases:
if hasattr(b, '_rfm_pipeline_hooks'):
hooks.update(getattr(b, '_rfm_pipeline_hooks'))
cls._rfm_pipeline_hooks = hooks # HookRegistry(local_hooks)
cls._final_methods = {v.__name__ for v in namespace.values()
if hasattr(v, '_rfm_final')}
# Add the final functions from its parents
cls._final_methods.update(*(b._final_methods for b in bases
if hasattr(b, '_final_methods')))
if hasattr(cls, '_rfm_special_test') and cls._rfm_special_test:
return
for v in namespace.values():
for b in bases:
if not hasattr(b, '_final_methods'):
continue
if callable(v) and v.__name__ in b._final_methods:
msg = (f"'{cls.__qualname__}.{v.__name__}' attempts to "
f"override final method "
f"'{b.__qualname__}.{v.__name__}'; "
f"you should use the pipeline hooks instead")
raise ReframeSyntaxError(msg)
def __call__(cls, *args, **kwargs):
'''Intercept reframe-specific constructor arguments.
When registering a regression test using any supported decorator,
this decorator may pass additional arguments to the class constructor
to perform specific reframe-internal actions. This gives extra control
over the class instantiation process, allowing reframe to instantiate
the regression test class differently if this class was registered or
not (e.g. when deep-copying a regression test object). These interal
arguments must be intercepted before the object initialization, since
these would otherwise affect the __init__ method's signature, and these
internal mechanisms must be fully transparent to the user.
'''
obj = cls.__new__(cls, *args, **kwargs)
# Intercept constructor arguments
kwargs.pop('_rfm_use_params', None)
obj.__init__(*args, **kwargs)
return obj
def __getattr__(cls, name):
''' Attribute lookup method for the MetaNamespace.
This metaclass implements a custom namespace, where built-in `variable`
and `parameter` types are stored in their own sub-namespaces (see
:class:`reframe.core.meta.RegressionTestMeta.MetaNamespace`).
This method will perform an attribute lookup on these sub-namespaces if
a call to the default `__getattribute__` method fails to retrieve the
requested class attribute.
'''
try:
return cls._rfm_var_space.vars[name]
except KeyError:
try:
return cls._rfm_param_space.params[name]
except KeyError:
raise AttributeError(
f'class {cls.__qualname__!r} has no attribute {name!r}'
) from None
@property
def param_space(cls):
# Make the parameter space available as read-only
return cls._rfm_param_space
def is_abstract(cls):
'''Check if the class is an abstract test.
This is the case when some parameters are undefined, which results in
the length of the parameter space being 0.
:return: bool indicating wheteher the test has undefined parameters.
:meta private:
'''
return len(cls.param_space) == 0
|
normal
|
{
"blob_id": "e754a24fc9c965c50f7fa12036c884a1a54cc29d",
"index": 6853,
"step-1": "<mask token>\n\n\nclass RegressionTestMeta(type):\n\n\n class MetaNamespace(namespaces.LocalNamespace):\n \"\"\"Custom namespace to control the cls attribute assignment.\n\n Regular Python class attributes can be overriden by either\n parameters or variables respecting the order of execution.\n A variable or a parameter may not be declared more than once in the\n same class body. Overriding a variable with a parameter or the other\n way around has an undefined behaviour. A variable's value may be\n updated multiple times within the same class body. A parameter's\n value may not be updated more than once within the same class body.\n \"\"\"\n\n def __setitem__(self, key, value):\n if isinstance(value, variables.TestVar):\n self['_rfm_local_var_space'][key] = value\n value.__set_name__(self, key)\n self._namespace.pop(key, None)\n elif isinstance(value, parameters.TestParam):\n self['_rfm_local_param_space'][key] = value\n self._namespace.pop(key, None)\n elif key in self['_rfm_local_param_space']:\n raise ValueError(f'cannot override parameter {key!r}')\n else:\n self._namespace[key] = value\n\n def __getitem__(self, key):\n \"\"\"Expose and control access to the local namespaces.\n\n Variables may only be retrieved if their value has been previously\n set. Accessing a parameter in the class body is disallowed (the\n actual test parameter is set during the class instantiation).\n \"\"\"\n try:\n return super().__getitem__(key)\n except KeyError as err:\n try:\n return self['_rfm_local_var_space'][key]\n except KeyError:\n if key in self['_rfm_local_param_space']:\n raise ValueError(\n 'accessing a test parameter from the class body is disallowed'\n ) from None\n else:\n for b in self['_rfm_bases']:\n if key in b._rfm_var_space:\n v = b._rfm_var_space[key].default_value\n self._namespace[key] = v\n return self._namespace[key]\n raise err from None\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n namespace = super().__prepare__(name, bases, **kwargs)\n namespace['_rfm_bases'] = [b for b in bases if hasattr(b,\n '_rfm_var_space')]\n local_param_space = namespaces.LocalNamespace()\n namespace['_rfm_local_param_space'] = local_param_space\n namespace['parameter'] = parameters.TestParam\n local_var_space = namespaces.LocalNamespace()\n namespace['_rfm_local_var_space'] = local_var_space\n namespace['variable'] = variables.TestVar\n namespace['required'] = variables.Undefined\n return metacls.MetaNamespace(namespace)\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 RegressionTestMeta(type):\n\n\n class MetaNamespace(namespaces.LocalNamespace):\n \"\"\"Custom namespace to control the cls attribute assignment.\n\n Regular Python class attributes can be overriden by either\n parameters or variables respecting the order of execution.\n A variable or a parameter may not be declared more than once in the\n same class body. Overriding a variable with a parameter or the other\n way around has an undefined behaviour. A variable's value may be\n updated multiple times within the same class body. A parameter's\n value may not be updated more than once within the same class body.\n \"\"\"\n\n def __setitem__(self, key, value):\n if isinstance(value, variables.TestVar):\n self['_rfm_local_var_space'][key] = value\n value.__set_name__(self, key)\n self._namespace.pop(key, None)\n elif isinstance(value, parameters.TestParam):\n self['_rfm_local_param_space'][key] = value\n self._namespace.pop(key, None)\n elif key in self['_rfm_local_param_space']:\n raise ValueError(f'cannot override parameter {key!r}')\n else:\n self._namespace[key] = value\n\n def __getitem__(self, key):\n \"\"\"Expose and control access to the local namespaces.\n\n Variables may only be retrieved if their value has been previously\n set. Accessing a parameter in the class body is disallowed (the\n actual test parameter is set during the class instantiation).\n \"\"\"\n try:\n return super().__getitem__(key)\n except KeyError as err:\n try:\n return self['_rfm_local_var_space'][key]\n except KeyError:\n if key in self['_rfm_local_param_space']:\n raise ValueError(\n 'accessing a test parameter from the class body is disallowed'\n ) from None\n else:\n for b in self['_rfm_bases']:\n if key in b._rfm_var_space:\n v = b._rfm_var_space[key].default_value\n self._namespace[key] = v\n return self._namespace[key]\n raise err from None\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n namespace = super().__prepare__(name, bases, **kwargs)\n namespace['_rfm_bases'] = [b for b in bases if hasattr(b,\n '_rfm_var_space')]\n local_param_space = namespaces.LocalNamespace()\n namespace['_rfm_local_param_space'] = local_param_space\n namespace['parameter'] = parameters.TestParam\n local_var_space = namespaces.LocalNamespace()\n namespace['_rfm_local_var_space'] = local_var_space\n namespace['variable'] = variables.TestVar\n namespace['required'] = variables.Undefined\n return metacls.MetaNamespace(namespace)\n <mask token>\n\n def __init__(cls, name, bases, namespace, **kwargs):\n super().__init__(name, bases, namespace, **kwargs)\n cls._rfm_dir = set()\n for base in bases:\n if hasattr(base, '_rfm_dir'):\n cls._rfm_dir.update(base._rfm_dir)\n used_attribute_names = set(cls._rfm_dir)\n variables.VarSpace(cls, used_attribute_names)\n used_attribute_names.update(cls._rfm_var_space.vars)\n parameters.ParamSpace(cls, used_attribute_names)\n cls._rfm_dir.update(cls.__dict__)\n hooks = HookRegistry.create(namespace)\n for b in bases:\n if hasattr(b, '_rfm_pipeline_hooks'):\n hooks.update(getattr(b, '_rfm_pipeline_hooks'))\n cls._rfm_pipeline_hooks = hooks\n cls._final_methods = {v.__name__ for v in namespace.values() if\n hasattr(v, '_rfm_final')}\n cls._final_methods.update(*(b._final_methods for b in bases if\n hasattr(b, '_final_methods')))\n if hasattr(cls, '_rfm_special_test') and cls._rfm_special_test:\n return\n for v in namespace.values():\n for b in bases:\n if not hasattr(b, '_final_methods'):\n continue\n if callable(v) and v.__name__ in b._final_methods:\n msg = (\n f\"'{cls.__qualname__}.{v.__name__}' attempts to override final method '{b.__qualname__}.{v.__name__}'; you should use the pipeline hooks instead\"\n )\n raise ReframeSyntaxError(msg)\n\n def __call__(cls, *args, **kwargs):\n \"\"\"Intercept reframe-specific constructor arguments.\n\n When registering a regression test using any supported decorator,\n this decorator may pass additional arguments to the class constructor\n to perform specific reframe-internal actions. This gives extra control\n over the class instantiation process, allowing reframe to instantiate\n the regression test class differently if this class was registered or\n not (e.g. when deep-copying a regression test object). These interal\n arguments must be intercepted before the object initialization, since\n these would otherwise affect the __init__ method's signature, and these\n internal mechanisms must be fully transparent to the user.\n \"\"\"\n obj = cls.__new__(cls, *args, **kwargs)\n kwargs.pop('_rfm_use_params', None)\n obj.__init__(*args, **kwargs)\n return obj\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass RegressionTestMeta(type):\n\n\n class MetaNamespace(namespaces.LocalNamespace):\n \"\"\"Custom namespace to control the cls attribute assignment.\n\n Regular Python class attributes can be overriden by either\n parameters or variables respecting the order of execution.\n A variable or a parameter may not be declared more than once in the\n same class body. Overriding a variable with a parameter or the other\n way around has an undefined behaviour. A variable's value may be\n updated multiple times within the same class body. A parameter's\n value may not be updated more than once within the same class body.\n \"\"\"\n\n def __setitem__(self, key, value):\n if isinstance(value, variables.TestVar):\n self['_rfm_local_var_space'][key] = value\n value.__set_name__(self, key)\n self._namespace.pop(key, None)\n elif isinstance(value, parameters.TestParam):\n self['_rfm_local_param_space'][key] = value\n self._namespace.pop(key, None)\n elif key in self['_rfm_local_param_space']:\n raise ValueError(f'cannot override parameter {key!r}')\n else:\n self._namespace[key] = value\n\n def __getitem__(self, key):\n \"\"\"Expose and control access to the local namespaces.\n\n Variables may only be retrieved if their value has been previously\n set. Accessing a parameter in the class body is disallowed (the\n actual test parameter is set during the class instantiation).\n \"\"\"\n try:\n return super().__getitem__(key)\n except KeyError as err:\n try:\n return self['_rfm_local_var_space'][key]\n except KeyError:\n if key in self['_rfm_local_param_space']:\n raise ValueError(\n 'accessing a test parameter from the class body is disallowed'\n ) from None\n else:\n for b in self['_rfm_bases']:\n if key in b._rfm_var_space:\n v = b._rfm_var_space[key].default_value\n self._namespace[key] = v\n return self._namespace[key]\n raise err from None\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n namespace = super().__prepare__(name, bases, **kwargs)\n namespace['_rfm_bases'] = [b for b in bases if hasattr(b,\n '_rfm_var_space')]\n local_param_space = namespaces.LocalNamespace()\n namespace['_rfm_local_param_space'] = local_param_space\n namespace['parameter'] = parameters.TestParam\n local_var_space = namespaces.LocalNamespace()\n namespace['_rfm_local_var_space'] = local_var_space\n namespace['variable'] = variables.TestVar\n namespace['required'] = variables.Undefined\n return metacls.MetaNamespace(namespace)\n\n def __new__(metacls, name, bases, namespace, **kwargs):\n return super().__new__(metacls, name, bases, dict(namespace), **kwargs)\n\n def __init__(cls, name, bases, namespace, **kwargs):\n super().__init__(name, bases, namespace, **kwargs)\n cls._rfm_dir = set()\n for base in bases:\n if hasattr(base, '_rfm_dir'):\n cls._rfm_dir.update(base._rfm_dir)\n used_attribute_names = set(cls._rfm_dir)\n variables.VarSpace(cls, used_attribute_names)\n used_attribute_names.update(cls._rfm_var_space.vars)\n parameters.ParamSpace(cls, used_attribute_names)\n cls._rfm_dir.update(cls.__dict__)\n hooks = HookRegistry.create(namespace)\n for b in bases:\n if hasattr(b, '_rfm_pipeline_hooks'):\n hooks.update(getattr(b, '_rfm_pipeline_hooks'))\n cls._rfm_pipeline_hooks = hooks\n cls._final_methods = {v.__name__ for v in namespace.values() if\n hasattr(v, '_rfm_final')}\n cls._final_methods.update(*(b._final_methods for b in bases if\n hasattr(b, '_final_methods')))\n if hasattr(cls, '_rfm_special_test') and cls._rfm_special_test:\n return\n for v in namespace.values():\n for b in bases:\n if not hasattr(b, '_final_methods'):\n continue\n if callable(v) and v.__name__ in b._final_methods:\n msg = (\n f\"'{cls.__qualname__}.{v.__name__}' attempts to override final method '{b.__qualname__}.{v.__name__}'; you should use the pipeline hooks instead\"\n )\n raise ReframeSyntaxError(msg)\n\n def __call__(cls, *args, **kwargs):\n \"\"\"Intercept reframe-specific constructor arguments.\n\n When registering a regression test using any supported decorator,\n this decorator may pass additional arguments to the class constructor\n to perform specific reframe-internal actions. This gives extra control\n over the class instantiation process, allowing reframe to instantiate\n the regression test class differently if this class was registered or\n not (e.g. when deep-copying a regression test object). These interal\n arguments must be intercepted before the object initialization, since\n these would otherwise affect the __init__ method's signature, and these\n internal mechanisms must be fully transparent to the user.\n \"\"\"\n obj = cls.__new__(cls, *args, **kwargs)\n kwargs.pop('_rfm_use_params', None)\n obj.__init__(*args, **kwargs)\n return obj\n <mask token>\n\n @property\n def param_space(cls):\n return cls._rfm_param_space\n <mask token>\n",
"step-4": "<mask token>\n\n\nclass RegressionTestMeta(type):\n\n\n class MetaNamespace(namespaces.LocalNamespace):\n \"\"\"Custom namespace to control the cls attribute assignment.\n\n Regular Python class attributes can be overriden by either\n parameters or variables respecting the order of execution.\n A variable or a parameter may not be declared more than once in the\n same class body. Overriding a variable with a parameter or the other\n way around has an undefined behaviour. A variable's value may be\n updated multiple times within the same class body. A parameter's\n value may not be updated more than once within the same class body.\n \"\"\"\n\n def __setitem__(self, key, value):\n if isinstance(value, variables.TestVar):\n self['_rfm_local_var_space'][key] = value\n value.__set_name__(self, key)\n self._namespace.pop(key, None)\n elif isinstance(value, parameters.TestParam):\n self['_rfm_local_param_space'][key] = value\n self._namespace.pop(key, None)\n elif key in self['_rfm_local_param_space']:\n raise ValueError(f'cannot override parameter {key!r}')\n else:\n self._namespace[key] = value\n\n def __getitem__(self, key):\n \"\"\"Expose and control access to the local namespaces.\n\n Variables may only be retrieved if their value has been previously\n set. Accessing a parameter in the class body is disallowed (the\n actual test parameter is set during the class instantiation).\n \"\"\"\n try:\n return super().__getitem__(key)\n except KeyError as err:\n try:\n return self['_rfm_local_var_space'][key]\n except KeyError:\n if key in self['_rfm_local_param_space']:\n raise ValueError(\n 'accessing a test parameter from the class body is disallowed'\n ) from None\n else:\n for b in self['_rfm_bases']:\n if key in b._rfm_var_space:\n v = b._rfm_var_space[key].default_value\n self._namespace[key] = v\n return self._namespace[key]\n raise err from None\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n namespace = super().__prepare__(name, bases, **kwargs)\n namespace['_rfm_bases'] = [b for b in bases if hasattr(b,\n '_rfm_var_space')]\n local_param_space = namespaces.LocalNamespace()\n namespace['_rfm_local_param_space'] = local_param_space\n namespace['parameter'] = parameters.TestParam\n local_var_space = namespaces.LocalNamespace()\n namespace['_rfm_local_var_space'] = local_var_space\n namespace['variable'] = variables.TestVar\n namespace['required'] = variables.Undefined\n return metacls.MetaNamespace(namespace)\n\n def __new__(metacls, name, bases, namespace, **kwargs):\n return super().__new__(metacls, name, bases, dict(namespace), **kwargs)\n\n def __init__(cls, name, bases, namespace, **kwargs):\n super().__init__(name, bases, namespace, **kwargs)\n cls._rfm_dir = set()\n for base in bases:\n if hasattr(base, '_rfm_dir'):\n cls._rfm_dir.update(base._rfm_dir)\n used_attribute_names = set(cls._rfm_dir)\n variables.VarSpace(cls, used_attribute_names)\n used_attribute_names.update(cls._rfm_var_space.vars)\n parameters.ParamSpace(cls, used_attribute_names)\n cls._rfm_dir.update(cls.__dict__)\n hooks = HookRegistry.create(namespace)\n for b in bases:\n if hasattr(b, '_rfm_pipeline_hooks'):\n hooks.update(getattr(b, '_rfm_pipeline_hooks'))\n cls._rfm_pipeline_hooks = hooks\n cls._final_methods = {v.__name__ for v in namespace.values() if\n hasattr(v, '_rfm_final')}\n cls._final_methods.update(*(b._final_methods for b in bases if\n hasattr(b, '_final_methods')))\n if hasattr(cls, '_rfm_special_test') and cls._rfm_special_test:\n return\n for v in namespace.values():\n for b in bases:\n if not hasattr(b, '_final_methods'):\n continue\n if callable(v) and v.__name__ in b._final_methods:\n msg = (\n f\"'{cls.__qualname__}.{v.__name__}' attempts to override final method '{b.__qualname__}.{v.__name__}'; you should use the pipeline hooks instead\"\n )\n raise ReframeSyntaxError(msg)\n\n def __call__(cls, *args, **kwargs):\n \"\"\"Intercept reframe-specific constructor arguments.\n\n When registering a regression test using any supported decorator,\n this decorator may pass additional arguments to the class constructor\n to perform specific reframe-internal actions. This gives extra control\n over the class instantiation process, allowing reframe to instantiate\n the regression test class differently if this class was registered or\n not (e.g. when deep-copying a regression test object). These interal\n arguments must be intercepted before the object initialization, since\n these would otherwise affect the __init__ method's signature, and these\n internal mechanisms must be fully transparent to the user.\n \"\"\"\n obj = cls.__new__(cls, *args, **kwargs)\n kwargs.pop('_rfm_use_params', None)\n obj.__init__(*args, **kwargs)\n return obj\n\n def __getattr__(cls, name):\n \"\"\" Attribute lookup method for the MetaNamespace.\n\n This metaclass implements a custom namespace, where built-in `variable`\n and `parameter` types are stored in their own sub-namespaces (see\n :class:`reframe.core.meta.RegressionTestMeta.MetaNamespace`).\n This method will perform an attribute lookup on these sub-namespaces if\n a call to the default `__getattribute__` method fails to retrieve the\n requested class attribute.\n \"\"\"\n try:\n return cls._rfm_var_space.vars[name]\n except KeyError:\n try:\n return cls._rfm_param_space.params[name]\n except KeyError:\n raise AttributeError(\n f'class {cls.__qualname__!r} has no attribute {name!r}'\n ) from None\n\n @property\n def param_space(cls):\n return cls._rfm_param_space\n\n def is_abstract(cls):\n \"\"\"Check if the class is an abstract test.\n\n This is the case when some parameters are undefined, which results in\n the length of the parameter space being 0.\n\n :return: bool indicating wheteher the test has undefined parameters.\n\n :meta private:\n \"\"\"\n return len(cls.param_space) == 0\n",
"step-5": "# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)\n# ReFrame Project Developers. See the top-level LICENSE file for details.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n\n#\n# Meta-class for creating regression tests.\n#\n\n\nimport reframe.core.namespaces as namespaces\nimport reframe.core.parameters as parameters\nimport reframe.core.variables as variables\n\nfrom reframe.core.exceptions import ReframeSyntaxError\nfrom reframe.core.hooks import HookRegistry\n\n\nclass RegressionTestMeta(type):\n\n class MetaNamespace(namespaces.LocalNamespace):\n '''Custom namespace to control the cls attribute assignment.\n\n Regular Python class attributes can be overriden by either\n parameters or variables respecting the order of execution.\n A variable or a parameter may not be declared more than once in the\n same class body. Overriding a variable with a parameter or the other\n way around has an undefined behaviour. A variable's value may be\n updated multiple times within the same class body. A parameter's\n value may not be updated more than once within the same class body.\n '''\n\n def __setitem__(self, key, value):\n if isinstance(value, variables.TestVar):\n # Insert the attribute in the variable namespace\n self['_rfm_local_var_space'][key] = value\n value.__set_name__(self, key)\n\n # Override the regular class attribute (if present)\n self._namespace.pop(key, None)\n\n elif isinstance(value, parameters.TestParam):\n # Insert the attribute in the parameter namespace\n self['_rfm_local_param_space'][key] = value\n\n # Override the regular class attribute (if present)\n self._namespace.pop(key, None)\n\n elif key in self['_rfm_local_param_space']:\n raise ValueError(\n f'cannot override parameter {key!r}'\n )\n else:\n # Insert the items manually to overide the namespace clash\n # check from the base namespace.\n self._namespace[key] = value\n\n def __getitem__(self, key):\n '''Expose and control access to the local namespaces.\n\n Variables may only be retrieved if their value has been previously\n set. Accessing a parameter in the class body is disallowed (the\n actual test parameter is set during the class instantiation).\n '''\n try:\n return super().__getitem__(key)\n except KeyError as err:\n try:\n # Handle variable access\n return self['_rfm_local_var_space'][key]\n\n except KeyError:\n # Handle parameter access\n if key in self['_rfm_local_param_space']:\n raise ValueError(\n 'accessing a test parameter from the class '\n 'body is disallowed'\n ) from None\n else:\n # As the last resource, look if key is a variable in\n # any of the base classes. If so, make its value\n # available in the current class' namespace.\n for b in self['_rfm_bases']:\n if key in b._rfm_var_space:\n # Store a deep-copy of the variable's\n # value and return.\n v = b._rfm_var_space[key].default_value\n self._namespace[key] = v\n return self._namespace[key]\n\n # If 'key' is neither a variable nor a parameter,\n # raise the exception from the base __getitem__.\n raise err from None\n\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n namespace = super().__prepare__(name, bases, **kwargs)\n\n # Keep reference to the bases inside the namespace\n namespace['_rfm_bases'] = [\n b for b in bases if hasattr(b, '_rfm_var_space')\n ]\n\n # Regression test parameter space defined at the class level\n local_param_space = namespaces.LocalNamespace()\n namespace['_rfm_local_param_space'] = local_param_space\n\n # Directive to insert a regression test parameter directly in the\n # class body as: `P0 = parameter([0,1,2,3])`.\n namespace['parameter'] = parameters.TestParam\n\n # Regression test var space defined at the class level\n local_var_space = namespaces.LocalNamespace()\n namespace['_rfm_local_var_space'] = local_var_space\n\n # Directives to add/modify a regression test variable\n namespace['variable'] = variables.TestVar\n namespace['required'] = variables.Undefined\n return metacls.MetaNamespace(namespace)\n\n def __new__(metacls, name, bases, namespace, **kwargs):\n return super().__new__(metacls, name, bases, dict(namespace), **kwargs)\n\n def __init__(cls, name, bases, namespace, **kwargs):\n super().__init__(name, bases, namespace, **kwargs)\n\n # Create a set with the attribute names already in use.\n cls._rfm_dir = set()\n for base in bases:\n if hasattr(base, '_rfm_dir'):\n cls._rfm_dir.update(base._rfm_dir)\n\n used_attribute_names = set(cls._rfm_dir)\n\n # Build the var space and extend the target namespace\n variables.VarSpace(cls, used_attribute_names)\n used_attribute_names.update(cls._rfm_var_space.vars)\n\n # Build the parameter space\n parameters.ParamSpace(cls, used_attribute_names)\n\n # Update used names set with the local __dict__\n cls._rfm_dir.update(cls.__dict__)\n\n # Set up the hooks for the pipeline stages based on the _rfm_attach\n # attribute; all dependencies will be resolved first in the post-setup\n # phase if not assigned elsewhere\n hooks = HookRegistry.create(namespace)\n for b in bases:\n if hasattr(b, '_rfm_pipeline_hooks'):\n hooks.update(getattr(b, '_rfm_pipeline_hooks'))\n\n cls._rfm_pipeline_hooks = hooks # HookRegistry(local_hooks)\n cls._final_methods = {v.__name__ for v in namespace.values()\n if hasattr(v, '_rfm_final')}\n\n # Add the final functions from its parents\n cls._final_methods.update(*(b._final_methods for b in bases\n if hasattr(b, '_final_methods')))\n\n if hasattr(cls, '_rfm_special_test') and cls._rfm_special_test:\n return\n\n for v in namespace.values():\n for b in bases:\n if not hasattr(b, '_final_methods'):\n continue\n\n if callable(v) and v.__name__ in b._final_methods:\n msg = (f\"'{cls.__qualname__}.{v.__name__}' attempts to \"\n f\"override final method \"\n f\"'{b.__qualname__}.{v.__name__}'; \"\n f\"you should use the pipeline hooks instead\")\n raise ReframeSyntaxError(msg)\n\n def __call__(cls, *args, **kwargs):\n '''Intercept reframe-specific constructor arguments.\n\n When registering a regression test using any supported decorator,\n this decorator may pass additional arguments to the class constructor\n to perform specific reframe-internal actions. This gives extra control\n over the class instantiation process, allowing reframe to instantiate\n the regression test class differently if this class was registered or\n not (e.g. when deep-copying a regression test object). These interal\n arguments must be intercepted before the object initialization, since\n these would otherwise affect the __init__ method's signature, and these\n internal mechanisms must be fully transparent to the user.\n '''\n obj = cls.__new__(cls, *args, **kwargs)\n\n # Intercept constructor arguments\n kwargs.pop('_rfm_use_params', None)\n\n obj.__init__(*args, **kwargs)\n return obj\n\n def __getattr__(cls, name):\n ''' Attribute lookup method for the MetaNamespace.\n\n This metaclass implements a custom namespace, where built-in `variable`\n and `parameter` types are stored in their own sub-namespaces (see\n :class:`reframe.core.meta.RegressionTestMeta.MetaNamespace`).\n This method will perform an attribute lookup on these sub-namespaces if\n a call to the default `__getattribute__` method fails to retrieve the\n requested class attribute.\n '''\n try:\n return cls._rfm_var_space.vars[name]\n except KeyError:\n try:\n return cls._rfm_param_space.params[name]\n except KeyError:\n raise AttributeError(\n f'class {cls.__qualname__!r} has no attribute {name!r}'\n ) from None\n\n @property\n def param_space(cls):\n # Make the parameter space available as read-only\n return cls._rfm_param_space\n\n def is_abstract(cls):\n '''Check if the class is an abstract test.\n\n This is the case when some parameters are undefined, which results in\n the length of the parameter space being 0.\n\n :return: bool indicating wheteher the test has undefined parameters.\n\n :meta private:\n '''\n return len(cls.param_space) == 0\n",
"step-ids": [
2,
4,
6,
8,
10
]
}
|
[
2,
4,
6,
8,
10
] |
from Modules.Pitch.Factory import MainFactory
from Modules.ToJson import Oto
from audiolazy.lazy_midi import midi2str
import utaupy
import string
import random
import math
import os, subprocess, shutil
def RandomString(Length):
Letters = string.ascii_lowercase
return ''.join(random.choice(Letters) for i in range(Length))
UST_FILE = "filet.ust"
OTO_FILE = "Voice\\NanaMio\\oto.ini"
VB_PATH = "Voice\\NanaMio"
RESAMPLER_PATH = "Resampler\\macres.exe"
WAVTOOL_PATH = "Resampler\\wavtool-yawu.exe"
CACHE_PATH = "Cache\\"
OUTPUT_FILE = "temp.wav"
UstObject = utaupy.ust.load(UST_FILE)
OtoObject = Oto(OTO_FILE)
UstParts = UstObject.notes[4:28]
shutil.rmtree(os.path.join(os.getcwd(), CACHE_PATH))
os.mkdir(os.path.join(os.getcwd(), CACHE_PATH))
PreviousNote = -1
PreviousLength = 0
Tempo = round(float(UstObject.tempo))
MSPassed = 0
open(OUTPUT_FILE, "w+")
for NIndex, Note in enumerate(UstParts):
print("prevnote", PreviousNote)
Rest = False
if Note.lyric in OtoObject.keys():
LocalOto = OtoObject[Note.lyric]
else:
LocalOto = None
Rest = True
Lyric = Note.lyric
Length = Note.length
NoteNum = Note.notenum
PreUtterance = float(LocalOto["PreUtterance"]) if not Rest else 0
Velocity = Note.velocity
# try:
# PreUtterance = Note.get_by_key("PreUtterance")
# except KeyError:
# PreUtterance = 0
try:
StartPoint = Note.get_by_key("StartPoint")
except KeyError:
StartPoint = 0
try:
PBS = Note.pbs
except KeyError:
PBS = None
try:
PBW = Note["PBW"].split(",")
except KeyError:
PBW = None
try:
PBY = Note["PBY"].split(",")
for Index, Var in enumerate(PBY):
if Var == "":
PBY[Index] = "0"
except KeyError:
PBY = []
try:
PBM = Note.pbm
except KeyError:
PBM = []
try:
VBR = Note.get_by_key("VBR").split(",")
except KeyError:
VBR = None
try:
Flags = Note.get_by_key("Flags")
except KeyError:
Flags = "?"
try:
Modulation = Note.get_by_key("Modulation")
except KeyError:
Modulation = 100
try:
Intensity = Note.get_by_key("Intensity")
except KeyError:
Intensity = 100
try:
StartPoint = Note.get_by_key("StartPoint")
except KeyError:
StartPoint = 0
try:
Envelope = Note.get_by_key("Envelope")
Envelope = Envelope.replace("%", LocalOto["Overlap"]).split(",")
except (KeyError, TypeError):
Envelope = ["0","5","35","0","100","100","0"]
FileOrder = f"{NIndex:05}"
if Rest:
# Parameters = [os.path.join(os.getcwd(), RESAMPLER_PATH),os.path.join(os.getcwd(), CACHE_PATH, SILENCE_FILE), os.path.join(os.getcwd(),f"{FileOrder}_Blank_{RandomString(6)}.wav"),utaupy.ust.notenum_as_abc(NoteNum),"100","?","0",str(int(Length//50 *50 if Length/50 - Length//50 < 0.5 else math.ceil(Length/50) * 50)),"0","0","100","0"]
# Segment = AudioSegment.silent(duration=Length)
WavtoolParam = [
os.path.join(os.getcwd(), WAVTOOL_PATH),
os.path.join(os.getcwd(), OUTPUT_FILE),
OutputFile,
str(MSPassed),
str(Length)
] + (["0"] * 11)
PreviousNote = -1
MSPassed += float(Length)
subprocess.call(WavtoolParam)
else:
if PreviousNote == -1:
PrevNote = NoteNum
else:
PrevNote = int(PreviousNote)
if PBS is not None and PBW is not None:
PB = MainFactory()
PB.AddPitchBends(MSPassed, MSPassed + float(Length), PBS, PBW, PrevNoteNum=PrevNote, CurrentNoteNum=NoteNum, PBY=PBY, PBM=PBM, VBR=VBR)
PitchBendData = PB.RenderPitchBends(int(math.ceil((MSPassed + PBS[0]) / 5)), int(math.floor((MSPassed + float(Length)) / 5)), NoteNum)
else:
PitchBendData = None
# Bite Correction (The previous note should last for half the length before overlap)
if PreUtterance - float(LocalOto["Overlap"]) > (PreviousLength // 2):
CorrectionRate = (PreviousLength // 2) / (PreUtterance - float(LocalOto["Overlap"]))
BitedPreUtterance = PreUtterance * CorrectionRate
BitedOverlap = float(LocalOto["Overlap"]) * CorrectionRate
else:
BitedPreUtterance = PreUtterance
BitedOverlap = float(LocalOto["Overlap"])
BitedSTP = PreUtterance - BitedPreUtterance
LengthRequire = Length + float(StartPoint) - BitedSTP + BitedOverlap + 50
if LengthRequire < float(LocalOto["Consonant"]):
LengthRequire = float(LocalOto["Consonant"])
LengthRequire = LengthRequire//50 *50 if LengthRequire/50 - LengthRequire//50 < 0.5 else math.ceil(LengthRequire/50) * 50
InputFile = os.path.join(os.getcwd(), VB_PATH, LocalOto["File"])
OutputFile = os.path.join(os.getcwd(), CACHE_PATH, f"{FileOrder}_{Lyric}_{RandomString(6)}.wav")
Parameters = [
os.path.join(os.getcwd(), RESAMPLER_PATH),
InputFile,
OutputFile,
midi2str(NoteNum),
str(Velocity),
Flags,
LocalOto["Offset"],
str(int(LengthRequire)),
LocalOto["Consonant"],
LocalOto["Cutoff"],
Intensity,
Modulation,
f"!{Tempo}" if PitchBendData is not None else "",
f"{PitchBendData}" if PitchBendData is not None else ""
]
print(Parameters)
PreviousNote = NoteNum
PreviousLength = float(Length)
MSPassed += float(Length)
subprocess.call(Parameters)
if NIndex + 1 < len(UstParts) and UstParts[NIndex+1].lyric in OtoObject.keys():
NextOto = OtoObject[UstParts[NIndex+1].lyric]
NextPreUtterance = float(NextOto["PreUtterance"])
NextOverlap = float(NextOto["Overlap"])
WavtoolCorrection = PreUtterance - NextPreUtterance + NextOverlap
else:
WavtoolCorrection = PreUtterance
sign = "+" if WavtoolCorrection >= 0 else ""
WavtoolParam = [
os.path.join(os.getcwd(), WAVTOOL_PATH),
os.path.join(os.getcwd(), OUTPUT_FILE),
OutputFile,
str(float(StartPoint)),
f"{Length}@{float(Tempo)}{sign}{WavtoolCorrection}"
] + [str(i) for i in Envelope]
subprocess.call(WavtoolParam)
|
normal
|
{
"blob_id": "ce11a5c2fbd6e0ea0f8ab293dc53afd07a18c25c",
"index": 6160,
"step-1": "<mask token>\n\n\ndef RandomString(Length):\n Letters = string.ascii_lowercase\n return ''.join(random.choice(Letters) for i in range(Length))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef RandomString(Length):\n Letters = string.ascii_lowercase\n return ''.join(random.choice(Letters) for i in range(Length))\n\n\n<mask token>\nshutil.rmtree(os.path.join(os.getcwd(), CACHE_PATH))\nos.mkdir(os.path.join(os.getcwd(), CACHE_PATH))\n<mask token>\nopen(OUTPUT_FILE, 'w+')\nfor NIndex, Note in enumerate(UstParts):\n print('prevnote', PreviousNote)\n Rest = False\n if Note.lyric in OtoObject.keys():\n LocalOto = OtoObject[Note.lyric]\n else:\n LocalOto = None\n Rest = True\n Lyric = Note.lyric\n Length = Note.length\n NoteNum = Note.notenum\n PreUtterance = float(LocalOto['PreUtterance']) if not Rest else 0\n Velocity = Note.velocity\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n PBS = Note.pbs\n except KeyError:\n PBS = None\n try:\n PBW = Note['PBW'].split(',')\n except KeyError:\n PBW = None\n try:\n PBY = Note['PBY'].split(',')\n for Index, Var in enumerate(PBY):\n if Var == '':\n PBY[Index] = '0'\n except KeyError:\n PBY = []\n try:\n PBM = Note.pbm\n except KeyError:\n PBM = []\n try:\n VBR = Note.get_by_key('VBR').split(',')\n except KeyError:\n VBR = None\n try:\n Flags = Note.get_by_key('Flags')\n except KeyError:\n Flags = '?'\n try:\n Modulation = Note.get_by_key('Modulation')\n except KeyError:\n Modulation = 100\n try:\n Intensity = Note.get_by_key('Intensity')\n except KeyError:\n Intensity = 100\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n Envelope = Note.get_by_key('Envelope')\n Envelope = Envelope.replace('%', LocalOto['Overlap']).split(',')\n except (KeyError, TypeError):\n Envelope = ['0', '5', '35', '0', '100', '100', '0']\n FileOrder = f'{NIndex:05}'\n if Rest:\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(MSPassed), str(\n Length)] + ['0'] * 11\n PreviousNote = -1\n MSPassed += float(Length)\n subprocess.call(WavtoolParam)\n else:\n if PreviousNote == -1:\n PrevNote = NoteNum\n else:\n PrevNote = int(PreviousNote)\n if PBS is not None and PBW is not None:\n PB = MainFactory()\n PB.AddPitchBends(MSPassed, MSPassed + float(Length), PBS, PBW,\n PrevNoteNum=PrevNote, CurrentNoteNum=NoteNum, PBY=PBY, PBM=\n PBM, VBR=VBR)\n PitchBendData = PB.RenderPitchBends(int(math.ceil((MSPassed +\n PBS[0]) / 5)), int(math.floor((MSPassed + float(Length)) / \n 5)), NoteNum)\n else:\n PitchBendData = None\n if PreUtterance - float(LocalOto['Overlap']) > PreviousLength // 2:\n CorrectionRate = PreviousLength // 2 / (PreUtterance - float(\n LocalOto['Overlap']))\n BitedPreUtterance = PreUtterance * CorrectionRate\n BitedOverlap = float(LocalOto['Overlap']) * CorrectionRate\n else:\n BitedPreUtterance = PreUtterance\n BitedOverlap = float(LocalOto['Overlap'])\n BitedSTP = PreUtterance - BitedPreUtterance\n LengthRequire = Length + float(StartPoint\n ) - BitedSTP + BitedOverlap + 50\n if LengthRequire < float(LocalOto['Consonant']):\n LengthRequire = float(LocalOto['Consonant'])\n LengthRequire = (LengthRequire // 50 * 50 if LengthRequire / 50 - \n LengthRequire // 50 < 0.5 else math.ceil(LengthRequire / 50) * 50)\n InputFile = os.path.join(os.getcwd(), VB_PATH, LocalOto['File'])\n OutputFile = os.path.join(os.getcwd(), CACHE_PATH,\n f'{FileOrder}_{Lyric}_{RandomString(6)}.wav')\n Parameters = [os.path.join(os.getcwd(), RESAMPLER_PATH), InputFile,\n OutputFile, midi2str(NoteNum), str(Velocity), Flags, LocalOto[\n 'Offset'], str(int(LengthRequire)), LocalOto['Consonant'],\n LocalOto['Cutoff'], Intensity, Modulation, f'!{Tempo}' if \n PitchBendData is not None else '', f'{PitchBendData}' if \n PitchBendData is not None else '']\n print(Parameters)\n PreviousNote = NoteNum\n PreviousLength = float(Length)\n MSPassed += float(Length)\n subprocess.call(Parameters)\n if NIndex + 1 < len(UstParts) and UstParts[NIndex + 1\n ].lyric in OtoObject.keys():\n NextOto = OtoObject[UstParts[NIndex + 1].lyric]\n NextPreUtterance = float(NextOto['PreUtterance'])\n NextOverlap = float(NextOto['Overlap'])\n WavtoolCorrection = PreUtterance - NextPreUtterance + NextOverlap\n else:\n WavtoolCorrection = PreUtterance\n sign = '+' if WavtoolCorrection >= 0 else ''\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(float(\n StartPoint)), f'{Length}@{float(Tempo)}{sign}{WavtoolCorrection}'\n ] + [str(i) for i in Envelope]\n subprocess.call(WavtoolParam)\n",
"step-3": "<mask token>\n\n\ndef RandomString(Length):\n Letters = string.ascii_lowercase\n return ''.join(random.choice(Letters) for i in range(Length))\n\n\nUST_FILE = 'filet.ust'\nOTO_FILE = 'Voice\\\\NanaMio\\\\oto.ini'\nVB_PATH = 'Voice\\\\NanaMio'\nRESAMPLER_PATH = 'Resampler\\\\macres.exe'\nWAVTOOL_PATH = 'Resampler\\\\wavtool-yawu.exe'\nCACHE_PATH = 'Cache\\\\'\nOUTPUT_FILE = 'temp.wav'\nUstObject = utaupy.ust.load(UST_FILE)\nOtoObject = Oto(OTO_FILE)\nUstParts = UstObject.notes[4:28]\nshutil.rmtree(os.path.join(os.getcwd(), CACHE_PATH))\nos.mkdir(os.path.join(os.getcwd(), CACHE_PATH))\nPreviousNote = -1\nPreviousLength = 0\nTempo = round(float(UstObject.tempo))\nMSPassed = 0\nopen(OUTPUT_FILE, 'w+')\nfor NIndex, Note in enumerate(UstParts):\n print('prevnote', PreviousNote)\n Rest = False\n if Note.lyric in OtoObject.keys():\n LocalOto = OtoObject[Note.lyric]\n else:\n LocalOto = None\n Rest = True\n Lyric = Note.lyric\n Length = Note.length\n NoteNum = Note.notenum\n PreUtterance = float(LocalOto['PreUtterance']) if not Rest else 0\n Velocity = Note.velocity\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n PBS = Note.pbs\n except KeyError:\n PBS = None\n try:\n PBW = Note['PBW'].split(',')\n except KeyError:\n PBW = None\n try:\n PBY = Note['PBY'].split(',')\n for Index, Var in enumerate(PBY):\n if Var == '':\n PBY[Index] = '0'\n except KeyError:\n PBY = []\n try:\n PBM = Note.pbm\n except KeyError:\n PBM = []\n try:\n VBR = Note.get_by_key('VBR').split(',')\n except KeyError:\n VBR = None\n try:\n Flags = Note.get_by_key('Flags')\n except KeyError:\n Flags = '?'\n try:\n Modulation = Note.get_by_key('Modulation')\n except KeyError:\n Modulation = 100\n try:\n Intensity = Note.get_by_key('Intensity')\n except KeyError:\n Intensity = 100\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n Envelope = Note.get_by_key('Envelope')\n Envelope = Envelope.replace('%', LocalOto['Overlap']).split(',')\n except (KeyError, TypeError):\n Envelope = ['0', '5', '35', '0', '100', '100', '0']\n FileOrder = f'{NIndex:05}'\n if Rest:\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(MSPassed), str(\n Length)] + ['0'] * 11\n PreviousNote = -1\n MSPassed += float(Length)\n subprocess.call(WavtoolParam)\n else:\n if PreviousNote == -1:\n PrevNote = NoteNum\n else:\n PrevNote = int(PreviousNote)\n if PBS is not None and PBW is not None:\n PB = MainFactory()\n PB.AddPitchBends(MSPassed, MSPassed + float(Length), PBS, PBW,\n PrevNoteNum=PrevNote, CurrentNoteNum=NoteNum, PBY=PBY, PBM=\n PBM, VBR=VBR)\n PitchBendData = PB.RenderPitchBends(int(math.ceil((MSPassed +\n PBS[0]) / 5)), int(math.floor((MSPassed + float(Length)) / \n 5)), NoteNum)\n else:\n PitchBendData = None\n if PreUtterance - float(LocalOto['Overlap']) > PreviousLength // 2:\n CorrectionRate = PreviousLength // 2 / (PreUtterance - float(\n LocalOto['Overlap']))\n BitedPreUtterance = PreUtterance * CorrectionRate\n BitedOverlap = float(LocalOto['Overlap']) * CorrectionRate\n else:\n BitedPreUtterance = PreUtterance\n BitedOverlap = float(LocalOto['Overlap'])\n BitedSTP = PreUtterance - BitedPreUtterance\n LengthRequire = Length + float(StartPoint\n ) - BitedSTP + BitedOverlap + 50\n if LengthRequire < float(LocalOto['Consonant']):\n LengthRequire = float(LocalOto['Consonant'])\n LengthRequire = (LengthRequire // 50 * 50 if LengthRequire / 50 - \n LengthRequire // 50 < 0.5 else math.ceil(LengthRequire / 50) * 50)\n InputFile = os.path.join(os.getcwd(), VB_PATH, LocalOto['File'])\n OutputFile = os.path.join(os.getcwd(), CACHE_PATH,\n f'{FileOrder}_{Lyric}_{RandomString(6)}.wav')\n Parameters = [os.path.join(os.getcwd(), RESAMPLER_PATH), InputFile,\n OutputFile, midi2str(NoteNum), str(Velocity), Flags, LocalOto[\n 'Offset'], str(int(LengthRequire)), LocalOto['Consonant'],\n LocalOto['Cutoff'], Intensity, Modulation, f'!{Tempo}' if \n PitchBendData is not None else '', f'{PitchBendData}' if \n PitchBendData is not None else '']\n print(Parameters)\n PreviousNote = NoteNum\n PreviousLength = float(Length)\n MSPassed += float(Length)\n subprocess.call(Parameters)\n if NIndex + 1 < len(UstParts) and UstParts[NIndex + 1\n ].lyric in OtoObject.keys():\n NextOto = OtoObject[UstParts[NIndex + 1].lyric]\n NextPreUtterance = float(NextOto['PreUtterance'])\n NextOverlap = float(NextOto['Overlap'])\n WavtoolCorrection = PreUtterance - NextPreUtterance + NextOverlap\n else:\n WavtoolCorrection = PreUtterance\n sign = '+' if WavtoolCorrection >= 0 else ''\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(float(\n StartPoint)), f'{Length}@{float(Tempo)}{sign}{WavtoolCorrection}'\n ] + [str(i) for i in Envelope]\n subprocess.call(WavtoolParam)\n",
"step-4": "from Modules.Pitch.Factory import MainFactory\nfrom Modules.ToJson import Oto\nfrom audiolazy.lazy_midi import midi2str\nimport utaupy\nimport string\nimport random\nimport math\nimport os, subprocess, shutil\n\n\ndef RandomString(Length):\n Letters = string.ascii_lowercase\n return ''.join(random.choice(Letters) for i in range(Length))\n\n\nUST_FILE = 'filet.ust'\nOTO_FILE = 'Voice\\\\NanaMio\\\\oto.ini'\nVB_PATH = 'Voice\\\\NanaMio'\nRESAMPLER_PATH = 'Resampler\\\\macres.exe'\nWAVTOOL_PATH = 'Resampler\\\\wavtool-yawu.exe'\nCACHE_PATH = 'Cache\\\\'\nOUTPUT_FILE = 'temp.wav'\nUstObject = utaupy.ust.load(UST_FILE)\nOtoObject = Oto(OTO_FILE)\nUstParts = UstObject.notes[4:28]\nshutil.rmtree(os.path.join(os.getcwd(), CACHE_PATH))\nos.mkdir(os.path.join(os.getcwd(), CACHE_PATH))\nPreviousNote = -1\nPreviousLength = 0\nTempo = round(float(UstObject.tempo))\nMSPassed = 0\nopen(OUTPUT_FILE, 'w+')\nfor NIndex, Note in enumerate(UstParts):\n print('prevnote', PreviousNote)\n Rest = False\n if Note.lyric in OtoObject.keys():\n LocalOto = OtoObject[Note.lyric]\n else:\n LocalOto = None\n Rest = True\n Lyric = Note.lyric\n Length = Note.length\n NoteNum = Note.notenum\n PreUtterance = float(LocalOto['PreUtterance']) if not Rest else 0\n Velocity = Note.velocity\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n PBS = Note.pbs\n except KeyError:\n PBS = None\n try:\n PBW = Note['PBW'].split(',')\n except KeyError:\n PBW = None\n try:\n PBY = Note['PBY'].split(',')\n for Index, Var in enumerate(PBY):\n if Var == '':\n PBY[Index] = '0'\n except KeyError:\n PBY = []\n try:\n PBM = Note.pbm\n except KeyError:\n PBM = []\n try:\n VBR = Note.get_by_key('VBR').split(',')\n except KeyError:\n VBR = None\n try:\n Flags = Note.get_by_key('Flags')\n except KeyError:\n Flags = '?'\n try:\n Modulation = Note.get_by_key('Modulation')\n except KeyError:\n Modulation = 100\n try:\n Intensity = Note.get_by_key('Intensity')\n except KeyError:\n Intensity = 100\n try:\n StartPoint = Note.get_by_key('StartPoint')\n except KeyError:\n StartPoint = 0\n try:\n Envelope = Note.get_by_key('Envelope')\n Envelope = Envelope.replace('%', LocalOto['Overlap']).split(',')\n except (KeyError, TypeError):\n Envelope = ['0', '5', '35', '0', '100', '100', '0']\n FileOrder = f'{NIndex:05}'\n if Rest:\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(MSPassed), str(\n Length)] + ['0'] * 11\n PreviousNote = -1\n MSPassed += float(Length)\n subprocess.call(WavtoolParam)\n else:\n if PreviousNote == -1:\n PrevNote = NoteNum\n else:\n PrevNote = int(PreviousNote)\n if PBS is not None and PBW is not None:\n PB = MainFactory()\n PB.AddPitchBends(MSPassed, MSPassed + float(Length), PBS, PBW,\n PrevNoteNum=PrevNote, CurrentNoteNum=NoteNum, PBY=PBY, PBM=\n PBM, VBR=VBR)\n PitchBendData = PB.RenderPitchBends(int(math.ceil((MSPassed +\n PBS[0]) / 5)), int(math.floor((MSPassed + float(Length)) / \n 5)), NoteNum)\n else:\n PitchBendData = None\n if PreUtterance - float(LocalOto['Overlap']) > PreviousLength // 2:\n CorrectionRate = PreviousLength // 2 / (PreUtterance - float(\n LocalOto['Overlap']))\n BitedPreUtterance = PreUtterance * CorrectionRate\n BitedOverlap = float(LocalOto['Overlap']) * CorrectionRate\n else:\n BitedPreUtterance = PreUtterance\n BitedOverlap = float(LocalOto['Overlap'])\n BitedSTP = PreUtterance - BitedPreUtterance\n LengthRequire = Length + float(StartPoint\n ) - BitedSTP + BitedOverlap + 50\n if LengthRequire < float(LocalOto['Consonant']):\n LengthRequire = float(LocalOto['Consonant'])\n LengthRequire = (LengthRequire // 50 * 50 if LengthRequire / 50 - \n LengthRequire // 50 < 0.5 else math.ceil(LengthRequire / 50) * 50)\n InputFile = os.path.join(os.getcwd(), VB_PATH, LocalOto['File'])\n OutputFile = os.path.join(os.getcwd(), CACHE_PATH,\n f'{FileOrder}_{Lyric}_{RandomString(6)}.wav')\n Parameters = [os.path.join(os.getcwd(), RESAMPLER_PATH), InputFile,\n OutputFile, midi2str(NoteNum), str(Velocity), Flags, LocalOto[\n 'Offset'], str(int(LengthRequire)), LocalOto['Consonant'],\n LocalOto['Cutoff'], Intensity, Modulation, f'!{Tempo}' if \n PitchBendData is not None else '', f'{PitchBendData}' if \n PitchBendData is not None else '']\n print(Parameters)\n PreviousNote = NoteNum\n PreviousLength = float(Length)\n MSPassed += float(Length)\n subprocess.call(Parameters)\n if NIndex + 1 < len(UstParts) and UstParts[NIndex + 1\n ].lyric in OtoObject.keys():\n NextOto = OtoObject[UstParts[NIndex + 1].lyric]\n NextPreUtterance = float(NextOto['PreUtterance'])\n NextOverlap = float(NextOto['Overlap'])\n WavtoolCorrection = PreUtterance - NextPreUtterance + NextOverlap\n else:\n WavtoolCorrection = PreUtterance\n sign = '+' if WavtoolCorrection >= 0 else ''\n WavtoolParam = [os.path.join(os.getcwd(), WAVTOOL_PATH), os.path.\n join(os.getcwd(), OUTPUT_FILE), OutputFile, str(float(\n StartPoint)), f'{Length}@{float(Tempo)}{sign}{WavtoolCorrection}'\n ] + [str(i) for i in Envelope]\n subprocess.call(WavtoolParam)\n",
"step-5": "from Modules.Pitch.Factory import MainFactory\r\nfrom Modules.ToJson import Oto \r\nfrom audiolazy.lazy_midi import midi2str\r\nimport utaupy\r\nimport string\r\nimport random\r\nimport math\r\nimport os, subprocess, shutil\r\n\r\ndef RandomString(Length):\r\n\tLetters = string.ascii_lowercase\r\n\treturn ''.join(random.choice(Letters) for i in range(Length))\r\n\r\nUST_FILE = \"filet.ust\"\r\nOTO_FILE = \"Voice\\\\NanaMio\\\\oto.ini\"\r\nVB_PATH = \"Voice\\\\NanaMio\"\r\nRESAMPLER_PATH = \"Resampler\\\\macres.exe\"\r\nWAVTOOL_PATH = \"Resampler\\\\wavtool-yawu.exe\"\r\nCACHE_PATH = \"Cache\\\\\"\r\nOUTPUT_FILE = \"temp.wav\"\r\nUstObject = utaupy.ust.load(UST_FILE)\r\nOtoObject = Oto(OTO_FILE)\r\nUstParts = UstObject.notes[4:28]\r\n\r\nshutil.rmtree(os.path.join(os.getcwd(), CACHE_PATH))\r\nos.mkdir(os.path.join(os.getcwd(), CACHE_PATH))\r\n\r\nPreviousNote = -1\r\nPreviousLength = 0\r\nTempo = round(float(UstObject.tempo))\r\nMSPassed = 0\r\nopen(OUTPUT_FILE, \"w+\")\r\nfor NIndex, Note in enumerate(UstParts):\r\n\tprint(\"prevnote\", PreviousNote)\r\n\tRest = False\r\n\tif Note.lyric in OtoObject.keys():\r\n\t\tLocalOto = OtoObject[Note.lyric]\r\n\telse:\r\n\t\tLocalOto = None\r\n\t\tRest = True\r\n\r\n\tLyric = Note.lyric\r\n\tLength = Note.length\r\n\tNoteNum = Note.notenum\r\n\tPreUtterance = float(LocalOto[\"PreUtterance\"]) if not Rest else 0\r\n\tVelocity = Note.velocity\r\n\r\n\t# try:\r\n\t# \tPreUtterance = Note.get_by_key(\"PreUtterance\")\r\n\t# except KeyError:\r\n\t# \tPreUtterance = 0\r\n\r\n\ttry:\r\n\t\tStartPoint = Note.get_by_key(\"StartPoint\")\r\n\texcept KeyError:\r\n\t\tStartPoint = 0\r\n\r\n\ttry:\r\n\t\tPBS = Note.pbs\r\n\texcept KeyError:\r\n\t\tPBS = None\r\n\t\r\n\ttry:\r\n\t\tPBW = Note[\"PBW\"].split(\",\")\r\n\texcept KeyError:\r\n\t\tPBW = None\r\n\r\n\ttry:\r\n\t\tPBY = Note[\"PBY\"].split(\",\")\r\n\t\tfor Index, Var in enumerate(PBY):\r\n\t\t\tif Var == \"\":\r\n\t\t\t\tPBY[Index] = \"0\"\r\n\texcept KeyError:\r\n\t\tPBY = []\r\n\r\n\ttry:\r\n\t\tPBM = Note.pbm\r\n\texcept KeyError:\r\n\t\tPBM = []\r\n\r\n\ttry:\r\n\t\tVBR = Note.get_by_key(\"VBR\").split(\",\")\r\n\texcept KeyError:\r\n\t\tVBR = None\r\n\r\n\ttry:\r\n\t\tFlags = Note.get_by_key(\"Flags\")\r\n\texcept KeyError:\r\n\t\tFlags = \"?\"\r\n\r\n\ttry:\r\n\t\tModulation = Note.get_by_key(\"Modulation\")\r\n\texcept KeyError:\r\n\t\tModulation = 100\r\n\r\n\ttry:\r\n\t\tIntensity = Note.get_by_key(\"Intensity\")\r\n\texcept KeyError:\r\n\t\tIntensity = 100\r\n\r\n\ttry:\r\n\t\tStartPoint = Note.get_by_key(\"StartPoint\")\r\n\texcept KeyError:\r\n\t\tStartPoint = 0\r\n\r\n\ttry:\r\n\t\tEnvelope = Note.get_by_key(\"Envelope\")\r\n\t\tEnvelope = Envelope.replace(\"%\", LocalOto[\"Overlap\"]).split(\",\")\r\n\texcept (KeyError, TypeError):\r\n\t\tEnvelope = [\"0\",\"5\",\"35\",\"0\",\"100\",\"100\",\"0\"]\r\n\r\n\tFileOrder = f\"{NIndex:05}\"\r\n\tif Rest:\r\n\t\t# Parameters = [os.path.join(os.getcwd(), RESAMPLER_PATH),os.path.join(os.getcwd(), CACHE_PATH, SILENCE_FILE), os.path.join(os.getcwd(),f\"{FileOrder}_Blank_{RandomString(6)}.wav\"),utaupy.ust.notenum_as_abc(NoteNum),\"100\",\"?\",\"0\",str(int(Length//50 *50 if Length/50 - Length//50 < 0.5 else math.ceil(Length/50) * 50)),\"0\",\"0\",\"100\",\"0\"]\r\n\t\t# Segment = AudioSegment.silent(duration=Length)\r\n\t\tWavtoolParam = [\r\n\t\t\tos.path.join(os.getcwd(), WAVTOOL_PATH), \r\n\t\t\tos.path.join(os.getcwd(), OUTPUT_FILE), \r\n\t\t\tOutputFile, \r\n\t\t\tstr(MSPassed), \r\n\t\t\tstr(Length)\r\n\t\t] + ([\"0\"] * 11)\r\n\t\tPreviousNote = -1\r\n\t\tMSPassed += float(Length)\r\n\t\tsubprocess.call(WavtoolParam)\r\n\telse:\r\n\t\tif PreviousNote == -1:\r\n\t\t\tPrevNote = NoteNum\r\n\t\telse:\r\n\t\t\tPrevNote = int(PreviousNote)\r\n\r\n\t\tif PBS is not None and PBW is not None:\r\n\t\t\tPB = MainFactory()\r\n\t\t\tPB.AddPitchBends(MSPassed, MSPassed + float(Length), PBS, PBW, PrevNoteNum=PrevNote, CurrentNoteNum=NoteNum, PBY=PBY, PBM=PBM, VBR=VBR)\r\n\t\t\tPitchBendData = PB.RenderPitchBends(int(math.ceil((MSPassed + PBS[0]) / 5)), int(math.floor((MSPassed + float(Length)) / 5)), NoteNum)\r\n\t\telse:\r\n\t\t\tPitchBendData = None\r\n\r\n\r\n\t\t# Bite Correction (The previous note should last for half the length before overlap)\r\n\t\tif PreUtterance - float(LocalOto[\"Overlap\"]) > (PreviousLength // 2):\r\n\t\t\tCorrectionRate = (PreviousLength // 2) / (PreUtterance - float(LocalOto[\"Overlap\"]))\r\n\t\t\tBitedPreUtterance = PreUtterance * CorrectionRate\r\n\t\t\tBitedOverlap = float(LocalOto[\"Overlap\"]) * CorrectionRate\r\n\t\telse:\r\n\t\t\tBitedPreUtterance = PreUtterance\r\n\t\t\tBitedOverlap = float(LocalOto[\"Overlap\"])\r\n\r\n\t\tBitedSTP = PreUtterance - BitedPreUtterance \r\n\r\n\t\tLengthRequire = Length + float(StartPoint) - BitedSTP + BitedOverlap + 50\r\n\t\tif LengthRequire < float(LocalOto[\"Consonant\"]):\r\n\t\t\tLengthRequire = float(LocalOto[\"Consonant\"])\r\n\r\n\t\tLengthRequire = LengthRequire//50 *50 if LengthRequire/50 - LengthRequire//50 < 0.5 else math.ceil(LengthRequire/50) * 50\r\n\r\n\t\tInputFile = os.path.join(os.getcwd(), VB_PATH, LocalOto[\"File\"])\r\n\t\tOutputFile = os.path.join(os.getcwd(), CACHE_PATH, f\"{FileOrder}_{Lyric}_{RandomString(6)}.wav\")\r\n\r\n\t\tParameters = [\r\n\t\t\tos.path.join(os.getcwd(), RESAMPLER_PATH),\r\n\t\t\tInputFile, \r\n\t\t\tOutputFile,\r\n\t\t\tmidi2str(NoteNum),\r\n\t\t\tstr(Velocity),\r\n\t\t\tFlags,\r\n\t\t\tLocalOto[\"Offset\"],\r\n\t\t\tstr(int(LengthRequire)),\r\n\t\t\tLocalOto[\"Consonant\"],\r\n\t\t\tLocalOto[\"Cutoff\"],\r\n\t\t\tIntensity,\r\n\t\t\tModulation,\r\n\t\t\tf\"!{Tempo}\" if PitchBendData is not None else \"\",\r\n\t\t\tf\"{PitchBendData}\" if PitchBendData is not None else \"\"\r\n\t\t]\r\n\r\n\t\tprint(Parameters)\r\n\r\n\t\tPreviousNote = NoteNum\r\n\t\tPreviousLength = float(Length)\r\n\t\tMSPassed += float(Length)\r\n\t\tsubprocess.call(Parameters)\r\n\r\n\t\tif NIndex + 1 < len(UstParts) and UstParts[NIndex+1].lyric in OtoObject.keys():\r\n\t\t\tNextOto = OtoObject[UstParts[NIndex+1].lyric]\r\n\t\t\tNextPreUtterance = float(NextOto[\"PreUtterance\"])\r\n\t\t\tNextOverlap = float(NextOto[\"Overlap\"])\r\n\r\n\t\t\tWavtoolCorrection = PreUtterance - NextPreUtterance + NextOverlap\r\n\t\telse:\r\n\t\t\tWavtoolCorrection = PreUtterance\r\n\r\n\t\tsign = \"+\" if WavtoolCorrection >= 0 else \"\"\r\n\t\tWavtoolParam = [\r\n\t\t\tos.path.join(os.getcwd(), WAVTOOL_PATH), \r\n\t\t\tos.path.join(os.getcwd(), OUTPUT_FILE), \r\n\t\t\tOutputFile, \r\n\t\t\tstr(float(StartPoint)), \r\n\t\t\tf\"{Length}@{float(Tempo)}{sign}{WavtoolCorrection}\"\r\n\t\t] + [str(i) for i in Envelope] \r\n\r\n\t\tsubprocess.call(WavtoolParam)\r\n\r\n\r\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#
# @lc app=leetcode.cn id=784 lang=python3
#
# [784] 字母大小写全排列
#
# @lc code=start
# 回溯法 --> 通过 64 ms 13.5 MB
class Solution:
def __init__(self):
self.result = []
def letterCasePermutation(self, S: str) -> List[str]:
arr = list(S)
self.backtracing(arr, 0)
return self.result
def backtracing(self, arr, start):
if start == len(arr):
self.result.append(''.join(arr))
return
# 把自身递归
self.backtracing(arr, start+1)
# 若是字母,则切换大小写后递归
if arr[start].isalpha():
arr[start] = arr[start].lower() if arr[start].isupper() else arr[start].upper()
self.backtracing(arr, start+1)
# @lc code=end
|
normal
|
{
"blob_id": "632c690261b31c7ac0e1d90c814e3b9a7a0dcb29",
"index": 7663,
"step-1": "class Solution:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-3": "class Solution:\n\n def __init__(self):\n self.result = []\n <mask token>\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-4": "class Solution:\n\n def __init__(self):\n self.result = []\n\n def letterCasePermutation(self, S: str) ->List[str]:\n arr = list(S)\n self.backtracing(arr, 0)\n return self.result\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-5": "#\n# @lc app=leetcode.cn id=784 lang=python3\n#\n# [784] 字母大小写全排列\n#\n\n# @lc code=start\n# 回溯法 --> 通过 64 ms 13.5 MB\nclass Solution:\n def __init__(self):\n self.result = []\n\n def letterCasePermutation(self, S: str) -> List[str]:\n arr = list(S)\n self.backtracing(arr, 0)\n return self.result\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n # 把自身递归\n self.backtracing(arr, start+1)\n # 若是字母,则切换大小写后递归\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[start].upper()\n self.backtracing(arr, start+1)\n \n# @lc code=end\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# coding=utf-8
from smallinvoice.commons import BaseJsonEncodableObject, BaseService
class Catalog(BaseJsonEncodableObject):
def __init__(self, catalog_type, unit, name, cost_per_unit, vat=0):
self.type = catalog_type
self.unit = unit
self.name = name
self.cost_per_unit = cost_per_unit
self.vat = vat
class CatalogService(BaseService):
name = 'catalog'
|
normal
|
{
"blob_id": "37feeba8ff682e5998fde4bcba8c37043cb593f2",
"index": 5195,
"step-1": "<mask token>\n\n\nclass CatalogService(BaseService):\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CatalogService(BaseService):\n name = 'catalog'\n",
"step-3": "<mask token>\n\n\nclass Catalog(BaseJsonEncodableObject):\n <mask token>\n\n\nclass CatalogService(BaseService):\n name = 'catalog'\n",
"step-4": "from smallinvoice.commons import BaseJsonEncodableObject, BaseService\n\n\nclass Catalog(BaseJsonEncodableObject):\n\n def __init__(self, catalog_type, unit, name, cost_per_unit, vat=0):\n self.type = catalog_type\n self.unit = unit\n self.name = name\n self.cost_per_unit = cost_per_unit\n self.vat = vat\n\n\nclass CatalogService(BaseService):\n name = 'catalog'\n",
"step-5": "# coding=utf-8\nfrom smallinvoice.commons import BaseJsonEncodableObject, BaseService\n\n\nclass Catalog(BaseJsonEncodableObject):\n def __init__(self, catalog_type, unit, name, cost_per_unit, vat=0):\n self.type = catalog_type\n self.unit = unit\n self.name = name\n self.cost_per_unit = cost_per_unit\n self.vat = vat\n\n\nclass CatalogService(BaseService):\n name = 'catalog'\n\n",
"step-ids": [
1,
2,
3,
5,
6
]
}
|
[
1,
2,
3,
5,
6
] |
#ABC114 A - クイズ
print("ABC" if input()=="1" else "chokudai")
|
normal
|
{
"blob_id": "14d31a4b7491a7f7a64cd151e79c23546e4a3cd2",
"index": 7683,
"step-1": "<mask token>\n",
"step-2": "print('ABC' if input() == '1' else 'chokudai')\n",
"step-3": "#ABC114 A - クイズ\nprint(\"ABC\" if input()==\"1\" else \"chokudai\")\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
# 1
def transform_data(fn):
print(fn(10))
# 2
transform_data(lambda data: data / 5)
# 3
def transform_data2(fn, *args):
for arg in args:
print(fn(arg))
transform_data2(lambda data: data / 5, 10, 15, 22, 30)
# 4
def transform_data2(fn, *args):
for arg in args:
print('Result: {:^20.2f}'.format(fn(arg)))
transform_data2(lambda data: data / 5, 10, 15, 22, 30)
|
normal
|
{
"blob_id": "c87e6f8780bf8d9097f200c7f2f0faf55beb480c",
"index": 52,
"step-1": "<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n",
"step-2": "def transform_data(fn):\n print(fn(10))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n",
"step-3": "def transform_data(fn):\n print(fn(10))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print('Result: {:^20.2f}'.format(fn(arg)))\n\n\n<mask token>\n",
"step-4": "def transform_data(fn):\n print(fn(10))\n\n\ntransform_data(lambda data: data / 5)\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print('Result: {:^20.2f}'.format(fn(arg)))\n\n\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\n",
"step-5": "# 1\r\ndef transform_data(fn):\r\n print(fn(10))\r\n\r\n# 2\r\ntransform_data(lambda data: data / 5)\r\n\r\n# 3\r\ndef transform_data2(fn, *args):\r\n for arg in args:\r\n print(fn(arg))\r\n\r\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\r\n\r\n# 4\r\ndef transform_data2(fn, *args):\r\n for arg in args:\r\n print('Result: {:^20.2f}'.format(fn(arg)))\r\n\r\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#Importacion de Dependencias Flask
from flask import Blueprint,Flask, render_template, request,redirect,url_for,flash
#modelado de basedato.
from App import db
# Importacion de modulo de ModeloCliente
from App.Modulos.Proveedor.model import Proveedor
#Inportacion de modulo de formularioCliente
from App.Modulos.Proveedor import form
_Proveedor=Blueprint('Proveedor',__name__,url_prefix='/Proveedor')
@_Proveedor.route('/Proveedor', methods=['GET', 'POST']) # registro de proveedor
def proveedor():
frm = form.Fr_Proveedor(request.form)
if request.method == 'POST':
pr = Proveedor.query.filter_by(CI=frm.CI.data).first()
if frm.validate() and pr is None:
new_user = Proveedor(razonSolcial=frm.RasonSocial.data,
CI=frm.CI.data,
Direccion=frm.Direccion.data,
Correo=frm.Correo.data,
convencional=frm.Convencional.data,
Celular=frm.Celular.data
)
db.session.add(new_user)
db.session.commit()
flash("Se registrado con exito sus datos")
return redirect(url_for('Proveedor.proveedor'))
else:
flash("Error: No se registrado con exito sus Datos")
return render_template('Proveedor/frproveedor.html', frm=frm)
@_Proveedor.route('/listaP') # listado de Proveedores.
def listaP():
titulo = "Lista Proveedor"
return render_template("Proveedor/listaP.html", titulo=titulo, listas=Proveedor.query.all())
@_Proveedor.route('/UpdateP', methods=[ 'POST'])
def UpdateP():
print(request.form)
updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()
print("ci:",updateP.CI)
updateP.razonSolcial = request.form['RasonSocial']
updateP.Direccion = request.form['Direccion']
updateP.Correo = request.form['Correo']
updateP.convencional= request.form['Convencional']
updateP.Celular = request.form['Celular']
db.session.commit()
return redirect(url_for('Proveedor.listaP'))
@_Proveedor.route('/deleteP/<string:id>',methods=['GET','POST'])
def deleteP(id=None):
dlTP = Proveedor.query.filter_by(CI=id).first()
db.session.delete(dlTP)
db.session.commit()
return redirect(url_for('Proveedor.listaP'))
@_Proveedor.route("/modalP")
def modalP():
frm = form.Fr_Proveedor(request.form)
return render_template("modal/modaproveedor.html", frm=frm, title="Proveedor")
|
normal
|
{
"blob_id": "99ecb927e22bc303dd9dffd2793887e7398dbb83",
"index": 3649,
"step-1": "<mask token>\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n<mask token>\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n<mask token>\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-2": "<mask token>\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-3": "<mask token>\n_Proveedor = Blueprint('Proveedor', __name__, url_prefix='/Proveedor')\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-4": "from flask import Blueprint, Flask, render_template, request, redirect, url_for, flash\nfrom App import db\nfrom App.Modulos.Proveedor.model import Proveedor\nfrom App.Modulos.Proveedor import form\n_Proveedor = Blueprint('Proveedor', __name__, url_prefix='/Proveedor')\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-5": "#Importacion de Dependencias Flask\nfrom flask import Blueprint,Flask, render_template, request,redirect,url_for,flash\n#modelado de basedato.\nfrom App import db\n# Importacion de modulo de ModeloCliente\nfrom App.Modulos.Proveedor.model import Proveedor\n#Inportacion de modulo de formularioCliente\nfrom App.Modulos.Proveedor import form\n\n_Proveedor=Blueprint('Proveedor',__name__,url_prefix='/Proveedor')\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST']) # registro de proveedor\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data,\n CI=frm.CI.data,\n Direccion=frm.Direccion.data,\n Correo=frm.Correo.data,\n convencional=frm.Convencional.data,\n Celular=frm.Celular.data\n )\n db.session.add(new_user)\n db.session.commit()\n flash(\"Se registrado con exito sus datos\")\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash(\"Error: No se registrado con exito sus Datos\")\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n@_Proveedor.route('/listaP') # listado de Proveedores.\ndef listaP():\n titulo = \"Lista Proveedor\"\n return render_template(\"Proveedor/listaP.html\", titulo=titulo, listas=Proveedor.query.all())\n\n@_Proveedor.route('/UpdateP', methods=[ 'POST'])\ndef UpdateP():\n print(request.form)\n\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print(\"ci:\",updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional= request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>',methods=['GET','POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP) \n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n@_Proveedor.route(\"/modalP\")\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template(\"modal/modaproveedor.html\", frm=frm, title=\"Proveedor\")\n\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
from cpp_service.SubService import SubService
import config
if __name__ == "__main__":
gateway = config.gateway["trading_system_gateway"]
host = gateway["host"]
port = gateway["port"]
server_id = gateway["server_id"]
licences = gateway["licences"]
service = SubService(host, port, server_id, licences)
"""订阅order"""
service.sub_order()
|
normal
|
{
"blob_id": "f72cdf8d91c31760335b96052a34615307f48727",
"index": 9774,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n gateway = config.gateway['trading_system_gateway']\n host = gateway['host']\n port = gateway['port']\n server_id = gateway['server_id']\n licences = gateway['licences']\n service = SubService(host, port, server_id, licences)\n \"\"\"订阅order\"\"\"\n service.sub_order()\n",
"step-3": "from cpp_service.SubService import SubService\nimport config\nif __name__ == '__main__':\n gateway = config.gateway['trading_system_gateway']\n host = gateway['host']\n port = gateway['port']\n server_id = gateway['server_id']\n licences = gateway['licences']\n service = SubService(host, port, server_id, licences)\n \"\"\"订阅order\"\"\"\n service.sub_order()\n",
"step-4": "from cpp_service.SubService import SubService\nimport config\n\nif __name__ == \"__main__\":\n gateway = config.gateway[\"trading_system_gateway\"]\n host = gateway[\"host\"]\n port = gateway[\"port\"]\n server_id = gateway[\"server_id\"]\n licences = gateway[\"licences\"]\n\n service = SubService(host, port, server_id, licences)\n \"\"\"订阅order\"\"\"\n service.sub_order()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=None
)
ser.close()
ser.open()
if ser.isOpen():
print "Serial is open"
ser.flushInput()
ser.flushOutput()
while True:
mimic = ''
bytesToRead = ser.inWaiting()
mimic = ser.read( bytesToRead )
if mimic != '':
print mimic
time.sleep(0.5)
# ser.write( "Got it" )
|
normal
|
{
"blob_id": "b112ca3dc603035f340444fa74a7941b1b95f5e5",
"index": 6877,
"step-1": "import time\nimport serial\n\nser = serial.Serial(\n\tport='/dev/ttyUSB0',\n\tbaudrate=9600,\n\tparity=serial.PARITY_NONE,\n\tstopbits=serial.STOPBITS_ONE,\n\tbytesize=serial.EIGHTBITS,\n\ttimeout=None\n)\nser.close()\nser.open()\nif ser.isOpen():\n\tprint \"Serial is open\"\n\tser.flushInput()\n\tser.flushOutput()\n\n\nwhile True:\n\tmimic = ''\n\tbytesToRead = ser.inWaiting()\n\tmimic = ser.read( bytesToRead )\n\tif mimic != '':\n\t\tprint mimic\n\n\t\ttime.sleep(0.5)\n#\t\tser.write( \"Got it\" )\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from datetime import timedelta
import pandas as pd
__all__ = ["FixWindowCutoffStrategy"]
class CutoffStrategy:
"""
Class that holds a CutoffStrategy. This is a measure to prevent leakage
Parameters
----------
generate_fn: a function that generates a cutoff time for a given entity.
input: entity rows
output: a training cutoff in np.datetime64 format
Returns
-------
CutoffStrategy Instance
"""
def __init__(self, generate_fn, description='undescribed cutoff strategy'):
self.generate_fn = generate_fn
self.description = description
class FixWindowCutoffStrategy(CutoffStrategy):
def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):
self.description = "in next {} days".format(cutoff_window)
self.cutoff_base = cutoff_base
self.cutoff_end = cutoff_end
self.cutoff_window = cutoff_window
self.entity_col = entity_col
def generate_cutoffs(self, df):
cutoff_st_ed_pairs = []
current = self.cutoff_base
while True:
current_end = current + timedelta(days=self.cutoff_window)
if current_end > self.cutoff_end:
break
cutoff_st_ed_pairs.append((current, current_end))
current = current_end
entity_cutoffs = []
for entity_name in set(df[self.entity_col]):
for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:
entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))
return pd.DataFrame(entity_cutoffs, columns=[self.entity_col, "cutoff_st", "cutoff_ed"])
|
normal
|
{
"blob_id": "30f030d48368e1b103f926ee7a15b4b75c4459c7",
"index": 7030,
"step-1": "<mask token>\n\n\nclass CutoffStrategy:\n <mask token>\n\n def __init__(self, generate_fn, description='undescribed cutoff strategy'):\n self.generate_fn = generate_fn\n self.description = description\n\n\nclass FixWindowCutoffStrategy(CutoffStrategy):\n\n def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):\n self.description = 'in next {} days'.format(cutoff_window)\n self.cutoff_base = cutoff_base\n self.cutoff_end = cutoff_end\n self.cutoff_window = cutoff_window\n self.entity_col = entity_col\n\n def generate_cutoffs(self, df):\n cutoff_st_ed_pairs = []\n current = self.cutoff_base\n while True:\n current_end = current + timedelta(days=self.cutoff_window)\n if current_end > self.cutoff_end:\n break\n cutoff_st_ed_pairs.append((current, current_end))\n current = current_end\n entity_cutoffs = []\n for entity_name in set(df[self.entity_col]):\n for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:\n entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))\n return pd.DataFrame(entity_cutoffs, columns=[self.entity_col,\n 'cutoff_st', 'cutoff_ed'])\n",
"step-2": "<mask token>\n\n\nclass CutoffStrategy:\n \"\"\"\n Class that holds a CutoffStrategy. This is a measure to prevent leakage\n\n Parameters\n ----------\n generate_fn: a function that generates a cutoff time for a given entity.\n input: entity rows\n output: a training cutoff in np.datetime64 format\n\n Returns\n -------\n CutoffStrategy Instance\n \"\"\"\n\n def __init__(self, generate_fn, description='undescribed cutoff strategy'):\n self.generate_fn = generate_fn\n self.description = description\n\n\nclass FixWindowCutoffStrategy(CutoffStrategy):\n\n def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):\n self.description = 'in next {} days'.format(cutoff_window)\n self.cutoff_base = cutoff_base\n self.cutoff_end = cutoff_end\n self.cutoff_window = cutoff_window\n self.entity_col = entity_col\n\n def generate_cutoffs(self, df):\n cutoff_st_ed_pairs = []\n current = self.cutoff_base\n while True:\n current_end = current + timedelta(days=self.cutoff_window)\n if current_end > self.cutoff_end:\n break\n cutoff_st_ed_pairs.append((current, current_end))\n current = current_end\n entity_cutoffs = []\n for entity_name in set(df[self.entity_col]):\n for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:\n entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))\n return pd.DataFrame(entity_cutoffs, columns=[self.entity_col,\n 'cutoff_st', 'cutoff_ed'])\n",
"step-3": "<mask token>\n__all__ = ['FixWindowCutoffStrategy']\n\n\nclass CutoffStrategy:\n \"\"\"\n Class that holds a CutoffStrategy. This is a measure to prevent leakage\n\n Parameters\n ----------\n generate_fn: a function that generates a cutoff time for a given entity.\n input: entity rows\n output: a training cutoff in np.datetime64 format\n\n Returns\n -------\n CutoffStrategy Instance\n \"\"\"\n\n def __init__(self, generate_fn, description='undescribed cutoff strategy'):\n self.generate_fn = generate_fn\n self.description = description\n\n\nclass FixWindowCutoffStrategy(CutoffStrategy):\n\n def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):\n self.description = 'in next {} days'.format(cutoff_window)\n self.cutoff_base = cutoff_base\n self.cutoff_end = cutoff_end\n self.cutoff_window = cutoff_window\n self.entity_col = entity_col\n\n def generate_cutoffs(self, df):\n cutoff_st_ed_pairs = []\n current = self.cutoff_base\n while True:\n current_end = current + timedelta(days=self.cutoff_window)\n if current_end > self.cutoff_end:\n break\n cutoff_st_ed_pairs.append((current, current_end))\n current = current_end\n entity_cutoffs = []\n for entity_name in set(df[self.entity_col]):\n for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:\n entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))\n return pd.DataFrame(entity_cutoffs, columns=[self.entity_col,\n 'cutoff_st', 'cutoff_ed'])\n",
"step-4": "from datetime import timedelta\nimport pandas as pd\n__all__ = ['FixWindowCutoffStrategy']\n\n\nclass CutoffStrategy:\n \"\"\"\n Class that holds a CutoffStrategy. This is a measure to prevent leakage\n\n Parameters\n ----------\n generate_fn: a function that generates a cutoff time for a given entity.\n input: entity rows\n output: a training cutoff in np.datetime64 format\n\n Returns\n -------\n CutoffStrategy Instance\n \"\"\"\n\n def __init__(self, generate_fn, description='undescribed cutoff strategy'):\n self.generate_fn = generate_fn\n self.description = description\n\n\nclass FixWindowCutoffStrategy(CutoffStrategy):\n\n def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):\n self.description = 'in next {} days'.format(cutoff_window)\n self.cutoff_base = cutoff_base\n self.cutoff_end = cutoff_end\n self.cutoff_window = cutoff_window\n self.entity_col = entity_col\n\n def generate_cutoffs(self, df):\n cutoff_st_ed_pairs = []\n current = self.cutoff_base\n while True:\n current_end = current + timedelta(days=self.cutoff_window)\n if current_end > self.cutoff_end:\n break\n cutoff_st_ed_pairs.append((current, current_end))\n current = current_end\n entity_cutoffs = []\n for entity_name in set(df[self.entity_col]):\n for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:\n entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))\n return pd.DataFrame(entity_cutoffs, columns=[self.entity_col,\n 'cutoff_st', 'cutoff_ed'])\n",
"step-5": "from datetime import timedelta\n\nimport pandas as pd\n\n__all__ = [\"FixWindowCutoffStrategy\"]\n\n\nclass CutoffStrategy:\n \"\"\"\n Class that holds a CutoffStrategy. This is a measure to prevent leakage\n\n Parameters\n ----------\n generate_fn: a function that generates a cutoff time for a given entity.\n input: entity rows\n output: a training cutoff in np.datetime64 format\n\n Returns\n -------\n CutoffStrategy Instance\n \"\"\"\n\n def __init__(self, generate_fn, description='undescribed cutoff strategy'):\n self.generate_fn = generate_fn\n self.description = description\n\n\nclass FixWindowCutoffStrategy(CutoffStrategy):\n def __init__(self, entity_col, cutoff_base, cutoff_end, cutoff_window):\n self.description = \"in next {} days\".format(cutoff_window)\n self.cutoff_base = cutoff_base\n self.cutoff_end = cutoff_end\n self.cutoff_window = cutoff_window\n self.entity_col = entity_col\n\n def generate_cutoffs(self, df):\n cutoff_st_ed_pairs = []\n\n current = self.cutoff_base\n while True:\n current_end = current + timedelta(days=self.cutoff_window)\n if current_end > self.cutoff_end:\n break\n cutoff_st_ed_pairs.append((current, current_end))\n current = current_end\n\n entity_cutoffs = []\n for entity_name in set(df[self.entity_col]):\n for cutoff_st, cutoff_ed in cutoff_st_ed_pairs:\n entity_cutoffs.append((entity_name, cutoff_st, cutoff_ed))\n\n return pd.DataFrame(entity_cutoffs, columns=[self.entity_col, \"cutoff_st\", \"cutoff_ed\"])\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
import os
import datetime
from classifier import Classification
class PersistableClassificationModel(Classification):
"""
Classification classifier with ability to persist trained classifier on the disk.
"""
def __init__(self, output_dir, origin):
self.originModel = origin
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
self.path_to_persist = os.path.join(
output_dir,
'model-{0}.mdl'.format(datetime.datetime.now()).replace(":", "-"))
@property
def model(self):
return self.originModel.model
def persist(self):
"""
Persists original classifier to the file.
"""
self.originModel.model.save(self.path_to_persist)
return self
def build(self):
"""
Simply calls original classifier to build classifier.
"""
self.originModel.build()
return self
def train(self, training_set):
"""
Simply calls original classifier to train classifier.
"""
self.originModel.train(training_set)
return self
|
normal
|
{
"blob_id": "a4697f0a0d0cc264b28a58bcc28528c221b4cb49",
"index": 3807,
"step-1": "<mask token>\n\n\nclass PersistableClassificationModel(Classification):\n <mask token>\n\n def __init__(self, output_dir, origin):\n self.originModel = origin\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n self.path_to_persist = os.path.join(output_dir, 'model-{0}.mdl'.\n format(datetime.datetime.now()).replace(':', '-'))\n <mask token>\n <mask token>\n\n def build(self):\n \"\"\"\n Simply calls original classifier to build classifier.\n \"\"\"\n self.originModel.build()\n return self\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass PersistableClassificationModel(Classification):\n <mask token>\n\n def __init__(self, output_dir, origin):\n self.originModel = origin\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n self.path_to_persist = os.path.join(output_dir, 'model-{0}.mdl'.\n format(datetime.datetime.now()).replace(':', '-'))\n\n @property\n def model(self):\n return self.originModel.model\n\n def persist(self):\n \"\"\"\n Persists original classifier to the file.\n \"\"\"\n self.originModel.model.save(self.path_to_persist)\n return self\n\n def build(self):\n \"\"\"\n Simply calls original classifier to build classifier.\n \"\"\"\n self.originModel.build()\n return self\n\n def train(self, training_set):\n \"\"\"\n Simply calls original classifier to train classifier.\n \"\"\"\n self.originModel.train(training_set)\n return self\n",
"step-3": "<mask token>\n\n\nclass PersistableClassificationModel(Classification):\n \"\"\"\n Classification classifier with ability to persist trained classifier on the disk.\n \"\"\"\n\n def __init__(self, output_dir, origin):\n self.originModel = origin\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n self.path_to_persist = os.path.join(output_dir, 'model-{0}.mdl'.\n format(datetime.datetime.now()).replace(':', '-'))\n\n @property\n def model(self):\n return self.originModel.model\n\n def persist(self):\n \"\"\"\n Persists original classifier to the file.\n \"\"\"\n self.originModel.model.save(self.path_to_persist)\n return self\n\n def build(self):\n \"\"\"\n Simply calls original classifier to build classifier.\n \"\"\"\n self.originModel.build()\n return self\n\n def train(self, training_set):\n \"\"\"\n Simply calls original classifier to train classifier.\n \"\"\"\n self.originModel.train(training_set)\n return self\n",
"step-4": "import os\nimport datetime\nfrom classifier import Classification\n\n\nclass PersistableClassificationModel(Classification):\n \"\"\"\n Classification classifier with ability to persist trained classifier on the disk.\n \"\"\"\n\n def __init__(self, output_dir, origin):\n self.originModel = origin\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n self.path_to_persist = os.path.join(output_dir, 'model-{0}.mdl'.\n format(datetime.datetime.now()).replace(':', '-'))\n\n @property\n def model(self):\n return self.originModel.model\n\n def persist(self):\n \"\"\"\n Persists original classifier to the file.\n \"\"\"\n self.originModel.model.save(self.path_to_persist)\n return self\n\n def build(self):\n \"\"\"\n Simply calls original classifier to build classifier.\n \"\"\"\n self.originModel.build()\n return self\n\n def train(self, training_set):\n \"\"\"\n Simply calls original classifier to train classifier.\n \"\"\"\n self.originModel.train(training_set)\n return self\n",
"step-5": "import os\nimport datetime\n\nfrom classifier import Classification\n\n\nclass PersistableClassificationModel(Classification):\n\n \"\"\"\n Classification classifier with ability to persist trained classifier on the disk.\n \"\"\"\n def __init__(self, output_dir, origin):\n self.originModel = origin\n\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n\n self.path_to_persist = os.path.join(\n output_dir,\n 'model-{0}.mdl'.format(datetime.datetime.now()).replace(\":\", \"-\"))\n\n @property\n def model(self):\n return self.originModel.model\n\n def persist(self):\n \"\"\"\n Persists original classifier to the file.\n \"\"\"\n self.originModel.model.save(self.path_to_persist)\n return self\n\n def build(self):\n \"\"\"\n Simply calls original classifier to build classifier.\n \"\"\"\n self.originModel.build()\n return self\n\n def train(self, training_set):\n \"\"\"\n Simply calls original classifier to train classifier.\n \"\"\"\n self.originModel.train(training_set)\n return self\n",
"step-ids": [
3,
6,
7,
8,
9
]
}
|
[
3,
6,
7,
8,
9
] |
# Print list of files and directories
import os
def file_list(dir):
subdir_list = []
for item in os.listdir(dir):
fullpath = os.path.join(dir,item)
if os.path.isdir(fullpath):
subdir_list.append(fullpath)
else:
print(fullpath)
for d in subdir_list:
file_list(d)
file_list('D:\Workspace\test\PythonProject')
|
normal
|
{
"blob_id": "051544f41cc3c7d78210076cb9720866924ea2a1",
"index": 2942,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef file_list(dir):\n subdir_list = []\n for item in os.listdir(dir):\n fullpath = os.path.join(dir, item)\n if os.path.isdir(fullpath):\n subdir_list.append(fullpath)\n else:\n print(fullpath)\n for d in subdir_list:\n file_list(d)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef file_list(dir):\n subdir_list = []\n for item in os.listdir(dir):\n fullpath = os.path.join(dir, item)\n if os.path.isdir(fullpath):\n subdir_list.append(fullpath)\n else:\n print(fullpath)\n for d in subdir_list:\n file_list(d)\n\n\nfile_list('D:\\\\Workspace\\test\\\\PythonProject')\n",
"step-4": "import os\n\n\ndef file_list(dir):\n subdir_list = []\n for item in os.listdir(dir):\n fullpath = os.path.join(dir, item)\n if os.path.isdir(fullpath):\n subdir_list.append(fullpath)\n else:\n print(fullpath)\n for d in subdir_list:\n file_list(d)\n\n\nfile_list('D:\\\\Workspace\\test\\\\PythonProject')\n",
"step-5": "# Print list of files and directories\nimport os\n\ndef file_list(dir):\n subdir_list = []\n for item in os.listdir(dir):\n fullpath = os.path.join(dir,item)\n if os.path.isdir(fullpath):\n subdir_list.append(fullpath)\n else:\n print(fullpath)\n\n for d in subdir_list:\n file_list(d)\n\nfile_list('D:\\Workspace\\test\\PythonProject')\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
class Rectangulo():
def __init__(self, base, altura):
self.base = base
self.altura = altura
def calcular_area(self):
return self.base * self.altura
base = float(input("Ingrese la base del rectangulo: \n"))
altura = float(input("Ingrese la altura del rectangulo: \n"))
#Primera instancia de rectangulo
rectangulo_1 = Rectangulo(base, altura)
area_rectangulo = rectangulo_1.calcular_area()
print(f"El area del rectangulo de {base} * {altura} = {area_rectangulo}")
|
normal
|
{
"blob_id": "2e60781da004fb86d3a33deae970c1faf2a5037d",
"index": 5793,
"step-1": "class Rectangulo:\n <mask token>\n\n def calcular_area(self):\n return self.base * self.altura\n\n\n<mask token>\n",
"step-2": "class Rectangulo:\n\n def __init__(self, base, altura):\n self.base = base\n self.altura = altura\n\n def calcular_area(self):\n return self.base * self.altura\n\n\n<mask token>\n",
"step-3": "class Rectangulo:\n\n def __init__(self, base, altura):\n self.base = base\n self.altura = altura\n\n def calcular_area(self):\n return self.base * self.altura\n\n\n<mask token>\nprint(f'El area del rectangulo de {base} * {altura} = {area_rectangulo}')\n",
"step-4": "class Rectangulo:\n\n def __init__(self, base, altura):\n self.base = base\n self.altura = altura\n\n def calcular_area(self):\n return self.base * self.altura\n\n\nbase = float(input('Ingrese la base del rectangulo: \\n'))\naltura = float(input('Ingrese la altura del rectangulo: \\n'))\nrectangulo_1 = Rectangulo(base, altura)\narea_rectangulo = rectangulo_1.calcular_area()\nprint(f'El area del rectangulo de {base} * {altura} = {area_rectangulo}')\n",
"step-5": "class Rectangulo():\n\n def __init__(self, base, altura):\n self.base = base\n self.altura = altura\n\n def calcular_area(self):\n return self.base * self.altura\n\nbase = float(input(\"Ingrese la base del rectangulo: \\n\"))\naltura = float(input(\"Ingrese la altura del rectangulo: \\n\"))\n\n#Primera instancia de rectangulo\nrectangulo_1 = Rectangulo(base, altura)\narea_rectangulo = rectangulo_1.calcular_area()\nprint(f\"El area del rectangulo de {base} * {altura} = {area_rectangulo}\")\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
# -*- 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
] |
import datetime
import numpy as np
import tensorflow as tf
from alphai_time_series.performance_trials.performance import Metrics
import alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval
import alphai_cromulon_oracle.cromulon.train as crocubot_train
from alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions
from alphai_cromulon_oracle.cromulon.model import CrocuBotModel
from alphai_feature_generation.classifier import BinDistribution
from alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource
from alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration
import examples.iotools as io
from examples.benchmark.helpers import print_time_info
from examples.helpers import D_TYPE, load_default_topology
def run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):
topology = load_default_topology(series_name, tf_flags)
# First need to establish bin edges using full training set
n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)
bin_distribution = _create_bin_distribution(series_name, n_train_samples, topology)
batch_size = tf_flags.batch_size
save_path = io.build_check_point_filename(series_name, topology, tf_flags)
@printtime(message="Training {} with do_train: {}".format(series_name, int(do_training)))
def _do_training():
execution_time = datetime.datetime.now()
if do_training:
data_provider = TrainDataProviderForDataSource(
series_name,
D_TYPE,
n_train_samples,
batch_size,
True,
bin_distribution.bin_edges
)
train_x = data_provider.get_batch(0)
raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.batch_size)
tensorflow_path = TensorflowPath(save_path, tf_flags.model_save_path)
tensorboard_options = TensorboardOptions(tf_flags.tensorboard_log_path,
tf_flags.learning_rate,
batch_size,
execution_time
)
crocubot_train.train(topology,
data_provider,
tensorflow_path,
tensorboard_options,
tf_flags
)
else:
tf.reset_default_graph()
model = CrocuBotModel(topology)
model.build_layers_variables()
train_time, _ = execute_and_get_duration(_do_training)
print("Training complete.")
eval_time, _ = execute_and_get_duration(evaluate_network, topology, series_name, batch_size,
save_path, bin_distribution, tf_flags)
print('Metrics:')
print_time_info(train_time, eval_time)
def _create_bin_distribution(series_name, n_training_samples, topology):
data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, n_training_samples, True)
train_data = data_provider.get_batch(0)
return BinDistribution(train_data.labels, topology.n_classification_bins)
@printtime(message="Evaluation of Stocastic Series")
def evaluate_network(topology, series_name, batch_size, save_path, bin_dist, tf_flags):
n_training_samples = batch_size * 2
data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, batch_size, False)
test_features, test_labels = data_provider.get_batch(1)
binned_outputs = crocubot_eval.eval_neural_net(test_features, topology, tf_flags, save_path)
estimated_means, estimated_covariance = crocubot_eval.forecast_means_and_variance(
binned_outputs, bin_dist, tf_flags)
test_labels = np.squeeze(test_labels)
model_metrics = Metrics()
model_metrics.evaluate_sample_performance(
data_provider.data_source,
test_labels,
estimated_means,
estimated_covariance
)
|
normal
|
{
"blob_id": "bef16443f77b2c1e09db9950a4617703085d9f71",
"index": 7807,
"step-1": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\n<mask token>\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-3": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-4": "import datetime\nimport numpy as np\nimport tensorflow as tf\nfrom alphai_time_series.performance_trials.performance import Metrics\nimport alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval\nimport alphai_cromulon_oracle.cromulon.train as crocubot_train\nfrom alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions\nfrom alphai_cromulon_oracle.cromulon.model import CrocuBotModel\nfrom alphai_feature_generation.classifier import BinDistribution\nfrom alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource\nfrom alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration\nimport examples.iotools as io\nfrom examples.benchmark.helpers import print_time_info\nfrom examples.helpers import D_TYPE, load_default_topology\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-5": "import datetime\n\nimport numpy as np\nimport tensorflow as tf\nfrom alphai_time_series.performance_trials.performance import Metrics\n\nimport alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval\nimport alphai_cromulon_oracle.cromulon.train as crocubot_train\n\nfrom alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions\nfrom alphai_cromulon_oracle.cromulon.model import CrocuBotModel\nfrom alphai_feature_generation.classifier import BinDistribution\nfrom alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource\nfrom alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration\n\nimport examples.iotools as io\nfrom examples.benchmark.helpers import print_time_info\nfrom examples.helpers import D_TYPE, load_default_topology\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n\n topology = load_default_topology(series_name, tf_flags)\n\n # First need to establish bin edges using full training set\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n\n bin_distribution = _create_bin_distribution(series_name, n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message=\"Training {} with do_train: {}\".format(series_name, int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n\n data_provider = TrainDataProviderForDataSource(\n series_name,\n D_TYPE,\n n_train_samples,\n batch_size,\n True,\n bin_distribution.bin_edges\n )\n\n\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.batch_size)\n\n tensorflow_path = TensorflowPath(save_path, tf_flags.model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.tensorboard_log_path,\n tf_flags.learning_rate,\n batch_size,\n execution_time\n )\n crocubot_train.train(topology,\n data_provider,\n tensorflow_path,\n tensorboard_options,\n tf_flags\n )\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n\n train_time, _ = execute_and_get_duration(_do_training)\n\n print(\"Training complete.\")\n\n eval_time, _ = execute_and_get_duration(evaluate_network, topology, series_name, batch_size,\n save_path, bin_distribution, tf_flags)\n\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message=\"Evaluation of Stocastic Series\")\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist, tf_flags):\n\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, batch_size, False)\n\n test_features, test_labels = data_provider.get_batch(1)\n\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology, tf_flags, save_path)\n\n estimated_means, estimated_covariance = crocubot_eval.forecast_means_and_variance(\n binned_outputs, bin_dist, tf_flags)\n test_labels = np.squeeze(test_labels)\n\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(\n data_provider.data_source,\n test_labels,\n estimated_means,\n estimated_covariance\n )\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
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
] |
from django.test import TestCase
from django.core.files import File
from ResearchManage.forms import ResearchFormMKI
from django.test import Client
from unittest import TestCase, mock
from datetime import date, timedelta
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Create your tests here.
class TestForms(TestCase):
def test_valid_ResearchFormMKI_form(self): #Тест валидной формы первичной подачи заявки
with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':'224',
'description':'Ну мы тут тестим тесты',
'main_researcher':1,
'ver_bio':'Тесты тестов',
'version':'Тестовая',
'cast_researcher_date':date.today()-timedelta(days=2000*5),
'accept_research_version':'Тестовая версия',
'accept_research_date':date.today()-timedelta(days=2000*5),
'protocol_research_version':'Тестовая версия',
'protocol_research_date':date.today()-timedelta(days=2000*5),
'contract_date':date.today()-timedelta(days=2000*5),
'name_another_doc':'Тест',
'another_doc_version':'Тестовая',
'another_doc_date':date.today()-timedelta(days=2000*5)
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+"Test.txt")
print(form.errors)
print("test_valid_ResearchFormMKI_form")
self.assertTrue(form.is_valid())
def test_wrong_data_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с датой доков>сегодня.На момент написания тест кейс провальный!
with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':'224',
'description':'Ну мы тут тестим тесты',
'main_researcher':1,
'ver_bio':'Тесты тестов',
'version':'Тестовая',
'cast_researcher_date':date.today()+timedelta(days=2000*5),
'accept_research_version':'Тестовая версия',
'accept_research_date':date.today()+timedelta(days=2000*5),
'protocol_research_version':'Тестовая версия',
'protocol_research_date':date.today()+timedelta(days=2000*5),
'contract_date':date.today()+timedelta(days=2000*5),
'name_another_doc':'Тест',
'another_doc_version':'Тестовая',
'another_doc_date':date.today()+timedelta(days=2000*5)
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+'Test.txt')
print(form.errors)
print("test_wrong_data_ResearchFormMKI_form")
self.assertFalse(form.is_valid())
def test_wrong_file_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с несуществующим типом файла.На момент написания тест кейс провальный!
#TODO:расширить до каждого отдельного поля
with open(os.path.abspath(os.curdir)+'Test.aboba', 'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.aboba','rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':'224',
'description':'Ну мы тут тестим тесты',
'main_researcher':1,
'ver_bio':'Тесты тестов',
'version':'Тестовая',
'cast_researcher_date':date.today()-timedelta(days=2000*5),
'accept_research_version':'Тестовая версия',
'accept_research_date':date.today()-timedelta(days=2000*5),
'protocol_research_version':'Тестовая версия',
'protocol_research_date':date.today()-timedelta(days=2000*5),
'contract_date':date.today()-timedelta(days=2000*5),
'name_another_doc':'Тест',
'another_doc_version':'Тестовая',
'another_doc_date':date.today()-timedelta(days=2000*5)
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+'Test.aboba')
print(form.errors)
print("test_wrong_file_format_ResearchFormMKI_form")
self.assertFalse(form.is_valid())
def test_empty_main_researcher_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с невыбранным главным исследователем
with open(os.path.abspath(os.curdir)+'Test.txt', 'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':'224',
'description':'Ну мы тут тестим тесты',
'main_researcher':None,
'ver_bio':'Тесты тестов',
'version':'Тестовая',
'cast_researcher_date':date.today()-timedelta(days=2000*5),
'accept_research_version':'Тестовая версия',
'accept_research_date':date.today()-timedelta(days=2000*5),
'protocol_research_version':'Тестовая версия',
'protocol_research_date':date.today()-timedelta(days=2000*5),
'contract_date':date.today()-timedelta(days=2000*5),
'name_another_doc':'Тест',
'another_doc_version':'Тестовая',
'another_doc_date':date.today()-timedelta(days=2000*5)
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+'Test.txt')
print(form.errors)
print("test_empty_main_researcher_format_ResearchFormMKI_form")
self.assertFalse(form.is_valid())
def test_empty_char_fields_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с незаполненными полями для символьного ввода
#TODO:расширить до каждого отдельного поля
with open(os.path.abspath(os.curdir)+'Test.txt', 'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':None,
'description':None,
'main_researcher':1,
'ver_bio':None,
'version':None,
'cast_researcher_date':date.today()-timedelta(days=2000*5),
'accept_research_version':None,
'accept_research_date':date.today()-timedelta(days=2000*5),
'protocol_research_version':None,
'protocol_research_date':date.today()-timedelta(days=2000*5),
'contract_date':date.today()-timedelta(days=2000*5),
'name_another_doc':None,
'another_doc_version':None,
'another_doc_date':date.today()-timedelta(days=2000*5)
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+'Test.txt')
print(form.errors)
print("test_empty_char_fields_format_ResearchFormMKI_form")
self.assertFalse(form.is_valid())
def test_empty_date_fields_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с пустыми значениями полей даты На момент написания тест кейс провальный!
#TODO:расширить до каждого отдельного поля
with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:
f.write(b"ABOBA")
with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:
testfile=f.read()
form=ResearchFormMKI(data={
'protocol_number':'224',
'description':'Ну мы тут тестим тесты',
'main_researcher':1,
'ver_bio':'Тесты тестов',
'version':'Тестовая',
'cast_researcher_date':None,
'accept_research_version':'Тестовая версия',
'accept_research_date':None,
'protocol_research_version':'Тестовая версия',
'protocol_research_date':None,
'contract_date':None,
'name_another_doc':'Тест',
'another_doc_version':'Тестовая',
'another_doc_date':None
},
files={'another_doc': SimpleUploadedFile('another_doc', testfile),
'contract': SimpleUploadedFile('contract', testfile),
'advertising': SimpleUploadedFile('advertising', testfile),
'write_objects': SimpleUploadedFile('write_objects', testfile),
'protocol_research': SimpleUploadedFile('protocol_research', testfile),
'accept_research': SimpleUploadedFile('accept_research', testfile),
'form_inf': SimpleUploadedFile('form_inf', testfile),
'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),
'list_members': SimpleUploadedFile('list_members', testfile),
'document': SimpleUploadedFile('document', testfile)
})
os.remove(os.path.abspath(os.curdir)+'Test.txt')
print(form.errors)
print("test_empty_date_fields_ResearchFormMKI_form")
self.assertTrue(form.is_valid())
|
normal
|
{
"blob_id": "c5d0b23396e084ad6ffade15b3aa3c59b6be3cc0",
"index": 2706,
"step-1": "<mask token>\n\n\nclass TestForms(TestCase):\n <mask token>\n\n def test_wrong_data_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() + timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() + timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() + timedelta(days=\n 2000 * 5), 'contract_date': date.today() + timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() + timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_wrong_data_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_wrong_file_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.aboba')\n print(form.errors)\n print('test_wrong_file_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_main_researcher_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n None, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_main_researcher_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_char_fields_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': None,\n 'description': None, 'main_researcher': 1, 'ver_bio': None,\n 'version': None, 'cast_researcher_date': date.today() -\n timedelta(days=2000 * 5), 'accept_research_version': None,\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': None,\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': None, 'another_doc_version':\n None, 'another_doc_date': date.today() - timedelta(days=\n 2000 * 5)}, files={'another_doc': SimpleUploadedFile(\n 'another_doc', testfile), 'contract': SimpleUploadedFile(\n 'contract', testfile), 'advertising': SimpleUploadedFile(\n 'advertising', testfile), 'write_objects':\n SimpleUploadedFile('write_objects', testfile),\n 'protocol_research': SimpleUploadedFile('protocol_research',\n testfile), 'accept_research': SimpleUploadedFile(\n 'accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_char_fields_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestForms(TestCase):\n <mask token>\n\n def test_wrong_data_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() + timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() + timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() + timedelta(days=\n 2000 * 5), 'contract_date': date.today() + timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() + timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_wrong_data_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_wrong_file_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.aboba')\n print(form.errors)\n print('test_wrong_file_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_main_researcher_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n None, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_main_researcher_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_char_fields_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': None,\n 'description': None, 'main_researcher': 1, 'ver_bio': None,\n 'version': None, 'cast_researcher_date': date.today() -\n timedelta(days=2000 * 5), 'accept_research_version': None,\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': None,\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': None, 'another_doc_version':\n None, 'another_doc_date': date.today() - timedelta(days=\n 2000 * 5)}, files={'another_doc': SimpleUploadedFile(\n 'another_doc', testfile), 'contract': SimpleUploadedFile(\n 'contract', testfile), 'advertising': SimpleUploadedFile(\n 'advertising', testfile), 'write_objects':\n SimpleUploadedFile('write_objects', testfile),\n 'protocol_research': SimpleUploadedFile('protocol_research',\n testfile), 'accept_research': SimpleUploadedFile(\n 'accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_char_fields_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_date_fields_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': None, 'accept_research_version':\n 'Тестовая версия', 'accept_research_date': None,\n 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': None, 'contract_date': None,\n 'name_another_doc': 'Тест', 'another_doc_version':\n 'Тестовая', 'another_doc_date': None}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_date_fields_ResearchFormMKI_form')\n self.assertTrue(form.is_valid())\n",
"step-3": "<mask token>\n\n\nclass TestForms(TestCase):\n\n def test_valid_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_valid_ResearchFormMKI_form')\n self.assertTrue(form.is_valid())\n\n def test_wrong_data_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() + timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() + timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() + timedelta(days=\n 2000 * 5), 'contract_date': date.today() + timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() + timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_wrong_data_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_wrong_file_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.aboba')\n print(form.errors)\n print('test_wrong_file_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_main_researcher_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n None, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_main_researcher_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_char_fields_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': None,\n 'description': None, 'main_researcher': 1, 'ver_bio': None,\n 'version': None, 'cast_researcher_date': date.today() -\n timedelta(days=2000 * 5), 'accept_research_version': None,\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': None,\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': None, 'another_doc_version':\n None, 'another_doc_date': date.today() - timedelta(days=\n 2000 * 5)}, files={'another_doc': SimpleUploadedFile(\n 'another_doc', testfile), 'contract': SimpleUploadedFile(\n 'contract', testfile), 'advertising': SimpleUploadedFile(\n 'advertising', testfile), 'write_objects':\n SimpleUploadedFile('write_objects', testfile),\n 'protocol_research': SimpleUploadedFile('protocol_research',\n testfile), 'accept_research': SimpleUploadedFile(\n 'accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_char_fields_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_date_fields_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': None, 'accept_research_version':\n 'Тестовая версия', 'accept_research_date': None,\n 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': None, 'contract_date': None,\n 'name_another_doc': 'Тест', 'another_doc_version':\n 'Тестовая', 'another_doc_date': None}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_date_fields_ResearchFormMKI_form')\n self.assertTrue(form.is_valid())\n",
"step-4": "from django.test import TestCase\nfrom django.core.files import File\nfrom ResearchManage.forms import ResearchFormMKI\nfrom django.test import Client\nfrom unittest import TestCase, mock\nfrom datetime import date, timedelta\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport os\n\n\nclass TestForms(TestCase):\n\n def test_valid_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_valid_ResearchFormMKI_form')\n self.assertTrue(form.is_valid())\n\n def test_wrong_data_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() + timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() + timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() + timedelta(days=\n 2000 * 5), 'contract_date': date.today() + timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() + timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_wrong_data_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_wrong_file_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.aboba', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.aboba')\n print(form.errors)\n print('test_wrong_file_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_main_researcher_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n None, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': date.today() - timedelta(days=2000 *\n 5), 'accept_research_version': 'Тестовая версия',\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': 'Тест',\n 'another_doc_version': 'Тестовая', 'another_doc_date': date\n .today() - timedelta(days=2000 * 5)}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_main_researcher_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_char_fields_format_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': None,\n 'description': None, 'main_researcher': 1, 'ver_bio': None,\n 'version': None, 'cast_researcher_date': date.today() -\n timedelta(days=2000 * 5), 'accept_research_version': None,\n 'accept_research_date': date.today() - timedelta(days=2000 *\n 5), 'protocol_research_version': None,\n 'protocol_research_date': date.today() - timedelta(days=\n 2000 * 5), 'contract_date': date.today() - timedelta(days=\n 2000 * 5), 'name_another_doc': None, 'another_doc_version':\n None, 'another_doc_date': date.today() - timedelta(days=\n 2000 * 5)}, files={'another_doc': SimpleUploadedFile(\n 'another_doc', testfile), 'contract': SimpleUploadedFile(\n 'contract', testfile), 'advertising': SimpleUploadedFile(\n 'advertising', testfile), 'write_objects':\n SimpleUploadedFile('write_objects', testfile),\n 'protocol_research': SimpleUploadedFile('protocol_research',\n testfile), 'accept_research': SimpleUploadedFile(\n 'accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_char_fields_format_ResearchFormMKI_form')\n self.assertFalse(form.is_valid())\n\n def test_empty_date_fields_ResearchFormMKI_form(self):\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'wb') as f:\n f.write(b'ABOBA')\n with open(os.path.abspath(os.curdir) + 'Test.txt', 'rb') as f:\n testfile = f.read()\n form = ResearchFormMKI(data={'protocol_number': '224',\n 'description': 'Ну мы тут тестим тесты', 'main_researcher':\n 1, 'ver_bio': 'Тесты тестов', 'version': 'Тестовая',\n 'cast_researcher_date': None, 'accept_research_version':\n 'Тестовая версия', 'accept_research_date': None,\n 'protocol_research_version': 'Тестовая версия',\n 'protocol_research_date': None, 'contract_date': None,\n 'name_another_doc': 'Тест', 'another_doc_version':\n 'Тестовая', 'another_doc_date': None}, files={'another_doc':\n SimpleUploadedFile('another_doc', testfile), 'contract':\n SimpleUploadedFile('contract', testfile), 'advertising':\n SimpleUploadedFile('advertising', testfile),\n 'write_objects': SimpleUploadedFile('write_objects',\n testfile), 'protocol_research': SimpleUploadedFile(\n 'protocol_research', testfile), 'accept_research':\n SimpleUploadedFile('accept_research', testfile), 'form_inf':\n SimpleUploadedFile('form_inf', testfile), 'cast_researcher':\n SimpleUploadedFile('cast_researcher', testfile),\n 'list_members': SimpleUploadedFile('list_members', testfile\n ), 'document': SimpleUploadedFile('document', testfile)})\n os.remove(os.path.abspath(os.curdir) + 'Test.txt')\n print(form.errors)\n print('test_empty_date_fields_ResearchFormMKI_form')\n self.assertTrue(form.is_valid())\n",
"step-5": "from django.test import TestCase\nfrom django.core.files import File\nfrom ResearchManage.forms import ResearchFormMKI\nfrom django.test import Client\nfrom unittest import TestCase, mock\nfrom datetime import date, timedelta\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport os\n# Create your tests here.\n\nclass TestForms(TestCase):\n def test_valid_ResearchFormMKI_form(self): #Тест валидной формы первичной подачи заявки\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':'224',\n \t'description':'Ну мы тут тестим тесты',\n \t'main_researcher':1,\n \t'ver_bio':'Тесты тестов',\n \t'version':'Тестовая',\n \t'cast_researcher_date':date.today()-timedelta(days=2000*5),\n \t'accept_research_version':'Тестовая версия',\n \t'accept_research_date':date.today()-timedelta(days=2000*5),\n \t'protocol_research_version':'Тестовая версия',\n \t'protocol_research_date':date.today()-timedelta(days=2000*5),\n \t'contract_date':date.today()-timedelta(days=2000*5),\n \t'name_another_doc':'Тест',\n \t'another_doc_version':'Тестовая',\n \t'another_doc_date':date.today()-timedelta(days=2000*5)\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+\"Test.txt\")\n print(form.errors)\n print(\"test_valid_ResearchFormMKI_form\")\n self.assertTrue(form.is_valid())\n\n def test_wrong_data_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с датой доков>сегодня.На момент написания тест кейс провальный!\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':'224',\n \t'description':'Ну мы тут тестим тесты',\n \t'main_researcher':1,\n \t'ver_bio':'Тесты тестов',\n \t'version':'Тестовая',\n \t'cast_researcher_date':date.today()+timedelta(days=2000*5),\n \t'accept_research_version':'Тестовая версия',\n \t'accept_research_date':date.today()+timedelta(days=2000*5),\n \t'protocol_research_version':'Тестовая версия',\n \t'protocol_research_date':date.today()+timedelta(days=2000*5),\n \t'contract_date':date.today()+timedelta(days=2000*5),\n \t'name_another_doc':'Тест',\n \t'another_doc_version':'Тестовая',\n \t'another_doc_date':date.today()+timedelta(days=2000*5)\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+'Test.txt')\n print(form.errors)\n print(\"test_wrong_data_ResearchFormMKI_form\")\n self.assertFalse(form.is_valid())\n def test_wrong_file_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с несуществующим типом файла.На момент написания тест кейс провальный!\n #TODO:расширить до каждого отдельного поля\n with open(os.path.abspath(os.curdir)+'Test.aboba', 'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.aboba','rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':'224',\n \t'description':'Ну мы тут тестим тесты',\n \t'main_researcher':1,\n \t'ver_bio':'Тесты тестов',\n \t'version':'Тестовая',\n \t'cast_researcher_date':date.today()-timedelta(days=2000*5),\n \t'accept_research_version':'Тестовая версия',\n \t'accept_research_date':date.today()-timedelta(days=2000*5),\n \t'protocol_research_version':'Тестовая версия',\n \t'protocol_research_date':date.today()-timedelta(days=2000*5),\n \t'contract_date':date.today()-timedelta(days=2000*5),\n \t'name_another_doc':'Тест',\n \t'another_doc_version':'Тестовая',\n \t'another_doc_date':date.today()-timedelta(days=2000*5)\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+'Test.aboba')\n print(form.errors)\n print(\"test_wrong_file_format_ResearchFormMKI_form\")\n self.assertFalse(form.is_valid())\n\n def test_empty_main_researcher_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с невыбранным главным исследователем\n with open(os.path.abspath(os.curdir)+'Test.txt', 'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':'224',\n \t'description':'Ну мы тут тестим тесты',\n \t'main_researcher':None,\n \t'ver_bio':'Тесты тестов',\n \t'version':'Тестовая',\n \t'cast_researcher_date':date.today()-timedelta(days=2000*5),\n \t'accept_research_version':'Тестовая версия',\n \t'accept_research_date':date.today()-timedelta(days=2000*5),\n \t'protocol_research_version':'Тестовая версия',\n \t'protocol_research_date':date.today()-timedelta(days=2000*5),\n \t'contract_date':date.today()-timedelta(days=2000*5),\n \t'name_another_doc':'Тест',\n \t'another_doc_version':'Тестовая',\n \t'another_doc_date':date.today()-timedelta(days=2000*5)\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+'Test.txt')\n print(form.errors)\n print(\"test_empty_main_researcher_format_ResearchFormMKI_form\")\n self.assertFalse(form.is_valid())\n\n def test_empty_char_fields_format_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с незаполненными полями для символьного ввода\n #TODO:расширить до каждого отдельного поля\n with open(os.path.abspath(os.curdir)+'Test.txt', 'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':None,\n \t'description':None,\n \t'main_researcher':1,\n \t'ver_bio':None,\n \t'version':None,\n \t'cast_researcher_date':date.today()-timedelta(days=2000*5),\n \t'accept_research_version':None,\n \t'accept_research_date':date.today()-timedelta(days=2000*5),\n \t'protocol_research_version':None,\n \t'protocol_research_date':date.today()-timedelta(days=2000*5),\n \t'contract_date':date.today()-timedelta(days=2000*5),\n \t'name_another_doc':None,\n \t'another_doc_version':None,\n \t'another_doc_date':date.today()-timedelta(days=2000*5)\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+'Test.txt')\n print(form.errors)\n print(\"test_empty_char_fields_format_ResearchFormMKI_form\")\n self.assertFalse(form.is_valid())\n\n def test_empty_date_fields_ResearchFormMKI_form(self): #Тест формы первичной подачи заявки с пустыми значениями полей даты На момент написания тест кейс провальный!\n \t#TODO:расширить до каждого отдельного поля\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'wb') as f:\n \tf.write(b\"ABOBA\")\n with open(os.path.abspath(os.curdir)+'Test.txt' ,'rb') as f:\n \ttestfile=f.read()\n \tform=ResearchFormMKI(data={\n \t'protocol_number':'224',\n \t'description':'Ну мы тут тестим тесты',\n \t'main_researcher':1,\n \t'ver_bio':'Тесты тестов',\n \t'version':'Тестовая',\n \t'cast_researcher_date':None,\n \t'accept_research_version':'Тестовая версия',\n \t'accept_research_date':None,\n \t'protocol_research_version':'Тестовая версия',\n \t'protocol_research_date':None,\n \t'contract_date':None,\n \t'name_another_doc':'Тест',\n \t'another_doc_version':'Тестовая',\n \t'another_doc_date':None\n \t},\n \tfiles={'another_doc': SimpleUploadedFile('another_doc', testfile),\n \t'contract': SimpleUploadedFile('contract', testfile),\n \t'advertising': SimpleUploadedFile('advertising', testfile),\n \t'write_objects': SimpleUploadedFile('write_objects', testfile),\n \t'protocol_research': SimpleUploadedFile('protocol_research', testfile),\n \t'accept_research': SimpleUploadedFile('accept_research', testfile),\n \t'form_inf': SimpleUploadedFile('form_inf', testfile),\n \t'cast_researcher': SimpleUploadedFile('cast_researcher', testfile),\n \t'list_members': SimpleUploadedFile('list_members', testfile),\n \t'document': SimpleUploadedFile('document', testfile)\n \t})\n os.remove(os.path.abspath(os.curdir)+'Test.txt')\n print(form.errors)\n print(\"test_empty_date_fields_ResearchFormMKI_form\")\n self.assertTrue(form.is_valid())",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
"""component URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from product.views import product_list_view, component, product_detail_view
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from .views import home_page, login_page, register_page, logout_page
from tracker.views import tracker
urlpatterns = [
url(r'^login/$', login_page, name='login'),
url(r'^logout/$', logout_page, name='logout'),
url(r'^register/$', register_page, name='register'),
url(r'^product/$', product_list_view, name='product'),
url(r'^component/$', component, name='component'),
url(r'^tracker/$', tracker, name='tracker'),
url(r'^cart/', include(('cart.urls', 'cart'), namespace='cart')),
#url(r'^detail/$', product_detail_view, name='detail'),
#url(r'^product/product-(?P<parameter>[\w-]+).html', 'views.product', name="product"),
#url(r'^stores/\w+/',.....)
url(r'^detail/(?P<parameter>[\w-]+)/$', product_detail_view, name='detail'),
url(r'^$', home_page, name='home'),
url(r'^admin/', admin.site.urls),
]
|
normal
|
{
"blob_id": "0de735647cf87f64ab64af081da6e11b0ed8a7a7",
"index": 1173,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('^login/$', login_page, name='login'), url('^logout/$',\n logout_page, name='logout'), url('^register/$', register_page, name=\n 'register'), url('^product/$', product_list_view, name='product'), url(\n '^component/$', component, name='component'), url('^tracker/$', tracker,\n name='tracker'), url('^cart/', include(('cart.urls', 'cart'), namespace\n ='cart')), url('^detail/(?P<parameter>[\\\\w-]+)/$', product_detail_view,\n name='detail'), url('^$', home_page, name='home'), url('^admin/', admin\n .site.urls)]\n",
"step-3": "<mask token>\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom product.views import product_list_view, component, product_detail_view\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom .views import home_page, login_page, register_page, logout_page\nfrom tracker.views import tracker\nurlpatterns = [url('^login/$', login_page, name='login'), url('^logout/$',\n logout_page, name='logout'), url('^register/$', register_page, name=\n 'register'), url('^product/$', product_list_view, name='product'), url(\n '^component/$', component, name='component'), url('^tracker/$', tracker,\n name='tracker'), url('^cart/', include(('cart.urls', 'cart'), namespace\n ='cart')), url('^detail/(?P<parameter>[\\\\w-]+)/$', product_detail_view,\n name='detail'), url('^$', home_page, name='home'), url('^admin/', admin\n .site.urls)]\n",
"step-4": "\"\"\"component URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\nfrom product.views import product_list_view, component, product_detail_view\r\nfrom django.conf.urls import url, include\r\nfrom django.contrib import admin\r\n\r\nfrom django.views.generic import TemplateView\r\nfrom .views import home_page, login_page, register_page, logout_page\r\nfrom tracker.views import tracker\r\n\r\nurlpatterns = [\r\n url(r'^login/$', login_page, name='login'),\r\n url(r'^logout/$', logout_page, name='logout'),\r\n url(r'^register/$', register_page, name='register'),\r\n url(r'^product/$', product_list_view, name='product'),\r\n\r\n url(r'^component/$', component, name='component'),\r\n url(r'^tracker/$', tracker, name='tracker'),\r\n\r\n url(r'^cart/', include(('cart.urls', 'cart'), namespace='cart')),\r\n #url(r'^detail/$', product_detail_view, name='detail'),\r\n #url(r'^product/product-(?P<parameter>[\\w-]+).html', 'views.product', name=\"product\"),\r\n #url(r'^stores/\\w+/',.....)\r\n url(r'^detail/(?P<parameter>[\\w-]+)/$', product_detail_view, name='detail'),\r\n url(r'^$', home_page, name='home'),\r\n url(r'^admin/', admin.site.urls),\r\n\r\n]\r\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import pytest
from feast.pyspark.launchers.gcloud import DataprocClusterLauncher
@pytest.fixture
def dataproc_launcher(pytestconfig) -> DataprocClusterLauncher:
cluster_name = pytestconfig.getoption("--dataproc-cluster-name")
region = pytestconfig.getoption("--dataproc-region")
project_id = pytestconfig.getoption("--dataproc-project")
staging_location = pytestconfig.getoption("--dataproc-staging-location")
return DataprocClusterLauncher(
cluster_name=cluster_name,
staging_location=staging_location,
region=region,
project_id=project_id,
)
|
normal
|
{
"blob_id": "ff13ac0ee401471fe5446e8149f019d9da7f3ddf",
"index": 5147,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\[email protected]\ndef dataproc_launcher(pytestconfig) ->DataprocClusterLauncher:\n cluster_name = pytestconfig.getoption('--dataproc-cluster-name')\n region = pytestconfig.getoption('--dataproc-region')\n project_id = pytestconfig.getoption('--dataproc-project')\n staging_location = pytestconfig.getoption('--dataproc-staging-location')\n return DataprocClusterLauncher(cluster_name=cluster_name,\n staging_location=staging_location, region=region, project_id=project_id\n )\n",
"step-3": "import pytest\nfrom feast.pyspark.launchers.gcloud import DataprocClusterLauncher\n\n\[email protected]\ndef dataproc_launcher(pytestconfig) ->DataprocClusterLauncher:\n cluster_name = pytestconfig.getoption('--dataproc-cluster-name')\n region = pytestconfig.getoption('--dataproc-region')\n project_id = pytestconfig.getoption('--dataproc-project')\n staging_location = pytestconfig.getoption('--dataproc-staging-location')\n return DataprocClusterLauncher(cluster_name=cluster_name,\n staging_location=staging_location, region=region, project_id=project_id\n )\n",
"step-4": "import pytest\n\nfrom feast.pyspark.launchers.gcloud import DataprocClusterLauncher\n\n\[email protected]\ndef dataproc_launcher(pytestconfig) -> DataprocClusterLauncher:\n cluster_name = pytestconfig.getoption(\"--dataproc-cluster-name\")\n region = pytestconfig.getoption(\"--dataproc-region\")\n project_id = pytestconfig.getoption(\"--dataproc-project\")\n staging_location = pytestconfig.getoption(\"--dataproc-staging-location\")\n return DataprocClusterLauncher(\n cluster_name=cluster_name,\n staging_location=staging_location,\n region=region,\n project_id=project_id,\n )\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/bin/python3
import sys
# import numpy as np
def _get_change_making_matrix(set_of_coins, r):
matrix = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)]
# matrix = np.array(matrix)
for i in range(1,len(set_of_coins) + 1):
matrix[i][0] = i
return matrix
def change_making(coins, target):
"""This function assumes that all coins are available infinitely.
n is the number that we need to obtain with the fewest number of coins.
coins is a list or tuple with the available denominations."""
matrix = _get_change_making_matrix(coins, target)
for coin in range(1, len(coins) + 1):
for sub_target in range(1, target + 1):
# Just use the coin coins[c - 1].
if coins[coin - 1] == sub_target:
matrix[coin][sub_target] = 1+matrix[coin-1][sub_target]
# coins[c - 1] cannot be included.
# We use the previous solution for making r,
# excluding coins[c - 1].
elif coins[coin - 1] > sub_target:
matrix[coin][sub_target] = matrix[coin - 1][sub_target]
# We can use coins[c - 1].
# We need to decide which one of the following solutions is the best:
# 1. Using the previous solution for making r (without using coins[c - 1]).
# 2. Using the previous solution for making r - coins[c - 1] (without using coins[c - 1]) plus this 1 extra coin.
else:
matrix[coin][sub_target] = (matrix[coin - 1][sub_target]) + (
matrix[coin][sub_target - coins[coin - 1]])
return matrix[-1][-1]
input1 = input()
input2 = input()
# input1 = "10 4"
# input2 = "2 5 3 6"
n, m = input1.strip().split(' ')
n, m = [int(n), int(m)]
c = list(map(int, input2.strip().split(' ')))
# Print the number of ways of making change for 'n' units using coins having the values given by 'c'
ways = change_making(c, n)
print(ways)
|
normal
|
{
"blob_id": "f15bc62fad2c47fed2e9e5d269284ebe7487b789",
"index": 2297,
"step-1": "<mask token>\n\n\ndef _get_change_making_matrix(set_of_coins, r):\n matrix = [[(0) for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)\n ]\n for i in range(1, len(set_of_coins) + 1):\n matrix[i][0] = i\n return matrix\n\n\ndef change_making(coins, target):\n \"\"\"This function assumes that all coins are available infinitely.\n n is the number that we need to obtain with the fewest number of coins.\n coins is a list or tuple with the available denominations.\"\"\"\n matrix = _get_change_making_matrix(coins, target)\n for coin in range(1, len(coins) + 1):\n for sub_target in range(1, target + 1):\n if coins[coin - 1] == sub_target:\n matrix[coin][sub_target] = 1 + matrix[coin - 1][sub_target]\n elif coins[coin - 1] > sub_target:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target]\n else:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target\n ] + matrix[coin][sub_target - coins[coin - 1]]\n return matrix[-1][-1]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef _get_change_making_matrix(set_of_coins, r):\n matrix = [[(0) for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)\n ]\n for i in range(1, len(set_of_coins) + 1):\n matrix[i][0] = i\n return matrix\n\n\ndef change_making(coins, target):\n \"\"\"This function assumes that all coins are available infinitely.\n n is the number that we need to obtain with the fewest number of coins.\n coins is a list or tuple with the available denominations.\"\"\"\n matrix = _get_change_making_matrix(coins, target)\n for coin in range(1, len(coins) + 1):\n for sub_target in range(1, target + 1):\n if coins[coin - 1] == sub_target:\n matrix[coin][sub_target] = 1 + matrix[coin - 1][sub_target]\n elif coins[coin - 1] > sub_target:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target]\n else:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target\n ] + matrix[coin][sub_target - coins[coin - 1]]\n return matrix[-1][-1]\n\n\n<mask token>\nprint(ways)\n",
"step-3": "<mask token>\n\n\ndef _get_change_making_matrix(set_of_coins, r):\n matrix = [[(0) for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)\n ]\n for i in range(1, len(set_of_coins) + 1):\n matrix[i][0] = i\n return matrix\n\n\ndef change_making(coins, target):\n \"\"\"This function assumes that all coins are available infinitely.\n n is the number that we need to obtain with the fewest number of coins.\n coins is a list or tuple with the available denominations.\"\"\"\n matrix = _get_change_making_matrix(coins, target)\n for coin in range(1, len(coins) + 1):\n for sub_target in range(1, target + 1):\n if coins[coin - 1] == sub_target:\n matrix[coin][sub_target] = 1 + matrix[coin - 1][sub_target]\n elif coins[coin - 1] > sub_target:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target]\n else:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target\n ] + matrix[coin][sub_target - coins[coin - 1]]\n return matrix[-1][-1]\n\n\ninput1 = input()\ninput2 = input()\nn, m = input1.strip().split(' ')\nn, m = [int(n), int(m)]\nc = list(map(int, input2.strip().split(' ')))\nways = change_making(c, n)\nprint(ways)\n",
"step-4": "import sys\n\n\ndef _get_change_making_matrix(set_of_coins, r):\n matrix = [[(0) for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)\n ]\n for i in range(1, len(set_of_coins) + 1):\n matrix[i][0] = i\n return matrix\n\n\ndef change_making(coins, target):\n \"\"\"This function assumes that all coins are available infinitely.\n n is the number that we need to obtain with the fewest number of coins.\n coins is a list or tuple with the available denominations.\"\"\"\n matrix = _get_change_making_matrix(coins, target)\n for coin in range(1, len(coins) + 1):\n for sub_target in range(1, target + 1):\n if coins[coin - 1] == sub_target:\n matrix[coin][sub_target] = 1 + matrix[coin - 1][sub_target]\n elif coins[coin - 1] > sub_target:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target]\n else:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target\n ] + matrix[coin][sub_target - coins[coin - 1]]\n return matrix[-1][-1]\n\n\ninput1 = input()\ninput2 = input()\nn, m = input1.strip().split(' ')\nn, m = [int(n), int(m)]\nc = list(map(int, input2.strip().split(' ')))\nways = change_making(c, n)\nprint(ways)\n",
"step-5": "#!/bin/python3\n\nimport sys\n# import numpy as np\n\n\ndef _get_change_making_matrix(set_of_coins, r):\n matrix = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)]\n # matrix = np.array(matrix)\n for i in range(1,len(set_of_coins) + 1):\n matrix[i][0] = i\n\n return matrix\n\n\ndef change_making(coins, target):\n \"\"\"This function assumes that all coins are available infinitely.\n n is the number that we need to obtain with the fewest number of coins.\n coins is a list or tuple with the available denominations.\"\"\"\n matrix = _get_change_making_matrix(coins, target)\n\n for coin in range(1, len(coins) + 1):\n\n for sub_target in range(1, target + 1):\n\n # Just use the coin coins[c - 1].\n if coins[coin - 1] == sub_target:\n matrix[coin][sub_target] = 1+matrix[coin-1][sub_target]\n\n # coins[c - 1] cannot be included.\n # We use the previous solution for making r,\n # excluding coins[c - 1].\n elif coins[coin - 1] > sub_target:\n matrix[coin][sub_target] = matrix[coin - 1][sub_target]\n\n # We can use coins[c - 1].\n # We need to decide which one of the following solutions is the best:\n # 1. Using the previous solution for making r (without using coins[c - 1]).\n # 2. Using the previous solution for making r - coins[c - 1] (without using coins[c - 1]) plus this 1 extra coin.\n else:\n matrix[coin][sub_target] = (matrix[coin - 1][sub_target]) + (\n matrix[coin][sub_target - coins[coin - 1]])\n\n return matrix[-1][-1]\n\n\ninput1 = input()\ninput2 = input()\n\n# input1 = \"10 4\"\n# input2 = \"2 5 3 6\"\n\nn, m = input1.strip().split(' ')\nn, m = [int(n), int(m)]\nc = list(map(int, input2.strip().split(' ')))\n# Print the number of ways of making change for 'n' units using coins having the values given by 'c'\nways = change_making(c, n)\nprint(ways)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
from typing import Union, Tuple
import numpy as np
from UQpy.utilities.kernels.baseclass.GrassmannianKernel import GrassmannianKernel
class ProjectionKernel(GrassmannianKernel):
def __init__(self, kernel_parameter: Union[int, float] = None):
"""
:param kernel_parameter: Number of independent p-planes of each Grassmann point.
"""
super().__init__(kernel_parameter)
def element_wise_operation(self, xi_j: Tuple) -> float:
"""
Compute the Projection kernel entry for a tuple of points on the Grassmann manifold.
:param xi_j: Tuple of orthonormal matrices representing the grassmann points.
"""
xi, xj = xi_j
r = np.dot(xi.T, xj)
n = np.linalg.norm(r, "fro")
return n * n
|
normal
|
{
"blob_id": "14ce803e3deb529b489c150c7ecc702118448acb",
"index": 9022,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass ProjectionKernel(GrassmannianKernel):\n <mask token>\n\n def element_wise_operation(self, xi_j: Tuple) ->float:\n \"\"\"\n Compute the Projection kernel entry for a tuple of points on the Grassmann manifold.\n\n :param xi_j: Tuple of orthonormal matrices representing the grassmann points.\n \"\"\"\n xi, xj = xi_j\n r = np.dot(xi.T, xj)\n n = np.linalg.norm(r, 'fro')\n return n * n\n",
"step-3": "<mask token>\n\n\nclass ProjectionKernel(GrassmannianKernel):\n\n def __init__(self, kernel_parameter: Union[int, float]=None):\n \"\"\"\n :param kernel_parameter: Number of independent p-planes of each Grassmann point.\n \"\"\"\n super().__init__(kernel_parameter)\n\n def element_wise_operation(self, xi_j: Tuple) ->float:\n \"\"\"\n Compute the Projection kernel entry for a tuple of points on the Grassmann manifold.\n\n :param xi_j: Tuple of orthonormal matrices representing the grassmann points.\n \"\"\"\n xi, xj = xi_j\n r = np.dot(xi.T, xj)\n n = np.linalg.norm(r, 'fro')\n return n * n\n",
"step-4": "from typing import Union, Tuple\nimport numpy as np\nfrom UQpy.utilities.kernels.baseclass.GrassmannianKernel import GrassmannianKernel\n\n\nclass ProjectionKernel(GrassmannianKernel):\n\n def __init__(self, kernel_parameter: Union[int, float]=None):\n \"\"\"\n :param kernel_parameter: Number of independent p-planes of each Grassmann point.\n \"\"\"\n super().__init__(kernel_parameter)\n\n def element_wise_operation(self, xi_j: Tuple) ->float:\n \"\"\"\n Compute the Projection kernel entry for a tuple of points on the Grassmann manifold.\n\n :param xi_j: Tuple of orthonormal matrices representing the grassmann points.\n \"\"\"\n xi, xj = xi_j\n r = np.dot(xi.T, xj)\n n = np.linalg.norm(r, 'fro')\n return n * n\n",
"step-5": "from typing import Union, Tuple\n\nimport numpy as np\n\nfrom UQpy.utilities.kernels.baseclass.GrassmannianKernel import GrassmannianKernel\n\n\nclass ProjectionKernel(GrassmannianKernel):\n\n def __init__(self, kernel_parameter: Union[int, float] = None):\n \"\"\"\n :param kernel_parameter: Number of independent p-planes of each Grassmann point.\n \"\"\"\n super().__init__(kernel_parameter)\n\n def element_wise_operation(self, xi_j: Tuple) -> float:\n \"\"\"\n Compute the Projection kernel entry for a tuple of points on the Grassmann manifold.\n\n :param xi_j: Tuple of orthonormal matrices representing the grassmann points.\n \"\"\"\n xi, xj = xi_j\n r = np.dot(xi.T, xj)\n n = np.linalg.norm(r, \"fro\")\n return n * n\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
from launch import LaunchDescription
from launch_ros.actions import Node
import os
params = os.path.join('INSERT_PATH/src/beckhoff_ros', 'config', 'params.yaml')
def generate_launch_description():
return LaunchDescription([Node(package='beckhoff_ros', executable=
'beckhoff_ros_node', name='beckhoff_ros_node', parameters=[params],
output='screen')])
|
normal
|
{
"blob_id": "ae4f8eb71939ff212d05d12f65edeaecf66f2205",
"index": 4874,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef generate_launch_description():\n return LaunchDescription([Node(package='beckhoff_ros', executable=\n 'beckhoff_ros_node', name='beckhoff_ros_node', parameters=[params],\n output='screen')])\n",
"step-3": "<mask token>\nparams = os.path.join('INSERT_PATH/src/beckhoff_ros', 'config', 'params.yaml')\n\n\ndef generate_launch_description():\n return LaunchDescription([Node(package='beckhoff_ros', executable=\n 'beckhoff_ros_node', name='beckhoff_ros_node', parameters=[params],\n output='screen')])\n",
"step-4": "from launch import LaunchDescription\nfrom launch_ros.actions import Node\nimport os\nparams = os.path.join('INSERT_PATH/src/beckhoff_ros', 'config', 'params.yaml')\n\n\ndef generate_launch_description():\n return LaunchDescription([Node(package='beckhoff_ros', executable=\n 'beckhoff_ros_node', name='beckhoff_ros_node', parameters=[params],\n output='screen')])\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import math
import os
import pathfinder as pf
from constants import X_ROBOT_LENGTH, Y_ROBOT_WIDTH, Y_WALL_TO_EXCHANGE_FAR, \
X_WALL_TO_SWITCH_NEAR
from utilities.functions import GeneratePath
class settings():
order = pf.FIT_HERMITE_QUINTIC
samples = 1000000
period = 0.02
maxVelocity = 6.0
maxAcceleration = 10
maxJerk = 30
# The waypoints are entered as X, Y, and Theta. Theta is measured clockwise from the X-axis and
# is in units of radians. It is important to generate the paths in a consistent manner to those
# used by the controller. For example, use either metric or imperial units. Also, use a
# consistent frame of reference. This means that +X is forward, -X is backward, +Y is right, and
# -Y is left, +headings are going from +X towards +Y, and -headings are going from +X to -Y.
waypoints = [
pf.Waypoint(0, 0, 0),
pf.Waypoint(96 / 12, -22 / 12, 0),
]
GeneratePath(os.path.dirname(__file__), "first_cube_middle_start_left_switch", waypoints, settings)
|
normal
|
{
"blob_id": "5e06dfb7aac64b5b98b4c0d88a86f038baf44feb",
"index": 5412,
"step-1": "<mask token>\n\n\nclass settings:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass settings:\n order = pf.FIT_HERMITE_QUINTIC\n samples = 1000000\n period = 0.02\n maxVelocity = 6.0\n maxAcceleration = 10\n maxJerk = 30\n\n\n<mask token>\nGeneratePath(os.path.dirname(__file__),\n 'first_cube_middle_start_left_switch', waypoints, settings)\n",
"step-3": "<mask token>\n\n\nclass settings:\n order = pf.FIT_HERMITE_QUINTIC\n samples = 1000000\n period = 0.02\n maxVelocity = 6.0\n maxAcceleration = 10\n maxJerk = 30\n\n\nwaypoints = [pf.Waypoint(0, 0, 0), pf.Waypoint(96 / 12, -22 / 12, 0)]\nGeneratePath(os.path.dirname(__file__),\n 'first_cube_middle_start_left_switch', waypoints, settings)\n",
"step-4": "import math\nimport os\nimport pathfinder as pf\nfrom constants import X_ROBOT_LENGTH, Y_ROBOT_WIDTH, Y_WALL_TO_EXCHANGE_FAR, X_WALL_TO_SWITCH_NEAR\nfrom utilities.functions import GeneratePath\n\n\nclass settings:\n order = pf.FIT_HERMITE_QUINTIC\n samples = 1000000\n period = 0.02\n maxVelocity = 6.0\n maxAcceleration = 10\n maxJerk = 30\n\n\nwaypoints = [pf.Waypoint(0, 0, 0), pf.Waypoint(96 / 12, -22 / 12, 0)]\nGeneratePath(os.path.dirname(__file__),\n 'first_cube_middle_start_left_switch', waypoints, settings)\n",
"step-5": "import math\r\nimport os\r\nimport pathfinder as pf\r\nfrom constants import X_ROBOT_LENGTH, Y_ROBOT_WIDTH, Y_WALL_TO_EXCHANGE_FAR, \\\r\n X_WALL_TO_SWITCH_NEAR\r\nfrom utilities.functions import GeneratePath\r\n\r\n\r\nclass settings():\r\n order = pf.FIT_HERMITE_QUINTIC\r\n samples = 1000000\r\n period = 0.02\r\n maxVelocity = 6.0\r\n maxAcceleration = 10\r\n maxJerk = 30\r\n\r\n\r\n# The waypoints are entered as X, Y, and Theta. Theta is measured clockwise from the X-axis and\r\n# is in units of radians. It is important to generate the paths in a consistent manner to those\r\n# used by the controller. For example, use either metric or imperial units. Also, use a\r\n# consistent frame of reference. This means that +X is forward, -X is backward, +Y is right, and\r\n# -Y is left, +headings are going from +X towards +Y, and -headings are going from +X to -Y.\r\nwaypoints = [\r\n pf.Waypoint(0, 0, 0),\r\n pf.Waypoint(96 / 12, -22 / 12, 0),\r\n]\r\n\r\nGeneratePath(os.path.dirname(__file__), \"first_cube_middle_start_left_switch\", waypoints, settings)\r\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
data = [
"........#.............#........",
"...#....#...#....#.............",
".#..#...#............#.....#..#",
"..#......#..##............###..",
"..........#......#..#..#.......",
".#..#.......#.........#.#......",
".........#..#....##..#.##....#.",
"..#....##...#..................",
"##..........#.##...#....##..#..",
"...#....#...#..............#...",
"...........................#..#",
"..##.##.#..................#...",
"...#.##..#............#........",
"........#.......#...#.....##.#.",
".##..........#......#.......#..",
"...#..........#...#..#.......#.",
"......#...#...#.##.......#.#...",
"........#...#...#...##.........",
"#..............#.#....#.......#",
"..#..#..#.#....#...............",
".....#........#...#..........#.",
"##......#...#..#.##.......#....",
"..#.#.....#.#.............#.#.#",
"#..#..##......##...#...........",
"..#......#........#.....#......",
".....#.......#....#.#...#......",
"...#........#...........#...#..",
".......#.#...........###....#..",
"...#...........##....##........",
"#....#..####....#.....#..#....#",
"..........#...........#........",
"...#.......#....#.#.........#..",
"....#...#.......#..###.........",
"......#......#..#......#..#....",
"...#.....#............#..#.....",
"...#.#.#.#..#.......#.....#....",
"#....##...#.........#...##.....",
"#..#.......#..#..#..#...##.....",
"#.......#............#.....#...",
".#........##....##...#........#",
".....#...#.....................",
".......#........#..............",
".....#............#.#.#...#.#..",
".....##..#.............#.......",
"..#.##..#........#..#...#......",
".........#.#....#...........#..",
".#.....#..#....#.....#...#.....",
"....#.#................#.......",
"...............##......#...#...",
".##...#...#.......##.#....#....",
"............#........#.......#.",
"......##.#.#...................",
".#.#..............#.......#....",
"#.....#...#.......#..#...#.....",
".............#....#..#......#..",
"........#...##................#",
".......#...#..#..##............",
"..#..#...##...#..#.#.....#...#.",
".#.#...#.........#.#...........",
"...###....#.......#...#........",
"........#......##.#...#..##..#.",
".....................#.#.......",
".............#...........#...#.",
"#..#..#.....#.#...#............",
"...#....#.....#...........#....",
"..##.....##...#......#..##.....",
"#.....#.....###.#.....#....##..",
".#...........###...............",
"..................#..##.#...#..",
"................#....##.#......",
".#.#.#...#....#.........#..#.#.",
"#.......#........##............",
".......##.#....#.#............#",
"..........#..##.#....#.........",
"........##..#....#.............",
".........#....#...........##...",
"#.........#.#..#..#..........#.",
".....#........#......#.........",
"....#.#.#...............#......",
".#..#..##...#.##..........#....",
"..#....................#.#.....",
".........#....#...........#.#.#",
"........#....##.##.............",
"..#.....#.......#..#......#....",
"#..........#.#.....#.#....#....",
"........##.#.....#..#.....#.#..",
"...................#...#....#.#",
"............#..#....#...#...#..",
"..............#.#.........#....",
"...#..#..#.#..##..##...........",
".#...........................#.",
".#.......#...........#....#.#.#",
"......#..#...#........#...##...",
".........#......#.#.......#...#",
"...#..##................#......",
".............#.#..##....#.#....",
"...............#..#......#.....",
".#......#.#.#....#........#....",
"........#..#.##..#..#.........#",
"...#....#.#...#..#.......#..#..",
"..#...##.........#..#...#......",
"...#...........#.............#.",
"....#.....................#....",
".....#..#...............#.#...#",
"....#..........#........#......",
"..#....#........##..##.........",
"...#....#..#.#.......#...#.....",
"..#........#....#...##....#.#..",
".#...#........##.....#....###..",
"#....#....##......#........#...",
".........#..#.#..........#....#",
"....#...#.....#.......##.......",
"..............#..........#.##..",
"#...#..#..............#......#.",
".................#......##....#",
"..#..##..#.......#..#.#......#.",
".............#........#.....#.#",
".#.##............#..#..........",
"..#...#...........#..##........",
".#....#...#....#.......#.......",
"...#.#..#..#..#....#.....#..#..",
"....#..##..............#...#...",
"#..........###......###........",
".##.##......#..#............#..",
".#...........#.#.....#...#.....",
"#.#..#...#............#........",
".........#...#...#..........##.",
".......###..#..........#.......",
"...........###.....#........#..",
".#.............#.....#......#..",
"...#.....#....#.#.........##...",
"....##..##...#.......##........",
"......#....##.........#......#.",
"..........#.....##..#.....#..#.",
"..........####...#..#.........#",
".##....#..#.#...#.......#......",
"...#.#.##.#.#...#....#.#.#.....",
".........#...##........##.....#",
"..#........#..........##...##.#",
"##...##..........#.#...........",
"..............#......#.........",
"........#.....#.#.......#......",
".#...#.....#....#.#..#.........",
".....#....................##...",
"....#..................#.#...##",
".....#............#..##........",
"#..........#....#.#.......##.#.",
"....#..#.....................#.",
"#..#....##.....#...............",
"..#...#..#..##....#.#..........",
".......#......#.#.......#.....#",
"...#.#.......#...#.##..........",
"....#..........#....#.#.#......",
".......#..#..........#..##.....",
"#......#......#...#......#...#.",
"###..#....##......##........#..",
".#..........#.....#.......#.#..",
".......#.....#.....#.#.........",
"..#...#....#...................",
"..............#.##.............",
".#...#.......#.##...#.#.......#",
".......#......................#",
"....#.#...#.#........#.........",
".#......#....#...#.............",
"#.......#...###.....#.#.#..#...",
"#....##.#...............##.....",
"..#.......#..................#.",
".....####...............#......",
".##......#......#.#.......##.#.",
"#......##..###....#....#......#",
".##.......##.##...#.##.........",
"......##............#.......#..",
"......#..#.....##.#............",
".#..........#.....##...........",
"#.........#......#......##.#...",
".........#.......#..#......#.#.",
".........#.......#...........#.",
".#..##.#..................##...",
".............#.............#...",
".....##........#......##...##..",
"..#..#.#.....#..#....#.........",
".....#....#.....#.....#........",
"#......##.....#....#....#......",
"#.................#..#.#......#",
".......#..#......#....#.#...#.#",
"....#.........#..#..........#.#",
"##......#............#...#...#.",
"....##......#...#.....#....##..",
".#...##.........#..............",
"......#.....................#..",
"..#..........###....#..........",
"#....#...#..#.............#....",
"#........#.#......#....#.......",
".#...#.......#..#...#.#...#..#.",
"................##.#.....#.....",
"###.......#...#................",
"...#.......#...#.#.....#.......",
"..#.........#.....#.#.......#..",
"......#.......................#",
"#.....#.#..#....#.......#......",
"...#....#..#....####...........",
".............#.....#...##......",
".......#.........#...#..#......",
".##..#.........#....#.#........",
"....##...#.#...........#....#..",
".........................##....",
"..###.......##....#.#.........#",
".#....#.#.#...........##....#..",
"......#...#..#..#..#..#.......#",
"..#....#.#.......#..#..#..#...#",
".....##...#.##....#.#...#......",
".........#..#....#..#..........",
".##..##.........#.#.....#......",
"..........#...##...#.#...#.....",
"#.##..#..#.............#.......",
"...#...........#.......#......#",
".......#....#....#...##.......#",
"..#.##........###..#......#....",
"...#...........###......#..#..#",
".#.........#.#.........#.#.....",
"##.......##.##.##......##......",
"............#...#..........#...",
"....................#..........",
"...#..#...........#...#...#....",
".................#...#......###",
"...#................#.#.##.....",
"...............#........#......",
"#.............##......#.#..#...",
"..#.#.....#..#.##.....##...#...",
"......#.........#......#.......",
"#.......#......#....#........#.",
".#..##.....#.........#.........",
"....##.##.#...#.........##.#...",
"...............#..#..#..##.....",
".#..#...............###........",
".##............##..............",
"...............#...##...#...#.#",
"..#.#......#.#..#.............#",
"#.#..#..##.........#.#.#...#...",
"....##.#....................##.",
".........#..#.....#.....#..#..#",
"....#......#......#.##....#....",
"........###..#.............#..#",
"##................#.........#..",
"#.....#.......#....#...........",
"..#.......#..#........#....#...",
"..#.#.##..#.#...##........#.##.",
"..#..........#............#....",
"..........#...............##...",
"..........###........#.#.......",
".....###..#.............#......",
"##.............#...#.....#.....",
".....#......#....#........#.#..",
"............#..#..............#",
".................#...........##",
"#........#.........###.....#...",
"..#.#..............##......#.#.",
".#...........#.........#..##..#",
"...............................",
".#.....#..#....#....#......#...",
".#...#......#.#..#....#.......#",
"......#.##.......#......#......",
"......#..###..#................",
"#..#.....#........##...#.......",
"......##.........##....#...##..",
".#..........#.................#",
"#..#.......#...............#...",
".........#..###....#.#.##.#....",
"..#...#.##..##...............##",
".........#.....................",
".#....##...#......#....#.......",
"............#..........#..#....",
"...#......##....#....#........#",
".#...................#.........",
"#.#........###....#..........#.",
".........#....#....#........##.",
".#....#..#.........#..#........",
"...............#..#...#..#...##",
".........#....##....#......#...",
".#.............................",
"...#........#...#.#...#.#..#...",
".....#..##...#.#...............",
"#.....#....#.........#.........",
"#...#...........##.........#...",
"..##........#.#...#...#......#.",
"...........#.....#...#.#.......",
"......###....#.....#...........",
"......##...#..........#....#.#.",
".......##..##..........#.......",
"....#............#..#....##....",
"..##...................#.#.....",
"...#.#..#.#....................",
".#..##..#............##.###..#.",
"#.#...#....#.#..........#.#....",
"........#....#.....#...........",
"..##....#...#.......#..........",
"...........##.##....#..........",
".....#............#............",
".......#.............#....#....",
".................#......#......",
"......##.......#....#..##...#..",
".#..#....#.....................",
"...#.#.#...#......##...........",
"##........##.#....#....#.......",
".......#.....#..#..#...#.##....",
"#..........#....#.#..#..#..#...",
"...##..............#...........",
".........#.....#.#....#.......#",
".........#....##..#..##..#.....",
".....#......................#..",
"...###...#..#......#...........",
"....#.....................#....",
"...............................",
"..#.....###.......#..#....#....",
"#..........#.................#.",
"......#.......###.......#..##..",
".............#.##..............",
"......#..#.#..#...........#....",
"...#....##.#...#..#.#...#....#.",
"..................#...#....#.##",
"......#.#....#.................",
"......#.#.....#.....#..##......",
"#..##...........#..#.....#.##..",
]
def treeCounter(moveRight, moveDown):
row = 0
index = 0
trees = 0
finished = False
while not finished:
row += moveDown
if len(data) > row:
index = (index + moveRight) % len(data[row])
if data[row][index] == '#':
trees += 1
else:
finished = True
print(trees)
treeCounter(1,1)
treeCounter(3,1)
treeCounter(5,1)
treeCounter(7,1)
treeCounter(1,2)
|
normal
|
{
"blob_id": "c22651437094723b711a959e031f1c7f928f735a",
"index": 7645,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef treeCounter(moveRight, moveDown):\n row = 0\n index = 0\n trees = 0\n finished = False\n while not finished:\n row += moveDown\n if len(data) > row:\n index = (index + moveRight) % len(data[row])\n if data[row][index] == '#':\n trees += 1\n else:\n finished = True\n print(trees)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef treeCounter(moveRight, moveDown):\n row = 0\n index = 0\n trees = 0\n finished = False\n while not finished:\n row += moveDown\n if len(data) > row:\n index = (index + moveRight) % len(data[row])\n if data[row][index] == '#':\n trees += 1\n else:\n finished = True\n print(trees)\n\n\ntreeCounter(1, 1)\ntreeCounter(3, 1)\ntreeCounter(5, 1)\ntreeCounter(7, 1)\ntreeCounter(1, 2)\n",
"step-4": "data = ['........#.............#........',\n '...#....#...#....#.............', '.#..#...#............#.....#..#',\n '..#......#..##............###..', '..........#......#..#..#.......',\n '.#..#.......#.........#.#......', '.........#..#....##..#.##....#.',\n '..#....##...#..................', '##..........#.##...#....##..#..',\n '...#....#...#..............#...', '...........................#..#',\n '..##.##.#..................#...', '...#.##..#............#........',\n '........#.......#...#.....##.#.', '.##..........#......#.......#..',\n '...#..........#...#..#.......#.', '......#...#...#.##.......#.#...',\n '........#...#...#...##.........', '#..............#.#....#.......#',\n '..#..#..#.#....#...............', '.....#........#...#..........#.',\n '##......#...#..#.##.......#....', '..#.#.....#.#.............#.#.#',\n '#..#..##......##...#...........', '..#......#........#.....#......',\n '.....#.......#....#.#...#......', '...#........#...........#...#..',\n '.......#.#...........###....#..', '...#...........##....##........',\n '#....#..####....#.....#..#....#', '..........#...........#........',\n '...#.......#....#.#.........#..', '....#...#.......#..###.........',\n '......#......#..#......#..#....', '...#.....#............#..#.....',\n '...#.#.#.#..#.......#.....#....', '#....##...#.........#...##.....',\n '#..#.......#..#..#..#...##.....', '#.......#............#.....#...',\n '.#........##....##...#........#', '.....#...#.....................',\n '.......#........#..............', '.....#............#.#.#...#.#..',\n '.....##..#.............#.......', '..#.##..#........#..#...#......',\n '.........#.#....#...........#..', '.#.....#..#....#.....#...#.....',\n '....#.#................#.......', '...............##......#...#...',\n '.##...#...#.......##.#....#....', '............#........#.......#.',\n '......##.#.#...................', '.#.#..............#.......#....',\n '#.....#...#.......#..#...#.....', '.............#....#..#......#..',\n '........#...##................#', '.......#...#..#..##............',\n '..#..#...##...#..#.#.....#...#.', '.#.#...#.........#.#...........',\n '...###....#.......#...#........', '........#......##.#...#..##..#.',\n '.....................#.#.......', '.............#...........#...#.',\n '#..#..#.....#.#...#............', '...#....#.....#...........#....',\n '..##.....##...#......#..##.....', '#.....#.....###.#.....#....##..',\n '.#...........###...............', '..................#..##.#...#..',\n '................#....##.#......', '.#.#.#...#....#.........#..#.#.',\n '#.......#........##............', '.......##.#....#.#............#',\n '..........#..##.#....#.........', '........##..#....#.............',\n '.........#....#...........##...', '#.........#.#..#..#..........#.',\n '.....#........#......#.........', '....#.#.#...............#......',\n '.#..#..##...#.##..........#....', '..#....................#.#.....',\n '.........#....#...........#.#.#', '........#....##.##.............',\n '..#.....#.......#..#......#....', '#..........#.#.....#.#....#....',\n '........##.#.....#..#.....#.#..', '...................#...#....#.#',\n '............#..#....#...#...#..', '..............#.#.........#....',\n '...#..#..#.#..##..##...........', '.#...........................#.',\n '.#.......#...........#....#.#.#', '......#..#...#........#...##...',\n '.........#......#.#.......#...#', '...#..##................#......',\n '.............#.#..##....#.#....', '...............#..#......#.....',\n '.#......#.#.#....#........#....', '........#..#.##..#..#.........#',\n '...#....#.#...#..#.......#..#..', '..#...##.........#..#...#......',\n '...#...........#.............#.', '....#.....................#....',\n '.....#..#...............#.#...#', '....#..........#........#......',\n '..#....#........##..##.........', '...#....#..#.#.......#...#.....',\n '..#........#....#...##....#.#..', '.#...#........##.....#....###..',\n '#....#....##......#........#...', '.........#..#.#..........#....#',\n '....#...#.....#.......##.......', '..............#..........#.##..',\n '#...#..#..............#......#.', '.................#......##....#',\n '..#..##..#.......#..#.#......#.', '.............#........#.....#.#',\n '.#.##............#..#..........', '..#...#...........#..##........',\n '.#....#...#....#.......#.......', '...#.#..#..#..#....#.....#..#..',\n '....#..##..............#...#...', '#..........###......###........',\n '.##.##......#..#............#..', '.#...........#.#.....#...#.....',\n '#.#..#...#............#........', '.........#...#...#..........##.',\n '.......###..#..........#.......', '...........###.....#........#..',\n '.#.............#.....#......#..', '...#.....#....#.#.........##...',\n '....##..##...#.......##........', '......#....##.........#......#.',\n '..........#.....##..#.....#..#.', '..........####...#..#.........#',\n '.##....#..#.#...#.......#......', '...#.#.##.#.#...#....#.#.#.....',\n '.........#...##........##.....#', '..#........#..........##...##.#',\n '##...##..........#.#...........', '..............#......#.........',\n '........#.....#.#.......#......', '.#...#.....#....#.#..#.........',\n '.....#....................##...', '....#..................#.#...##',\n '.....#............#..##........', '#..........#....#.#.......##.#.',\n '....#..#.....................#.', '#..#....##.....#...............',\n '..#...#..#..##....#.#..........', '.......#......#.#.......#.....#',\n '...#.#.......#...#.##..........', '....#..........#....#.#.#......',\n '.......#..#..........#..##.....', '#......#......#...#......#...#.',\n '###..#....##......##........#..', '.#..........#.....#.......#.#..',\n '.......#.....#.....#.#.........', '..#...#....#...................',\n '..............#.##.............', '.#...#.......#.##...#.#.......#',\n '.......#......................#', '....#.#...#.#........#.........',\n '.#......#....#...#.............', '#.......#...###.....#.#.#..#...',\n '#....##.#...............##.....', '..#.......#..................#.',\n '.....####...............#......', '.##......#......#.#.......##.#.',\n '#......##..###....#....#......#', '.##.......##.##...#.##.........',\n '......##............#.......#..', '......#..#.....##.#............',\n '.#..........#.....##...........', '#.........#......#......##.#...',\n '.........#.......#..#......#.#.', '.........#.......#...........#.',\n '.#..##.#..................##...', '.............#.............#...',\n '.....##........#......##...##..', '..#..#.#.....#..#....#.........',\n '.....#....#.....#.....#........', '#......##.....#....#....#......',\n '#.................#..#.#......#', '.......#..#......#....#.#...#.#',\n '....#.........#..#..........#.#', '##......#............#...#...#.',\n '....##......#...#.....#....##..', '.#...##.........#..............',\n '......#.....................#..', '..#..........###....#..........',\n '#....#...#..#.............#....', '#........#.#......#....#.......',\n '.#...#.......#..#...#.#...#..#.', '................##.#.....#.....',\n '###.......#...#................', '...#.......#...#.#.....#.......',\n '..#.........#.....#.#.......#..', '......#.......................#',\n '#.....#.#..#....#.......#......', '...#....#..#....####...........',\n '.............#.....#...##......', '.......#.........#...#..#......',\n '.##..#.........#....#.#........', '....##...#.#...........#....#..',\n '.........................##....', '..###.......##....#.#.........#',\n '.#....#.#.#...........##....#..', '......#...#..#..#..#..#.......#',\n '..#....#.#.......#..#..#..#...#', '.....##...#.##....#.#...#......',\n '.........#..#....#..#..........', '.##..##.........#.#.....#......',\n '..........#...##...#.#...#.....', '#.##..#..#.............#.......',\n '...#...........#.......#......#', '.......#....#....#...##.......#',\n '..#.##........###..#......#....', '...#...........###......#..#..#',\n '.#.........#.#.........#.#.....', '##.......##.##.##......##......',\n '............#...#..........#...', '....................#..........',\n '...#..#...........#...#...#....', '.................#...#......###',\n '...#................#.#.##.....', '...............#........#......',\n '#.............##......#.#..#...', '..#.#.....#..#.##.....##...#...',\n '......#.........#......#.......', '#.......#......#....#........#.',\n '.#..##.....#.........#.........', '....##.##.#...#.........##.#...',\n '...............#..#..#..##.....', '.#..#...............###........',\n '.##............##..............', '...............#...##...#...#.#',\n '..#.#......#.#..#.............#', '#.#..#..##.........#.#.#...#...',\n '....##.#....................##.', '.........#..#.....#.....#..#..#',\n '....#......#......#.##....#....', '........###..#.............#..#',\n '##................#.........#..', '#.....#.......#....#...........',\n '..#.......#..#........#....#...', '..#.#.##..#.#...##........#.##.',\n '..#..........#............#....', '..........#...............##...',\n '..........###........#.#.......', '.....###..#.............#......',\n '##.............#...#.....#.....', '.....#......#....#........#.#..',\n '............#..#..............#', '.................#...........##',\n '#........#.........###.....#...', '..#.#..............##......#.#.',\n '.#...........#.........#..##..#', '...............................',\n '.#.....#..#....#....#......#...', '.#...#......#.#..#....#.......#',\n '......#.##.......#......#......', '......#..###..#................',\n '#..#.....#........##...#.......', '......##.........##....#...##..',\n '.#..........#.................#', '#..#.......#...............#...',\n '.........#..###....#.#.##.#....', '..#...#.##..##...............##',\n '.........#.....................', '.#....##...#......#....#.......',\n '............#..........#..#....', '...#......##....#....#........#',\n '.#...................#.........', '#.#........###....#..........#.',\n '.........#....#....#........##.', '.#....#..#.........#..#........',\n '...............#..#...#..#...##', '.........#....##....#......#...',\n '.#.............................', '...#........#...#.#...#.#..#...',\n '.....#..##...#.#...............', '#.....#....#.........#.........',\n '#...#...........##.........#...', '..##........#.#...#...#......#.',\n '...........#.....#...#.#.......', '......###....#.....#...........',\n '......##...#..........#....#.#.', '.......##..##..........#.......',\n '....#............#..#....##....', '..##...................#.#.....',\n '...#.#..#.#....................', '.#..##..#............##.###..#.',\n '#.#...#....#.#..........#.#....', '........#....#.....#...........',\n '..##....#...#.......#..........', '...........##.##....#..........',\n '.....#............#............', '.......#.............#....#....',\n '.................#......#......', '......##.......#....#..##...#..',\n '.#..#....#.....................', '...#.#.#...#......##...........',\n '##........##.#....#....#.......', '.......#.....#..#..#...#.##....',\n '#..........#....#.#..#..#..#...', '...##..............#...........',\n '.........#.....#.#....#.......#', '.........#....##..#..##..#.....',\n '.....#......................#..', '...###...#..#......#...........',\n '....#.....................#....', '...............................',\n '..#.....###.......#..#....#....', '#..........#.................#.',\n '......#.......###.......#..##..', '.............#.##..............',\n '......#..#.#..#...........#....', '...#....##.#...#..#.#...#....#.',\n '..................#...#....#.##', '......#.#....#.................',\n '......#.#.....#.....#..##......', '#..##...........#..#.....#.##..']\n\n\ndef treeCounter(moveRight, moveDown):\n row = 0\n index = 0\n trees = 0\n finished = False\n while not finished:\n row += moveDown\n if len(data) > row:\n index = (index + moveRight) % len(data[row])\n if data[row][index] == '#':\n trees += 1\n else:\n finished = True\n print(trees)\n\n\ntreeCounter(1, 1)\ntreeCounter(3, 1)\ntreeCounter(5, 1)\ntreeCounter(7, 1)\ntreeCounter(1, 2)\n",
"step-5": "data = [\n \"........#.............#........\",\n \"...#....#...#....#.............\",\n \".#..#...#............#.....#..#\",\n \"..#......#..##............###..\",\n \"..........#......#..#..#.......\",\n \".#..#.......#.........#.#......\",\n \".........#..#....##..#.##....#.\",\n \"..#....##...#..................\",\n \"##..........#.##...#....##..#..\",\n \"...#....#...#..............#...\",\n \"...........................#..#\",\n \"..##.##.#..................#...\",\n \"...#.##..#............#........\",\n \"........#.......#...#.....##.#.\",\n \".##..........#......#.......#..\",\n \"...#..........#...#..#.......#.\",\n \"......#...#...#.##.......#.#...\",\n \"........#...#...#...##.........\",\n \"#..............#.#....#.......#\",\n \"..#..#..#.#....#...............\",\n \".....#........#...#..........#.\",\n \"##......#...#..#.##.......#....\",\n \"..#.#.....#.#.............#.#.#\",\n \"#..#..##......##...#...........\",\n \"..#......#........#.....#......\",\n \".....#.......#....#.#...#......\",\n \"...#........#...........#...#..\",\n \".......#.#...........###....#..\",\n \"...#...........##....##........\",\n \"#....#..####....#.....#..#....#\",\n \"..........#...........#........\",\n \"...#.......#....#.#.........#..\",\n \"....#...#.......#..###.........\",\n \"......#......#..#......#..#....\",\n \"...#.....#............#..#.....\",\n \"...#.#.#.#..#.......#.....#....\",\n \"#....##...#.........#...##.....\",\n \"#..#.......#..#..#..#...##.....\",\n \"#.......#............#.....#...\",\n \".#........##....##...#........#\",\n \".....#...#.....................\",\n \".......#........#..............\",\n \".....#............#.#.#...#.#..\",\n \".....##..#.............#.......\",\n \"..#.##..#........#..#...#......\",\n \".........#.#....#...........#..\",\n \".#.....#..#....#.....#...#.....\",\n \"....#.#................#.......\",\n \"...............##......#...#...\",\n \".##...#...#.......##.#....#....\",\n \"............#........#.......#.\",\n \"......##.#.#...................\",\n \".#.#..............#.......#....\",\n \"#.....#...#.......#..#...#.....\",\n \".............#....#..#......#..\",\n \"........#...##................#\",\n \".......#...#..#..##............\",\n \"..#..#...##...#..#.#.....#...#.\",\n \".#.#...#.........#.#...........\",\n \"...###....#.......#...#........\",\n \"........#......##.#...#..##..#.\",\n \".....................#.#.......\",\n \".............#...........#...#.\",\n \"#..#..#.....#.#...#............\",\n \"...#....#.....#...........#....\",\n \"..##.....##...#......#..##.....\",\n \"#.....#.....###.#.....#....##..\",\n \".#...........###...............\",\n \"..................#..##.#...#..\",\n \"................#....##.#......\",\n \".#.#.#...#....#.........#..#.#.\",\n \"#.......#........##............\",\n \".......##.#....#.#............#\",\n \"..........#..##.#....#.........\",\n \"........##..#....#.............\",\n \".........#....#...........##...\",\n \"#.........#.#..#..#..........#.\",\n \".....#........#......#.........\",\n \"....#.#.#...............#......\",\n \".#..#..##...#.##..........#....\",\n \"..#....................#.#.....\",\n \".........#....#...........#.#.#\",\n \"........#....##.##.............\",\n \"..#.....#.......#..#......#....\",\n \"#..........#.#.....#.#....#....\",\n \"........##.#.....#..#.....#.#..\",\n \"...................#...#....#.#\",\n \"............#..#....#...#...#..\",\n \"..............#.#.........#....\",\n \"...#..#..#.#..##..##...........\",\n \".#...........................#.\",\n \".#.......#...........#....#.#.#\",\n \"......#..#...#........#...##...\",\n \".........#......#.#.......#...#\",\n \"...#..##................#......\",\n \".............#.#..##....#.#....\",\n \"...............#..#......#.....\",\n \".#......#.#.#....#........#....\",\n \"........#..#.##..#..#.........#\",\n \"...#....#.#...#..#.......#..#..\",\n \"..#...##.........#..#...#......\",\n \"...#...........#.............#.\",\n \"....#.....................#....\",\n \".....#..#...............#.#...#\",\n \"....#..........#........#......\",\n \"..#....#........##..##.........\",\n \"...#....#..#.#.......#...#.....\",\n \"..#........#....#...##....#.#..\",\n \".#...#........##.....#....###..\",\n \"#....#....##......#........#...\",\n \".........#..#.#..........#....#\",\n \"....#...#.....#.......##.......\",\n \"..............#..........#.##..\",\n \"#...#..#..............#......#.\",\n \".................#......##....#\",\n \"..#..##..#.......#..#.#......#.\",\n \".............#........#.....#.#\",\n \".#.##............#..#..........\",\n \"..#...#...........#..##........\",\n \".#....#...#....#.......#.......\",\n \"...#.#..#..#..#....#.....#..#..\",\n \"....#..##..............#...#...\",\n \"#..........###......###........\",\n \".##.##......#..#............#..\",\n \".#...........#.#.....#...#.....\",\n \"#.#..#...#............#........\",\n \".........#...#...#..........##.\",\n \".......###..#..........#.......\",\n \"...........###.....#........#..\",\n \".#.............#.....#......#..\",\n \"...#.....#....#.#.........##...\",\n \"....##..##...#.......##........\",\n \"......#....##.........#......#.\",\n \"..........#.....##..#.....#..#.\",\n \"..........####...#..#.........#\",\n \".##....#..#.#...#.......#......\",\n \"...#.#.##.#.#...#....#.#.#.....\",\n \".........#...##........##.....#\",\n \"..#........#..........##...##.#\",\n \"##...##..........#.#...........\",\n \"..............#......#.........\",\n \"........#.....#.#.......#......\",\n \".#...#.....#....#.#..#.........\",\n \".....#....................##...\",\n \"....#..................#.#...##\",\n \".....#............#..##........\",\n \"#..........#....#.#.......##.#.\",\n \"....#..#.....................#.\",\n \"#..#....##.....#...............\",\n \"..#...#..#..##....#.#..........\",\n \".......#......#.#.......#.....#\",\n \"...#.#.......#...#.##..........\",\n \"....#..........#....#.#.#......\",\n \".......#..#..........#..##.....\",\n \"#......#......#...#......#...#.\",\n \"###..#....##......##........#..\",\n \".#..........#.....#.......#.#..\",\n \".......#.....#.....#.#.........\",\n \"..#...#....#...................\",\n \"..............#.##.............\",\n \".#...#.......#.##...#.#.......#\",\n \".......#......................#\",\n \"....#.#...#.#........#.........\",\n \".#......#....#...#.............\",\n \"#.......#...###.....#.#.#..#...\",\n \"#....##.#...............##.....\",\n \"..#.......#..................#.\",\n \".....####...............#......\",\n \".##......#......#.#.......##.#.\",\n \"#......##..###....#....#......#\",\n \".##.......##.##...#.##.........\",\n \"......##............#.......#..\",\n \"......#..#.....##.#............\",\n \".#..........#.....##...........\",\n \"#.........#......#......##.#...\",\n \".........#.......#..#......#.#.\",\n \".........#.......#...........#.\",\n \".#..##.#..................##...\",\n \".............#.............#...\",\n \".....##........#......##...##..\",\n \"..#..#.#.....#..#....#.........\",\n \".....#....#.....#.....#........\",\n \"#......##.....#....#....#......\",\n \"#.................#..#.#......#\",\n \".......#..#......#....#.#...#.#\",\n \"....#.........#..#..........#.#\",\n \"##......#............#...#...#.\",\n \"....##......#...#.....#....##..\",\n \".#...##.........#..............\",\n \"......#.....................#..\",\n \"..#..........###....#..........\",\n \"#....#...#..#.............#....\",\n \"#........#.#......#....#.......\",\n \".#...#.......#..#...#.#...#..#.\",\n \"................##.#.....#.....\",\n \"###.......#...#................\",\n \"...#.......#...#.#.....#.......\",\n \"..#.........#.....#.#.......#..\",\n \"......#.......................#\",\n \"#.....#.#..#....#.......#......\",\n \"...#....#..#....####...........\",\n \".............#.....#...##......\",\n \".......#.........#...#..#......\",\n \".##..#.........#....#.#........\",\n \"....##...#.#...........#....#..\",\n \".........................##....\",\n \"..###.......##....#.#.........#\",\n \".#....#.#.#...........##....#..\",\n \"......#...#..#..#..#..#.......#\",\n \"..#....#.#.......#..#..#..#...#\",\n \".....##...#.##....#.#...#......\",\n \".........#..#....#..#..........\",\n \".##..##.........#.#.....#......\",\n \"..........#...##...#.#...#.....\",\n \"#.##..#..#.............#.......\",\n \"...#...........#.......#......#\",\n \".......#....#....#...##.......#\",\n \"..#.##........###..#......#....\",\n \"...#...........###......#..#..#\",\n \".#.........#.#.........#.#.....\",\n \"##.......##.##.##......##......\",\n \"............#...#..........#...\",\n \"....................#..........\",\n \"...#..#...........#...#...#....\",\n \".................#...#......###\",\n \"...#................#.#.##.....\",\n \"...............#........#......\",\n \"#.............##......#.#..#...\",\n \"..#.#.....#..#.##.....##...#...\",\n \"......#.........#......#.......\",\n \"#.......#......#....#........#.\",\n \".#..##.....#.........#.........\",\n \"....##.##.#...#.........##.#...\",\n \"...............#..#..#..##.....\",\n \".#..#...............###........\",\n \".##............##..............\",\n \"...............#...##...#...#.#\",\n \"..#.#......#.#..#.............#\",\n \"#.#..#..##.........#.#.#...#...\",\n \"....##.#....................##.\",\n \".........#..#.....#.....#..#..#\",\n \"....#......#......#.##....#....\",\n \"........###..#.............#..#\",\n \"##................#.........#..\",\n \"#.....#.......#....#...........\",\n \"..#.......#..#........#....#...\",\n \"..#.#.##..#.#...##........#.##.\",\n \"..#..........#............#....\",\n \"..........#...............##...\",\n \"..........###........#.#.......\",\n \".....###..#.............#......\",\n \"##.............#...#.....#.....\",\n \".....#......#....#........#.#..\",\n \"............#..#..............#\",\n \".................#...........##\",\n \"#........#.........###.....#...\",\n \"..#.#..............##......#.#.\",\n \".#...........#.........#..##..#\",\n \"...............................\",\n \".#.....#..#....#....#......#...\",\n \".#...#......#.#..#....#.......#\",\n \"......#.##.......#......#......\",\n \"......#..###..#................\",\n \"#..#.....#........##...#.......\",\n \"......##.........##....#...##..\",\n \".#..........#.................#\",\n \"#..#.......#...............#...\",\n \".........#..###....#.#.##.#....\",\n \"..#...#.##..##...............##\",\n \".........#.....................\",\n \".#....##...#......#....#.......\",\n \"............#..........#..#....\",\n \"...#......##....#....#........#\",\n \".#...................#.........\",\n \"#.#........###....#..........#.\",\n \".........#....#....#........##.\",\n \".#....#..#.........#..#........\",\n \"...............#..#...#..#...##\",\n \".........#....##....#......#...\",\n \".#.............................\",\n \"...#........#...#.#...#.#..#...\",\n \".....#..##...#.#...............\",\n \"#.....#....#.........#.........\",\n \"#...#...........##.........#...\",\n \"..##........#.#...#...#......#.\",\n \"...........#.....#...#.#.......\",\n \"......###....#.....#...........\",\n \"......##...#..........#....#.#.\",\n \".......##..##..........#.......\",\n \"....#............#..#....##....\",\n \"..##...................#.#.....\",\n \"...#.#..#.#....................\",\n \".#..##..#............##.###..#.\",\n \"#.#...#....#.#..........#.#....\",\n \"........#....#.....#...........\",\n \"..##....#...#.......#..........\",\n \"...........##.##....#..........\",\n \".....#............#............\",\n \".......#.............#....#....\",\n \".................#......#......\",\n \"......##.......#....#..##...#..\",\n \".#..#....#.....................\",\n \"...#.#.#...#......##...........\",\n \"##........##.#....#....#.......\",\n \".......#.....#..#..#...#.##....\",\n \"#..........#....#.#..#..#..#...\",\n \"...##..............#...........\",\n \".........#.....#.#....#.......#\",\n \".........#....##..#..##..#.....\",\n \".....#......................#..\",\n \"...###...#..#......#...........\",\n \"....#.....................#....\",\n \"...............................\",\n \"..#.....###.......#..#....#....\",\n \"#..........#.................#.\",\n \"......#.......###.......#..##..\",\n \".............#.##..............\",\n \"......#..#.#..#...........#....\",\n \"...#....##.#...#..#.#...#....#.\",\n \"..................#...#....#.##\",\n \"......#.#....#.................\",\n \"......#.#.....#.....#..##......\",\n \"#..##...........#..#.....#.##..\",\n]\n\ndef treeCounter(moveRight, moveDown):\n\n row = 0\n index = 0\n trees = 0\n\n finished = False\n\n while not finished:\n\n row += moveDown\n if len(data) > row:\n index = (index + moveRight) % len(data[row])\n if data[row][index] == '#':\n trees += 1\n else:\n finished = True\n\n print(trees)\n\n\ntreeCounter(1,1)\ntreeCounter(3,1)\ntreeCounter(5,1)\ntreeCounter(7,1)\ntreeCounter(1,2)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import turtle
def draw_square():
conrad = turtle.Turtle()
conrad.shape("turtle")
conrad.color("red")
conrad.speed(3)
i = 0
while(i < 4):
conrad.forward(200)
conrad.right(90)
i += 1
def draw_circle():
niki = turtle.Turtle()
niki.circle(50)
def draw_triangle():
tri = turtle.Turtle()
tri.shape("turtle")
i = 0
while(i < 3):
tri.forward(135)
tri.right(145)
i += 1
def main():
window = turtle.Screen()
window.bgcolor("blue")
draw_square()
draw_circle()
draw_triangle()
window.exitonclick()
main()
|
normal
|
{
"blob_id": "9a982e0ab7fff882767a98ed01f5ed68bd710888",
"index": 7433,
"step-1": "<mask token>\n\n\ndef draw_circle():\n niki = turtle.Turtle()\n niki.circle(50)\n\n\ndef draw_triangle():\n tri = turtle.Turtle()\n tri.shape('turtle')\n i = 0\n while i < 3:\n tri.forward(135)\n tri.right(145)\n i += 1\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef draw_square():\n conrad = turtle.Turtle()\n conrad.shape('turtle')\n conrad.color('red')\n conrad.speed(3)\n i = 0\n while i < 4:\n conrad.forward(200)\n conrad.right(90)\n i += 1\n\n\ndef draw_circle():\n niki = turtle.Turtle()\n niki.circle(50)\n\n\ndef draw_triangle():\n tri = turtle.Turtle()\n tri.shape('turtle')\n i = 0\n while i < 3:\n tri.forward(135)\n tri.right(145)\n i += 1\n\n\ndef main():\n window = turtle.Screen()\n window.bgcolor('blue')\n draw_square()\n draw_circle()\n draw_triangle()\n window.exitonclick()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef draw_square():\n conrad = turtle.Turtle()\n conrad.shape('turtle')\n conrad.color('red')\n conrad.speed(3)\n i = 0\n while i < 4:\n conrad.forward(200)\n conrad.right(90)\n i += 1\n\n\ndef draw_circle():\n niki = turtle.Turtle()\n niki.circle(50)\n\n\ndef draw_triangle():\n tri = turtle.Turtle()\n tri.shape('turtle')\n i = 0\n while i < 3:\n tri.forward(135)\n tri.right(145)\n i += 1\n\n\ndef main():\n window = turtle.Screen()\n window.bgcolor('blue')\n draw_square()\n draw_circle()\n draw_triangle()\n window.exitonclick()\n\n\nmain()\n",
"step-4": "import turtle\n\n\ndef draw_square():\n conrad = turtle.Turtle()\n conrad.shape('turtle')\n conrad.color('red')\n conrad.speed(3)\n i = 0\n while i < 4:\n conrad.forward(200)\n conrad.right(90)\n i += 1\n\n\ndef draw_circle():\n niki = turtle.Turtle()\n niki.circle(50)\n\n\ndef draw_triangle():\n tri = turtle.Turtle()\n tri.shape('turtle')\n i = 0\n while i < 3:\n tri.forward(135)\n tri.right(145)\n i += 1\n\n\ndef main():\n window = turtle.Screen()\n window.bgcolor('blue')\n draw_square()\n draw_circle()\n draw_triangle()\n window.exitonclick()\n\n\nmain()\n",
"step-5": "import turtle\n\ndef draw_square():\n\t\n\tconrad = turtle.Turtle()\n\tconrad.shape(\"turtle\")\n\tconrad.color(\"red\")\n\tconrad.speed(3)\n\n\ti = 0\n\twhile(i < 4):\n\t\tconrad.forward(200)\n\t\tconrad.right(90)\n\t\ti += 1\n\ndef draw_circle():\n\t\n\tniki = turtle.Turtle()\n\tniki.circle(50)\n\ndef draw_triangle():\n\t\n\ttri = turtle.Turtle()\n\ttri.shape(\"turtle\")\n\n\ti = 0\n\twhile(i < 3):\n\t\ttri.forward(135)\n\t\ttri.right(145)\n\t\ti += 1\n\ndef main():\n\twindow = turtle.Screen()\n\twindow.bgcolor(\"blue\")\n\t\n\tdraw_square()\n\tdraw_circle()\n\tdraw_triangle()\n\twindow.exitonclick()\n\nmain()",
"step-ids": [
2,
4,
5,
6,
7
]
}
|
[
2,
4,
5,
6,
7
] |
from board.ttt import TTT
from mctsai.mcts import MCTS
import unittest
# skip = [0, 1]
skip = [0]
class TestTTT(unittest.TestCase):
def test_mcts(self):
if 0 in skip:
print("Skipping ai self-play")
return
ttt = TTT()
for i in range(1000):
mcts = MCTS(ttt)
state = mcts.root.state
while not mcts.board.ending_state(state):
move = mcts.search()
print(move)
state = mcts.board.get_state(state, move)
mcts.board.print(state)
mcts.make_move(move)
self.assertEqual(mcts.board.ending_state(state), -1)
def test_play_mcts(self):
if 1 in skip:
print("Skipping human-ai play")
return
ttt = TTT()
mcts = MCTS(ttt)
state = mcts.root.state
my_player = 2
while not mcts.board.ending_state(state):
mcts.board.print(state)
move = mcts.search()
print(move)
if state[1] == my_player:
move = input("Make move!\n")
move = (int(move[0]), int(move[1]))
mcts.make_move(move)
state = mcts.root.state
mcts.board.print(state)
# state = mcts.board.get_state(state, move)
# mcts = MCTS(ttt)
# mcts.root.state = state
# mcts.root.remaining_moves = mcts.board.get_legal_moves(mcts.root.state)
def test_positions(self):
# simple block
move_sequence = [(1, 1), (2, 0), (0, 1)]
# self.from_position(move_sequence, (2, 1), "Simple block 1")
# simple block 2
move_sequence = [(1, 1), (2, 2), (2, 1)]
# self.from_position(move_sequence, (0, 1), "Simple block 2")
# simple win 1
move_sequence = [(1, 1), (2, 2), (2, 0), (0, 2), (1, 2), (2, 1)]
# self.from_position(move_sequence, (1, 0), "Simple win")
def from_position(self, move_sequence, expected_move, name):
ttt = TTT()
mcts = MCTS(ttt, searchtime= 30)
mcts.board.print(mcts.root.state)
for move in move_sequence:
mcts.search()
mcts.make_move(move)
mcts.board.print(mcts.root.state)
move = mcts.search()
print("Testing {} block (that was lost before) on the following board".format(name))
self.assertEqual(move, expected_move)
def test_trick_win(self):
pass
# ttt = TTT()
# state = ttt.get_initial_state()
# state = ttt.get_state(state, (1, 1))
# state = ttt.get_state(state, (2, 2))
# state = ttt.get_state(state, (2, 0))
# print("Testing trick win on the following board")
# ttt.print(state)
# for _ in range(100):
# mcts = MCTS(ttt)
# mcts.set_root_state(state)
# move = mcts.search()
# self.assertEqual(move, (0, 2))
def test_defend_trick_win(self):
pass
|
normal
|
{
"blob_id": "d0a3f332e04627eb275168972bd92cd1ea9b9447",
"index": 227,
"step-1": "<mask token>\n\n\nclass TestTTT(unittest.TestCase):\n\n def test_mcts(self):\n if 0 in skip:\n print('Skipping ai self-play')\n return\n ttt = TTT()\n for i in range(1000):\n mcts = MCTS(ttt)\n state = mcts.root.state\n while not mcts.board.ending_state(state):\n move = mcts.search()\n print(move)\n state = mcts.board.get_state(state, move)\n mcts.board.print(state)\n mcts.make_move(move)\n self.assertEqual(mcts.board.ending_state(state), -1)\n\n def test_play_mcts(self):\n if 1 in skip:\n print('Skipping human-ai play')\n return\n ttt = TTT()\n mcts = MCTS(ttt)\n state = mcts.root.state\n my_player = 2\n while not mcts.board.ending_state(state):\n mcts.board.print(state)\n move = mcts.search()\n print(move)\n if state[1] == my_player:\n move = input('Make move!\\n')\n move = int(move[0]), int(move[1])\n mcts.make_move(move)\n state = mcts.root.state\n mcts.board.print(state)\n <mask token>\n <mask token>\n\n def test_trick_win(self):\n pass\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestTTT(unittest.TestCase):\n\n def test_mcts(self):\n if 0 in skip:\n print('Skipping ai self-play')\n return\n ttt = TTT()\n for i in range(1000):\n mcts = MCTS(ttt)\n state = mcts.root.state\n while not mcts.board.ending_state(state):\n move = mcts.search()\n print(move)\n state = mcts.board.get_state(state, move)\n mcts.board.print(state)\n mcts.make_move(move)\n self.assertEqual(mcts.board.ending_state(state), -1)\n\n def test_play_mcts(self):\n if 1 in skip:\n print('Skipping human-ai play')\n return\n ttt = TTT()\n mcts = MCTS(ttt)\n state = mcts.root.state\n my_player = 2\n while not mcts.board.ending_state(state):\n mcts.board.print(state)\n move = mcts.search()\n print(move)\n if state[1] == my_player:\n move = input('Make move!\\n')\n move = int(move[0]), int(move[1])\n mcts.make_move(move)\n state = mcts.root.state\n mcts.board.print(state)\n\n def test_positions(self):\n move_sequence = [(1, 1), (2, 0), (0, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 0), (0, 2), (1, 2), (2, 1)]\n\n def from_position(self, move_sequence, expected_move, name):\n ttt = TTT()\n mcts = MCTS(ttt, searchtime=30)\n mcts.board.print(mcts.root.state)\n for move in move_sequence:\n mcts.search()\n mcts.make_move(move)\n mcts.board.print(mcts.root.state)\n move = mcts.search()\n print('Testing {} block (that was lost before) on the following board'\n .format(name))\n self.assertEqual(move, expected_move)\n\n def test_trick_win(self):\n pass\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TestTTT(unittest.TestCase):\n\n def test_mcts(self):\n if 0 in skip:\n print('Skipping ai self-play')\n return\n ttt = TTT()\n for i in range(1000):\n mcts = MCTS(ttt)\n state = mcts.root.state\n while not mcts.board.ending_state(state):\n move = mcts.search()\n print(move)\n state = mcts.board.get_state(state, move)\n mcts.board.print(state)\n mcts.make_move(move)\n self.assertEqual(mcts.board.ending_state(state), -1)\n\n def test_play_mcts(self):\n if 1 in skip:\n print('Skipping human-ai play')\n return\n ttt = TTT()\n mcts = MCTS(ttt)\n state = mcts.root.state\n my_player = 2\n while not mcts.board.ending_state(state):\n mcts.board.print(state)\n move = mcts.search()\n print(move)\n if state[1] == my_player:\n move = input('Make move!\\n')\n move = int(move[0]), int(move[1])\n mcts.make_move(move)\n state = mcts.root.state\n mcts.board.print(state)\n\n def test_positions(self):\n move_sequence = [(1, 1), (2, 0), (0, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 0), (0, 2), (1, 2), (2, 1)]\n\n def from_position(self, move_sequence, expected_move, name):\n ttt = TTT()\n mcts = MCTS(ttt, searchtime=30)\n mcts.board.print(mcts.root.state)\n for move in move_sequence:\n mcts.search()\n mcts.make_move(move)\n mcts.board.print(mcts.root.state)\n move = mcts.search()\n print('Testing {} block (that was lost before) on the following board'\n .format(name))\n self.assertEqual(move, expected_move)\n\n def test_trick_win(self):\n pass\n\n def test_defend_trick_win(self):\n pass\n",
"step-4": "<mask token>\nskip = [0]\n\n\nclass TestTTT(unittest.TestCase):\n\n def test_mcts(self):\n if 0 in skip:\n print('Skipping ai self-play')\n return\n ttt = TTT()\n for i in range(1000):\n mcts = MCTS(ttt)\n state = mcts.root.state\n while not mcts.board.ending_state(state):\n move = mcts.search()\n print(move)\n state = mcts.board.get_state(state, move)\n mcts.board.print(state)\n mcts.make_move(move)\n self.assertEqual(mcts.board.ending_state(state), -1)\n\n def test_play_mcts(self):\n if 1 in skip:\n print('Skipping human-ai play')\n return\n ttt = TTT()\n mcts = MCTS(ttt)\n state = mcts.root.state\n my_player = 2\n while not mcts.board.ending_state(state):\n mcts.board.print(state)\n move = mcts.search()\n print(move)\n if state[1] == my_player:\n move = input('Make move!\\n')\n move = int(move[0]), int(move[1])\n mcts.make_move(move)\n state = mcts.root.state\n mcts.board.print(state)\n\n def test_positions(self):\n move_sequence = [(1, 1), (2, 0), (0, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 1)]\n move_sequence = [(1, 1), (2, 2), (2, 0), (0, 2), (1, 2), (2, 1)]\n\n def from_position(self, move_sequence, expected_move, name):\n ttt = TTT()\n mcts = MCTS(ttt, searchtime=30)\n mcts.board.print(mcts.root.state)\n for move in move_sequence:\n mcts.search()\n mcts.make_move(move)\n mcts.board.print(mcts.root.state)\n move = mcts.search()\n print('Testing {} block (that was lost before) on the following board'\n .format(name))\n self.assertEqual(move, expected_move)\n\n def test_trick_win(self):\n pass\n\n def test_defend_trick_win(self):\n pass\n",
"step-5": "from board.ttt import TTT\nfrom mctsai.mcts import MCTS\nimport unittest\n\n# skip = [0, 1]\n\nskip = [0]\n\nclass TestTTT(unittest.TestCase):\n def test_mcts(self):\n if 0 in skip:\n print(\"Skipping ai self-play\")\n return\n ttt = TTT()\n for i in range(1000):\n mcts = MCTS(ttt)\n state = mcts.root.state\n while not mcts.board.ending_state(state):\n move = mcts.search()\n print(move)\n state = mcts.board.get_state(state, move)\n mcts.board.print(state)\n mcts.make_move(move)\n self.assertEqual(mcts.board.ending_state(state), -1)\n\n def test_play_mcts(self):\n if 1 in skip:\n print(\"Skipping human-ai play\")\n return\n\n ttt = TTT()\n mcts = MCTS(ttt)\n state = mcts.root.state\n my_player = 2\n while not mcts.board.ending_state(state):\n mcts.board.print(state)\n move = mcts.search()\n print(move)\n if state[1] == my_player:\n move = input(\"Make move!\\n\")\n move = (int(move[0]), int(move[1]))\n\n mcts.make_move(move)\n state = mcts.root.state\n mcts.board.print(state)\n # state = mcts.board.get_state(state, move)\n # mcts = MCTS(ttt)\n # mcts.root.state = state\n # mcts.root.remaining_moves = mcts.board.get_legal_moves(mcts.root.state)\n\n def test_positions(self):\n # simple block\n move_sequence = [(1, 1), (2, 0), (0, 1)]\n # self.from_position(move_sequence, (2, 1), \"Simple block 1\")\n\n # simple block 2\n move_sequence = [(1, 1), (2, 2), (2, 1)]\n # self.from_position(move_sequence, (0, 1), \"Simple block 2\")\n\n # simple win 1\n move_sequence = [(1, 1), (2, 2), (2, 0), (0, 2), (1, 2), (2, 1)]\n # self.from_position(move_sequence, (1, 0), \"Simple win\")\n\n def from_position(self, move_sequence, expected_move, name):\n ttt = TTT()\n mcts = MCTS(ttt, searchtime= 30)\n mcts.board.print(mcts.root.state)\n for move in move_sequence:\n mcts.search()\n mcts.make_move(move)\n mcts.board.print(mcts.root.state)\n\n move = mcts.search()\n\n print(\"Testing {} block (that was lost before) on the following board\".format(name))\n self.assertEqual(move, expected_move)\n\n def test_trick_win(self):\n pass\n # ttt = TTT()\n # state = ttt.get_initial_state()\n # state = ttt.get_state(state, (1, 1))\n # state = ttt.get_state(state, (2, 2))\n # state = ttt.get_state(state, (2, 0))\n # print(\"Testing trick win on the following board\")\n # ttt.print(state)\n # for _ in range(100):\n # mcts = MCTS(ttt)\n # mcts.set_root_state(state)\n # move = mcts.search()\n # self.assertEqual(move, (0, 2))\n\n def test_defend_trick_win(self):\n pass\n\n\n\n\n\n\n",
"step-ids": [
4,
6,
7,
8,
10
]
}
|
[
4,
6,
7,
8,
10
] |
import os
import shutil
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-D', '--dir', required=False, help='Directory to sort')
args = vars(ap.parse_args())
if args['dir'] == None:
DIR = os.getcwd()
elif os.path.exists(args['dir']):
DIR = args['dir']
for file in os.listdir(DIR):
if not os.path.isdir(os.path.join(DIR, file)):
name, ext = os.path.splitext(file)
ext = ext[::-1][:-1][::-1]
if os.path.exists(os.path.join(DIR, ext.upper())):
shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.
upper(), file))
else:
os.mkdir(os.path.join(DIR, ext.upper()))
shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.
upper(), file))
|
normal
|
{
"blob_id": "93737e4c409d0efb1ae2263cb60d4b03d9aad0d8",
"index": 247,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\n<mask token>\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n",
"step-3": "<mask token>\nap = argparse.ArgumentParser()\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\nargs = vars(ap.parse_args())\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n",
"step-4": "import os\nimport shutil\nimport argparse\nap = argparse.ArgumentParser()\nap.add_argument('-D', '--dir', required=False, help='Directory to sort')\nargs = vars(ap.parse_args())\nif args['dir'] == None:\n DIR = os.getcwd()\nelif os.path.exists(args['dir']):\n DIR = args['dir']\nfor file in os.listdir(DIR):\n if not os.path.isdir(os.path.join(DIR, file)):\n name, ext = os.path.splitext(file)\n ext = ext[::-1][:-1][::-1]\n if os.path.exists(os.path.join(DIR, ext.upper())):\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n else:\n os.mkdir(os.path.join(DIR, ext.upper()))\n shutil.move(os.path.join(DIR, file), os.path.join(DIR, ext.\n upper(), file))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
PROFILE_PIC_PATH = 'users/profile_pic'
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
image = models.ImageField(null=True, blank=True, upload_to=PROFILE_PIC_PATH
)
birth_date = models.DateField(null=True, blank=True)
|
normal
|
{
"blob_id": "3e7df9a733c94b89d22d10883844c438444d5e2c",
"index": 8010,
"step-1": "<mask token>\n\n\nclass Profile(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n bio = models.TextField(max_length=500, blank=True)\n image = models.ImageField(null=True, blank=True, upload_to=PROFILE_PIC_PATH\n )\n birth_date = models.DateField(null=True, blank=True)\n",
"step-3": "<mask token>\nPROFILE_PIC_PATH = 'users/profile_pic'\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n bio = models.TextField(max_length=500, blank=True)\n image = models.ImageField(null=True, blank=True, upload_to=PROFILE_PIC_PATH\n )\n birth_date = models.DateField(null=True, blank=True)\n",
"step-4": "from __future__ import unicode_literals\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import User\nfrom django.dispatch import receiver\nPROFILE_PIC_PATH = 'users/profile_pic'\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n bio = models.TextField(max_length=500, blank=True)\n image = models.ImageField(null=True, blank=True, upload_to=PROFILE_PIC_PATH\n )\n birth_date = models.DateField(null=True, blank=True)\n",
"step-5": null,
"step-ids": [
1,
2,
3,
4
]
}
|
[
1,
2,
3,
4
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
from espeak import espeak
except ImportError:
class espeak():
@classmethod
def synth(*args):
print('Cannot generate speech. Please, install python3-espeak module.')
return 1
def run(*args, **kwargs):
text = ' '.join(map(str, args))
espeak.synth(text)
|
normal
|
{
"blob_id": "cd5929496b13dd0d5f5ca97500c5bb3572907cc5",
"index": 2769,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run(*args, **kwargs):\n text = ' '.join(map(str, args))\n espeak.synth(text)\n",
"step-3": "try:\n from espeak import espeak\nexcept ImportError:\n\n\n class espeak:\n\n @classmethod\n def synth(*args):\n print(\n 'Cannot generate speech. Please, install python3-espeak module.'\n )\n return 1\n\n\ndef run(*args, **kwargs):\n text = ' '.join(map(str, args))\n espeak.synth(text)\n",
"step-4": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ntry:\n from espeak import espeak\nexcept ImportError:\n class espeak():\n @classmethod\n def synth(*args):\n print('Cannot generate speech. Please, install python3-espeak module.')\n return 1\n\n\ndef run(*args, **kwargs):\n text = ' '.join(map(str, args))\n espeak.synth(text)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# -*- coding: utf8 -*-
from django.db import models
import custom_fields
import datetime
#import mptt
# Create your models here.
class Message(models.Model):
user = models.ForeignKey('User')
time = models.DateTimeField(auto_now=True,auto_now_add=True)
text = models.TextField()
#true если это ответ поддержки
reply = models.BooleanField(default=False)
ticket = models.ForeignKey('Ticket')
ip = models.IPAddressField(blank=True,null=True)
class User(models.Model):
name = models.CharField("Имя",max_length=60)
email = models.EmailField(blank=True,null=True)
phone = models.CharField("Внутр. телефон",max_length=30,blank=True,null=True)
mobile = models.CharField("Корп. мобильный",max_length=30,blank=True,null=True)
city_phone = models.CharField("Городской телефон",max_length=30,blank=True,null=True)
sat_phone = models.CharField("Спутниковый телефон",max_length=30,blank=True,null=True)
personal_phone = models.CharField("Личный телефон",max_length=30,blank=True,null=True)
admin = models.BooleanField(default=False)
login = models.CharField(max_length=16,blank=True,null=True)
password = models.CharField(max_length=32,blank=True,null=True)
place = models.ForeignKey('Place',blank=True,null=True)
class Device(models.Model):
TYPE_CHOICES=(
('00','Компьютер'),
('10','Монитор'),
('20','Принтер'),
('30','МФУ'),
('40','Плоттер'),
('50','Сканер'),
('60','Сервер'),
('70','Маршрутизатор'),
('80','Модем'),
)
type=models.CharField(max_length=3,choices=TYPE_CHOICES)
inv_no=models.CharField(max_length=40)
ip=models.IPAddressField(blank=True,null=True)
model=models.CharField(max_length=60,blank=True,null=True)
mac=custom_fields.MACAddressField(blank=True,null=True)
info=models.TextField(blank=True,null=True)
place = models.ForeignKey('Place')
hostname=models.CharField(blank=True,null=True,max_length=40)
def type_display(self):
for desc in self.TYPE_CHOICES:
if desc[0]==self.type:
return desc[1]
def get_absolute_url(self):
return "/place/"+str(self.place.id)
class Ticket(models.Model):
#NEW,OPEN,CLOSED,DELETED
STATUS_CHOICES=(
('00','Новое'),
('10','Принято'),
('20','Ожидаем ответ'),
('30','Закрыто'),
('40','Удалено'),
)
PRIO_CHOICES=(
('00','Крайне срочно'),
('10','Срочно'),
('20','Обычно'),
('30','Длительное')
)
CATEGORY_CHOICES=(
('00','Компьютеры, локальный софт, железо'),
('10','Печать, принтеры, расходники'),
('20','Корпоративные системы (SAP,АСУД ..)'),
('30','Сетевые сервисы и оборуд., Серверы'),
('40','СКС (провода, розетки)'),
)
status = models.CharField("Статус",max_length=3, choices=STATUS_CHOICES)
priority = models.CharField("Приоритет",max_length=3, choices=PRIO_CHOICES)
category = models.CharField("Категория",max_length=3, choices=CATEGORY_CHOICES,blank=True,null=True)
hours_limit=models.DecimalField("Лимит времени, ч.",max_digits=4, decimal_places=1,default=2)
#Описание проблемы. при создании тикета - присваиваем текст 1го обращения
#В процессе выполнения заявки можем менять
description = models.TextField("Описание проблемы")
#Описание решения по закрытии заявки
resume = models.TextField("Отчёт о решении",blank=True,null=True)
user = models.ForeignKey(User,related_name="tickets")
admin = models.ForeignKey(User,related_name="tasks",blank=True,null=True)
device = models.ForeignKey(Device,blank=True,null=True)
#Время создания.
ctime = models.DateTimeField(auto_now_add = True)
#Время закрытия
closing_time = models.DateTimeField(blank=True,null=True)
def get_short_text(self):
return self.description[:120]
def hours_from_now(self):
delta=datetime.datetime.now()-self.ctime
return round(delta.days*24.0+delta.seconds/3600.0,1)
def is_new(self,*args):
value=self.status
if args:
value=args[0]
if value=='00':
return True
else:
return False
def is_closed(self,*args):
value=self.status
if args:
value=args[0]
if value=='30':
return True
else:
return False
def accept_by(self,user):
self.admin=user
def no(self):
return '{0:0>5}'.format(self.id)
class Place(models.Model):
name = models.CharField(max_length=60)
parent = models.ForeignKey('self',null=True, blank=True )
address = models.CharField(max_length=70)
LEVEL_DESC=(
(1,"Населённый пункт"),
(2,"Территория, группа зданий"),
(3,"Здание"),
(4,"Этаж"),
(5,"Кабинет/помещение"),
(6,"Место/комплекс"),
)
def childs(self):
return Place.objects.filter(parent=self)
def get_level(self):
res=0
try:
if self.parent!=None:
o=self
while (o.parent !=None):
res+=1
o=o.parent
except:
None
return res
def level_display(self):
level=self.get_level()
for desc in self.LEVEL_DESC:
if desc[0]==level:
return desc[1]
def path(self):
path=[]
o=self
while (o.parent != None):
path.insert(0,o)
o=o.parent
path.insert(0,o)
return path
def get_absolute_url(self):
return '/place/'+str(self.id)
def __unicode__(self):
return self.name
def users(self):
return User.objects.filter(place=self)
#mptt.register(Place)
class Document(models.Model):
name=models.CharField(max_length=60)
place=models.ForeignKey(Place,blank=True,null=True)
def latest_file(self):
return DocFile.objects.filter(document=self).order_by('-id')[0]
class DocFile(models.Model):
document=models.ForeignKey(Document)
version=models.IntegerField()
file_name=models.CharField(max_length=60)
comment=models.CharField(max_length=90,blank=True,null=True)
ctime = models.DateTimeField()
user = models.ForeignKey(User)
|
normal
|
{
"blob_id": "64fd597918fe8133d53d1df741512cd2e49a111d",
"index": 1252,
"step-1": "<mask token>\n\n\nclass Ticket(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def get_short_text(self):\n return self.description[:120]\n\n def hours_from_now(self):\n delta = datetime.datetime.now() - self.ctime\n return round(delta.days * 24.0 + delta.seconds / 3600.0, 1)\n\n def is_new(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '00':\n return True\n else:\n return False\n <mask token>\n\n def accept_by(self, user):\n self.admin = user\n\n def no(self):\n return '{0:0>5}'.format(self.id)\n\n\nclass Place(models.Model):\n name = models.CharField(max_length=60)\n parent = models.ForeignKey('self', null=True, blank=True)\n address = models.CharField(max_length=70)\n LEVEL_DESC = (1, 'Населённый пункт'), (2, 'Территория, группа зданий'), (\n 3, 'Здание'), (4, 'Этаж'), (5, 'Кабинет/помещение'), (6,\n 'Место/комплекс')\n\n def childs(self):\n return Place.objects.filter(parent=self)\n\n def get_level(self):\n res = 0\n try:\n if self.parent != None:\n o = self\n while o.parent != None:\n res += 1\n o = o.parent\n except:\n None\n return res\n\n def level_display(self):\n level = self.get_level()\n for desc in self.LEVEL_DESC:\n if desc[0] == level:\n return desc[1]\n\n def path(self):\n path = []\n o = self\n while o.parent != None:\n path.insert(0, o)\n o = o.parent\n path.insert(0, o)\n return path\n\n def get_absolute_url(self):\n return '/place/' + str(self.id)\n\n def __unicode__(self):\n return self.name\n\n def users(self):\n return User.objects.filter(place=self)\n\n\nclass Document(models.Model):\n name = models.CharField(max_length=60)\n place = models.ForeignKey(Place, blank=True, null=True)\n\n def latest_file(self):\n return DocFile.objects.filter(document=self).order_by('-id')[0]\n\n\nclass DocFile(models.Model):\n document = models.ForeignKey(Document)\n version = models.IntegerField()\n file_name = models.CharField(max_length=60)\n comment = models.CharField(max_length=90, blank=True, null=True)\n ctime = models.DateTimeField()\n user = models.ForeignKey(User)\n",
"step-2": "<mask token>\n\n\nclass Ticket(models.Model):\n STATUS_CHOICES = ('00', 'Новое'), ('10', 'Принято'), ('20', 'Ожидаем ответ'\n ), ('30', 'Закрыто'), ('40', 'Удалено')\n PRIO_CHOICES = ('00', 'Крайне срочно'), ('10', 'Срочно'), ('20', 'Обычно'\n ), ('30', 'Длительное')\n CATEGORY_CHOICES = ('00', 'Компьютеры, локальный софт, железо'), ('10',\n 'Печать, принтеры, расходники'), ('20',\n 'Корпоративные системы (SAP,АСУД ..)'), ('30',\n 'Сетевые сервисы и оборуд., Серверы'), ('40', 'СКС (провода, розетки)')\n status = models.CharField('Статус', max_length=3, choices=STATUS_CHOICES)\n priority = models.CharField('Приоритет', max_length=3, choices=PRIO_CHOICES\n )\n category = models.CharField('Категория', max_length=3, choices=\n CATEGORY_CHOICES, blank=True, null=True)\n hours_limit = models.DecimalField('Лимит времени, ч.', max_digits=4,\n decimal_places=1, default=2)\n description = models.TextField('Описание проблемы')\n resume = models.TextField('Отчёт о решении', blank=True, null=True)\n user = models.ForeignKey(User, related_name='tickets')\n admin = models.ForeignKey(User, related_name='tasks', blank=True, null=True\n )\n device = models.ForeignKey(Device, blank=True, null=True)\n ctime = models.DateTimeField(auto_now_add=True)\n closing_time = models.DateTimeField(blank=True, null=True)\n\n def get_short_text(self):\n return self.description[:120]\n\n def hours_from_now(self):\n delta = datetime.datetime.now() - self.ctime\n return round(delta.days * 24.0 + delta.seconds / 3600.0, 1)\n\n def is_new(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '00':\n return True\n else:\n return False\n\n def is_closed(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '30':\n return True\n else:\n return False\n\n def accept_by(self, user):\n self.admin = user\n\n def no(self):\n return '{0:0>5}'.format(self.id)\n\n\nclass Place(models.Model):\n name = models.CharField(max_length=60)\n parent = models.ForeignKey('self', null=True, blank=True)\n address = models.CharField(max_length=70)\n LEVEL_DESC = (1, 'Населённый пункт'), (2, 'Территория, группа зданий'), (\n 3, 'Здание'), (4, 'Этаж'), (5, 'Кабинет/помещение'), (6,\n 'Место/комплекс')\n\n def childs(self):\n return Place.objects.filter(parent=self)\n\n def get_level(self):\n res = 0\n try:\n if self.parent != None:\n o = self\n while o.parent != None:\n res += 1\n o = o.parent\n except:\n None\n return res\n\n def level_display(self):\n level = self.get_level()\n for desc in self.LEVEL_DESC:\n if desc[0] == level:\n return desc[1]\n\n def path(self):\n path = []\n o = self\n while o.parent != None:\n path.insert(0, o)\n o = o.parent\n path.insert(0, o)\n return path\n\n def get_absolute_url(self):\n return '/place/' + str(self.id)\n\n def __unicode__(self):\n return self.name\n\n def users(self):\n return User.objects.filter(place=self)\n\n\nclass Document(models.Model):\n name = models.CharField(max_length=60)\n place = models.ForeignKey(Place, blank=True, null=True)\n\n def latest_file(self):\n return DocFile.objects.filter(document=self).order_by('-id')[0]\n\n\nclass DocFile(models.Model):\n document = models.ForeignKey(Document)\n version = models.IntegerField()\n file_name = models.CharField(max_length=60)\n comment = models.CharField(max_length=90, blank=True, null=True)\n ctime = models.DateTimeField()\n user = models.ForeignKey(User)\n",
"step-3": "<mask token>\n\n\nclass User(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Device(models.Model):\n TYPE_CHOICES = ('00', 'Компьютер'), ('10', 'Монитор'), ('20', 'Принтер'), (\n '30', 'МФУ'), ('40', 'Плоттер'), ('50', 'Сканер'), ('60', 'Сервер'), (\n '70', 'Маршрутизатор'), ('80', 'Модем')\n type = models.CharField(max_length=3, choices=TYPE_CHOICES)\n inv_no = models.CharField(max_length=40)\n ip = models.IPAddressField(blank=True, null=True)\n model = models.CharField(max_length=60, blank=True, null=True)\n mac = custom_fields.MACAddressField(blank=True, null=True)\n info = models.TextField(blank=True, null=True)\n place = models.ForeignKey('Place')\n hostname = models.CharField(blank=True, null=True, max_length=40)\n\n def type_display(self):\n for desc in self.TYPE_CHOICES:\n if desc[0] == self.type:\n return desc[1]\n\n def get_absolute_url(self):\n return '/place/' + str(self.place.id)\n\n\nclass Ticket(models.Model):\n STATUS_CHOICES = ('00', 'Новое'), ('10', 'Принято'), ('20', 'Ожидаем ответ'\n ), ('30', 'Закрыто'), ('40', 'Удалено')\n PRIO_CHOICES = ('00', 'Крайне срочно'), ('10', 'Срочно'), ('20', 'Обычно'\n ), ('30', 'Длительное')\n CATEGORY_CHOICES = ('00', 'Компьютеры, локальный софт, железо'), ('10',\n 'Печать, принтеры, расходники'), ('20',\n 'Корпоративные системы (SAP,АСУД ..)'), ('30',\n 'Сетевые сервисы и оборуд., Серверы'), ('40', 'СКС (провода, розетки)')\n status = models.CharField('Статус', max_length=3, choices=STATUS_CHOICES)\n priority = models.CharField('Приоритет', max_length=3, choices=PRIO_CHOICES\n )\n category = models.CharField('Категория', max_length=3, choices=\n CATEGORY_CHOICES, blank=True, null=True)\n hours_limit = models.DecimalField('Лимит времени, ч.', max_digits=4,\n decimal_places=1, default=2)\n description = models.TextField('Описание проблемы')\n resume = models.TextField('Отчёт о решении', blank=True, null=True)\n user = models.ForeignKey(User, related_name='tickets')\n admin = models.ForeignKey(User, related_name='tasks', blank=True, null=True\n )\n device = models.ForeignKey(Device, blank=True, null=True)\n ctime = models.DateTimeField(auto_now_add=True)\n closing_time = models.DateTimeField(blank=True, null=True)\n\n def get_short_text(self):\n return self.description[:120]\n\n def hours_from_now(self):\n delta = datetime.datetime.now() - self.ctime\n return round(delta.days * 24.0 + delta.seconds / 3600.0, 1)\n\n def is_new(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '00':\n return True\n else:\n return False\n\n def is_closed(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '30':\n return True\n else:\n return False\n\n def accept_by(self, user):\n self.admin = user\n\n def no(self):\n return '{0:0>5}'.format(self.id)\n\n\nclass Place(models.Model):\n name = models.CharField(max_length=60)\n parent = models.ForeignKey('self', null=True, blank=True)\n address = models.CharField(max_length=70)\n LEVEL_DESC = (1, 'Населённый пункт'), (2, 'Территория, группа зданий'), (\n 3, 'Здание'), (4, 'Этаж'), (5, 'Кабинет/помещение'), (6,\n 'Место/комплекс')\n\n def childs(self):\n return Place.objects.filter(parent=self)\n\n def get_level(self):\n res = 0\n try:\n if self.parent != None:\n o = self\n while o.parent != None:\n res += 1\n o = o.parent\n except:\n None\n return res\n\n def level_display(self):\n level = self.get_level()\n for desc in self.LEVEL_DESC:\n if desc[0] == level:\n return desc[1]\n\n def path(self):\n path = []\n o = self\n while o.parent != None:\n path.insert(0, o)\n o = o.parent\n path.insert(0, o)\n return path\n\n def get_absolute_url(self):\n return '/place/' + str(self.id)\n\n def __unicode__(self):\n return self.name\n\n def users(self):\n return User.objects.filter(place=self)\n\n\nclass Document(models.Model):\n name = models.CharField(max_length=60)\n place = models.ForeignKey(Place, blank=True, null=True)\n\n def latest_file(self):\n return DocFile.objects.filter(document=self).order_by('-id')[0]\n\n\nclass DocFile(models.Model):\n document = models.ForeignKey(Document)\n version = models.IntegerField()\n file_name = models.CharField(max_length=60)\n comment = models.CharField(max_length=90, blank=True, null=True)\n ctime = models.DateTimeField()\n user = models.ForeignKey(User)\n",
"step-4": "<mask token>\n\n\nclass Message(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass User(models.Model):\n name = models.CharField('Имя', max_length=60)\n email = models.EmailField(blank=True, null=True)\n phone = models.CharField('Внутр. телефон', max_length=30, blank=True,\n null=True)\n mobile = models.CharField('Корп. мобильный', max_length=30, blank=True,\n null=True)\n city_phone = models.CharField('Городской телефон', max_length=30, blank\n =True, null=True)\n sat_phone = models.CharField('Спутниковый телефон', max_length=30,\n blank=True, null=True)\n personal_phone = models.CharField('Личный телефон', max_length=30,\n blank=True, null=True)\n admin = models.BooleanField(default=False)\n login = models.CharField(max_length=16, blank=True, null=True)\n password = models.CharField(max_length=32, blank=True, null=True)\n place = models.ForeignKey('Place', blank=True, null=True)\n\n\nclass Device(models.Model):\n TYPE_CHOICES = ('00', 'Компьютер'), ('10', 'Монитор'), ('20', 'Принтер'), (\n '30', 'МФУ'), ('40', 'Плоттер'), ('50', 'Сканер'), ('60', 'Сервер'), (\n '70', 'Маршрутизатор'), ('80', 'Модем')\n type = models.CharField(max_length=3, choices=TYPE_CHOICES)\n inv_no = models.CharField(max_length=40)\n ip = models.IPAddressField(blank=True, null=True)\n model = models.CharField(max_length=60, blank=True, null=True)\n mac = custom_fields.MACAddressField(blank=True, null=True)\n info = models.TextField(blank=True, null=True)\n place = models.ForeignKey('Place')\n hostname = models.CharField(blank=True, null=True, max_length=40)\n\n def type_display(self):\n for desc in self.TYPE_CHOICES:\n if desc[0] == self.type:\n return desc[1]\n\n def get_absolute_url(self):\n return '/place/' + str(self.place.id)\n\n\nclass Ticket(models.Model):\n STATUS_CHOICES = ('00', 'Новое'), ('10', 'Принято'), ('20', 'Ожидаем ответ'\n ), ('30', 'Закрыто'), ('40', 'Удалено')\n PRIO_CHOICES = ('00', 'Крайне срочно'), ('10', 'Срочно'), ('20', 'Обычно'\n ), ('30', 'Длительное')\n CATEGORY_CHOICES = ('00', 'Компьютеры, локальный софт, железо'), ('10',\n 'Печать, принтеры, расходники'), ('20',\n 'Корпоративные системы (SAP,АСУД ..)'), ('30',\n 'Сетевые сервисы и оборуд., Серверы'), ('40', 'СКС (провода, розетки)')\n status = models.CharField('Статус', max_length=3, choices=STATUS_CHOICES)\n priority = models.CharField('Приоритет', max_length=3, choices=PRIO_CHOICES\n )\n category = models.CharField('Категория', max_length=3, choices=\n CATEGORY_CHOICES, blank=True, null=True)\n hours_limit = models.DecimalField('Лимит времени, ч.', max_digits=4,\n decimal_places=1, default=2)\n description = models.TextField('Описание проблемы')\n resume = models.TextField('Отчёт о решении', blank=True, null=True)\n user = models.ForeignKey(User, related_name='tickets')\n admin = models.ForeignKey(User, related_name='tasks', blank=True, null=True\n )\n device = models.ForeignKey(Device, blank=True, null=True)\n ctime = models.DateTimeField(auto_now_add=True)\n closing_time = models.DateTimeField(blank=True, null=True)\n\n def get_short_text(self):\n return self.description[:120]\n\n def hours_from_now(self):\n delta = datetime.datetime.now() - self.ctime\n return round(delta.days * 24.0 + delta.seconds / 3600.0, 1)\n\n def is_new(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '00':\n return True\n else:\n return False\n\n def is_closed(self, *args):\n value = self.status\n if args:\n value = args[0]\n if value == '30':\n return True\n else:\n return False\n\n def accept_by(self, user):\n self.admin = user\n\n def no(self):\n return '{0:0>5}'.format(self.id)\n\n\nclass Place(models.Model):\n name = models.CharField(max_length=60)\n parent = models.ForeignKey('self', null=True, blank=True)\n address = models.CharField(max_length=70)\n LEVEL_DESC = (1, 'Населённый пункт'), (2, 'Территория, группа зданий'), (\n 3, 'Здание'), (4, 'Этаж'), (5, 'Кабинет/помещение'), (6,\n 'Место/комплекс')\n\n def childs(self):\n return Place.objects.filter(parent=self)\n\n def get_level(self):\n res = 0\n try:\n if self.parent != None:\n o = self\n while o.parent != None:\n res += 1\n o = o.parent\n except:\n None\n return res\n\n def level_display(self):\n level = self.get_level()\n for desc in self.LEVEL_DESC:\n if desc[0] == level:\n return desc[1]\n\n def path(self):\n path = []\n o = self\n while o.parent != None:\n path.insert(0, o)\n o = o.parent\n path.insert(0, o)\n return path\n\n def get_absolute_url(self):\n return '/place/' + str(self.id)\n\n def __unicode__(self):\n return self.name\n\n def users(self):\n return User.objects.filter(place=self)\n\n\nclass Document(models.Model):\n name = models.CharField(max_length=60)\n place = models.ForeignKey(Place, blank=True, null=True)\n\n def latest_file(self):\n return DocFile.objects.filter(document=self).order_by('-id')[0]\n\n\nclass DocFile(models.Model):\n document = models.ForeignKey(Document)\n version = models.IntegerField()\n file_name = models.CharField(max_length=60)\n comment = models.CharField(max_length=90, blank=True, null=True)\n ctime = models.DateTimeField()\n user = models.ForeignKey(User)\n",
"step-5": "# -*- coding: utf8 -*-\nfrom django.db import models\nimport custom_fields\nimport datetime\n#import mptt\n\n# Create your models here.\nclass Message(models.Model):\n user = models.ForeignKey('User')\n time = models.DateTimeField(auto_now=True,auto_now_add=True)\n text = models.TextField()\n #true если это ответ поддержки\n reply = models.BooleanField(default=False)\n ticket = models.ForeignKey('Ticket')\n ip = models.IPAddressField(blank=True,null=True)\n \n\nclass User(models.Model):\n name = models.CharField(\"Имя\",max_length=60)\n email = models.EmailField(blank=True,null=True)\n phone = models.CharField(\"Внутр. телефон\",max_length=30,blank=True,null=True)\n mobile = models.CharField(\"Корп. мобильный\",max_length=30,blank=True,null=True)\n city_phone = models.CharField(\"Городской телефон\",max_length=30,blank=True,null=True)\n sat_phone = models.CharField(\"Спутниковый телефон\",max_length=30,blank=True,null=True)\n personal_phone = models.CharField(\"Личный телефон\",max_length=30,blank=True,null=True)\n admin = models.BooleanField(default=False)\n login = models.CharField(max_length=16,blank=True,null=True)\n password = models.CharField(max_length=32,blank=True,null=True)\n place = models.ForeignKey('Place',blank=True,null=True)\n\nclass Device(models.Model):\n TYPE_CHOICES=(\n ('00','Компьютер'),\n ('10','Монитор'),\n ('20','Принтер'),\n ('30','МФУ'),\n ('40','Плоттер'),\n ('50','Сканер'),\n ('60','Сервер'),\n ('70','Маршрутизатор'),\n ('80','Модем'),\n )\n type=models.CharField(max_length=3,choices=TYPE_CHOICES)\n inv_no=models.CharField(max_length=40)\n ip=models.IPAddressField(blank=True,null=True)\n model=models.CharField(max_length=60,blank=True,null=True)\n mac=custom_fields.MACAddressField(blank=True,null=True)\n info=models.TextField(blank=True,null=True)\n place = models.ForeignKey('Place')\n hostname=models.CharField(blank=True,null=True,max_length=40)\n def type_display(self): \n for desc in self.TYPE_CHOICES:\n if desc[0]==self.type:\n return desc[1]\n def get_absolute_url(self):\n return \"/place/\"+str(self.place.id)\n\nclass Ticket(models.Model):\n #NEW,OPEN,CLOSED,DELETED\n STATUS_CHOICES=(\n ('00','Новое'),\n ('10','Принято'),\n ('20','Ожидаем ответ'),\n ('30','Закрыто'),\n ('40','Удалено'), \n )\n PRIO_CHOICES=(\n ('00','Крайне срочно'),\n ('10','Срочно'),\n ('20','Обычно'),\n ('30','Длительное')\n )\n\n CATEGORY_CHOICES=(\n ('00','Компьютеры, локальный софт, железо'),\n ('10','Печать, принтеры, расходники'),\n ('20','Корпоративные системы (SAP,АСУД ..)'),\n ('30','Сетевые сервисы и оборуд., Серверы'),\n ('40','СКС (провода, розетки)'),\n \n )\n\n status = models.CharField(\"Статус\",max_length=3, choices=STATUS_CHOICES)\n priority = models.CharField(\"Приоритет\",max_length=3, choices=PRIO_CHOICES)\n category = models.CharField(\"Категория\",max_length=3, choices=CATEGORY_CHOICES,blank=True,null=True)\n hours_limit=models.DecimalField(\"Лимит времени, ч.\",max_digits=4, decimal_places=1,default=2)\n #Описание проблемы. при создании тикета - присваиваем текст 1го обращения\n #В процессе выполнения заявки можем менять\n description = models.TextField(\"Описание проблемы\")\n #Описание решения по закрытии заявки\n resume = models.TextField(\"Отчёт о решении\",blank=True,null=True)\n user = models.ForeignKey(User,related_name=\"tickets\")\n admin = models.ForeignKey(User,related_name=\"tasks\",blank=True,null=True)\n device = models.ForeignKey(Device,blank=True,null=True) \n #Время создания. \n ctime = models.DateTimeField(auto_now_add = True)\n #Время закрытия\n closing_time = models.DateTimeField(blank=True,null=True)\n\n def get_short_text(self):\n return self.description[:120]\n \n def hours_from_now(self):\n delta=datetime.datetime.now()-self.ctime\n return round(delta.days*24.0+delta.seconds/3600.0,1)\n\n def is_new(self,*args):\n value=self.status\n if args:\n value=args[0]\n if value=='00':\n return True\n else:\n return False\n\n def is_closed(self,*args):\n value=self.status\n if args:\n value=args[0]\n if value=='30':\n return True\n else:\n return False\n \n def accept_by(self,user):\n self.admin=user\n \n def no(self):\n return '{0:0>5}'.format(self.id)\n \nclass Place(models.Model):\n name = models.CharField(max_length=60)\n parent = models.ForeignKey('self',null=True, blank=True )\n address = models.CharField(max_length=70)\n LEVEL_DESC=(\n (1,\"Населённый пункт\"),\n (2,\"Территория, группа зданий\"),\n (3,\"Здание\"),\n (4,\"Этаж\"),\n (5,\"Кабинет/помещение\"),\n (6,\"Место/комплекс\"),\n )\n def childs(self):\n return Place.objects.filter(parent=self)\n \n def get_level(self):\n res=0\n try:\n if self.parent!=None:\n o=self\n while (o.parent !=None):\n res+=1\n o=o.parent\n except:\n None\n return res\n \n def level_display(self):\n level=self.get_level()\n for desc in self.LEVEL_DESC:\n if desc[0]==level:\n return desc[1]\n \n def path(self): \n path=[]\n o=self\n while (o.parent != None):\n path.insert(0,o)\n o=o.parent\n path.insert(0,o)\n return path\n def get_absolute_url(self):\n return '/place/'+str(self.id)\n def __unicode__(self):\n return self.name\n \n def users(self):\n return User.objects.filter(place=self)\n\n#mptt.register(Place)\n\nclass Document(models.Model):\n name=models.CharField(max_length=60)\n place=models.ForeignKey(Place,blank=True,null=True)\n def latest_file(self):\n return DocFile.objects.filter(document=self).order_by('-id')[0]\n \nclass DocFile(models.Model):\n document=models.ForeignKey(Document)\n version=models.IntegerField()\n file_name=models.CharField(max_length=60)\n comment=models.CharField(max_length=90,blank=True,null=True)\n ctime = models.DateTimeField()\n user = models.ForeignKey(User)\n \n",
"step-ids": [
20,
22,
27,
29,
32
]
}
|
[
20,
22,
27,
29,
32
] |
import sys, getopt
import sys, locale
import httplib
import json
#sys.argv = [sys.argv[0], '--id=275', '--ofile=275.json']
def getRouteId(routeName, out_filename):
conn = httplib.HTTPConnection("data.ntpc.gov.tw")
qryString = "/od/data/api/67BB3C2B-E7D1-43A7-B872-61B2F082E11B?$format=json&$filter=nameZh%20eq%20" + routeName
conn.request("GET",qryString.encode('utf8'))
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print len(data)
ofile = open(out_filename, "w")
ofile.write(data)
ofile.close()
def main(argv):
route_id = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["id=","ofile="])
except getopt.GetoptError:
print 'cliGetRouteID.py -i <route id> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'cliGetRouteID.py -i <route id> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--id"):
route_id = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
getRouteId(route_id, outputfile)
print 'Route ID is', route_id
print 'Output file is', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
|
normal
|
{
"blob_id": "87c413051ed38b52fbcc0b0cf84ecd75cd1e3f0c",
"index": 3139,
"step-1": "import sys, getopt\nimport sys, locale\nimport httplib\nimport json\n\n#sys.argv = [sys.argv[0], '--id=275', '--ofile=275.json']\n\ndef getRouteId(routeName, out_filename):\n conn = httplib.HTTPConnection(\"data.ntpc.gov.tw\")\n qryString = \"/od/data/api/67BB3C2B-E7D1-43A7-B872-61B2F082E11B?$format=json&$filter=nameZh%20eq%20\" + routeName\n conn.request(\"GET\",qryString.encode('utf8'))\n response = conn.getresponse()\n print response.status, response.reason\n\n data = response.read()\n print len(data)\n\n ofile = open(out_filename, \"w\")\n ofile.write(data)\n ofile.close()\n \ndef main(argv):\n route_id = ''\n outputfile = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"id=\",\"ofile=\"])\n except getopt.GetoptError:\n print 'cliGetRouteID.py -i <route id> -o <outputfile>'\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print 'cliGetRouteID.py -i <route id> -o <outputfile>'\n sys.exit()\n elif opt in (\"-i\", \"--id\"):\n route_id = arg \n elif opt in (\"-o\", \"--ofile\"):\n outputfile = arg\n\n getRouteId(route_id, outputfile)\n print 'Route ID is', route_id\n print 'Output file is', outputfile\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
y_true = [7, 3, 3, 4, 9, 9, 2, 5, 0, 0, 6, 3, 1, 6, 8, 7, 9, 7, 4, 2, 0, 1,
4, 1, 7, 7, 5, 0, 8, 0, 1, 7, 4, 2, 2, 4, 9, 3, 1, 7, 1, 2, 1, 7, 5, 9,
9, 4, 8, 5, 7, 2, 7, 5, 5, 6, 6, 1, 2, 6, 6, 5, 3, 2, 3, 8, 8, 8, 8, 5,
3, 4, 3, 2, 8, 1, 9, 0, 6, 8, 6, 1, 1, 1, 5, 4, 8, 8, 5, 5, 8, 6, 4, 4,
6, 9, 8, 1, 5, 5]
y_pred_prob = [[0.0597563199698925, 0.1344364434480667, 0.1173347756266594,
0.11292721331119537, 0.10652001202106476, 0.13155865669250488,
0.10057594627141953, 0.10029518604278564, 0.10313529521226883,
0.03346000984311104], [0.0002930850023403764, 0.23393571376800537,
0.09061524271965027, 0.21862193942070007, 0.04659481346607208,
0.04461496323347092, 0.0952368974685669, 0.2075100988149643,
0.0616493821144104, 0.0009278177167288959], [0.22330643236637115,
1.0582012919257977e-06, 0.22777651250362396, 0.20880192518234253,
9.877869615593227e-07, 0.0006437229458242655, 0.1556401550769806,
7.201562368663872e-08, 0.18382851779460907, 5.064675860921852e-07], [
1.7682419638731517e-05, 0.001197152421809733, 0.015430454164743423,
0.0037515582516789436, 0.32882484793663025, 0.0003495111595839262,
0.012810198590159416, 0.054448556154966354, 0.30387693643569946,
0.27929291129112244], [0.16070464253425598, 4.810986276027052e-09,
0.15206283330917358, 0.004463076591491699, 0.1652054488658905,
0.0038724008481949568, 0.17216043174266815, 0.13407163321971893,
0.029512932524085045, 0.17794682085514069], [0.10922636836767197,
2.2864300319724862e-07, 0.11546860635280609, 0.001813476555980742,
0.1788507103919983, 0.005888130981475115, 0.18413811922073364,
0.10866158455610275, 0.10712066292762756, 0.18883220851421356], [
0.005557563621550798, 0.0001692363148322329, 0.35343053936958313,
0.0015008420450612903, 0.00037875055568292737, 0.2150292843580246,
0.014169459231197834, 0.03244209289550781, 0.33539846539497375,
0.041923996061086655], [0.193454310297966, 3.662989183794707e-05,
0.10065275430679321, 0.00039752188604325056, 0.16119857132434845,
0.19390884041786194, 0.07022294402122498, 0.02460072562098503,
0.16083283722400665, 0.0946948304772377], [0.28058794140815735,
1.1208027217435301e-06, 0.018203848972916603, 0.16030532121658325,
0.00018859952979255468, 0.21325571835041046, 0.2328961044549942,
0.007604319602251053, 0.04473938047885895, 0.04221738502383232], [
0.1718112975358963, 7.514636672567576e-05, 0.15386143326759338,
0.008414546959102154, 0.001738831982947886, 0.15720322728157043,
0.17100712656974792, 0.15586316585540771, 0.104509636759758,
0.07551562041044235], [0.001471314812079072, 0.008587654680013657,
0.0367623046040535, 0.011750160716474056, 0.07068527489900589,
0.4173307418823242, 0.12449752539396286, 0.014547907747328281,
0.2990296185016632, 0.01533727627247572], [0.005052714608609676,
0.0073812128975987434, 0.009834956377744675, 0.33292853832244873,
0.0018518454162403941, 0.0015299966325983405, 0.002040529390797019,
0.3055168688297272, 0.32741934061050415, 0.006443792954087257], [
0.0011697597801685333, 0.20749542117118835, 0.07009387016296387,
0.08994801342487335, 0.09965154528617859, 0.060963381081819534,
0.13158728182315826, 0.1365581601858139, 0.11990636587142944,
0.08262615650892258], [0.020798824727535248, 1.469431822442857e-06,
0.016172533854842186, 0.021048342809081078, 0.009139545261859894,
0.3956705331802368, 0.3814408779144287, 7.980810551089235e-06,
0.1391601711511612, 0.016559595242142677], [0.0008747534011490643,
0.0009511907119303942, 0.055323366075754166, 0.05426914989948273,
0.03363798186182976, 0.12827005982398987, 0.03197509050369263,
0.0008451330941170454, 0.37859639525413513, 0.3152569532394409], [
0.001832291018217802, 9.253426833311096e-05, 0.27192848920822144,
0.18078717589378357, 0.004130060318857431, 0.00929891224950552,
0.1695500910282135, 0.29965919256210327, 0.020460698753595352,
0.042260222136974335], [0.15259969234466553, 0.00015921871818136424,
0.16849327087402344, 0.002068838570266962, 0.17735524475574493,
0.02342645265161991, 0.18245863914489746, 0.00010533139720791951,
0.11123484373092651, 0.1820984184741974], [0.18936939537525177,
1.7293215250901994e-06, 0.029253976419568062, 0.1424887329339981,
0.01099975686520338, 0.0074686696752905846, 0.053486552089452744,
0.2111600935459137, 0.14551354944705963, 0.21025745570659637], [
3.861714503727853e-05, 0.1669524759054184, 0.00032175786327570677,
0.15850232541561127, 0.1955566704273224, 0.012984608300030231,
0.14730143547058105, 0.066555455327034, 0.1175893247127533,
0.13419757783412933], [0.1504199206829071, 0.006808706559240818,
0.22468900680541992, 0.18946652114391327, 1.2391226846375503e-05,
0.10332755744457245, 0.15032899379730225, 2.30663204092707e-06,
0.17487214505672455, 7.243863365147263e-05], [0.23918452858924866,
5.279692683046733e-09, 0.0671931579709053, 0.2041931003332138,
9.380520350532606e-05, 0.18892300128936768, 0.16166524589061737,
1.2340686907919007e-06, 0.1280936300754547, 0.010652361437678337], [
0.0019602354150265455, 0.17319674789905548, 0.16884981095790863,
0.025876348838210106, 0.11373495310544968, 0.034116633236408234,
0.09377618134021759, 0.16857513785362244, 0.10720878094434738,
0.11270517110824585], [0.006008224096149206, 7.275425741681829e-05,
0.002679133554920554, 0.005456522107124329, 0.2852444648742676,
0.007294526789337397, 0.26774612069129944, 0.0033797386568039656,
0.15357472002506256, 0.26854372024536133], [0.0020487161818891764,
0.18302913010120392, 0.17970730364322662, 0.03157859668135643,
0.10424197465181351, 0.028137331828475, 0.049388039857149124,
0.17323219776153564, 0.13171784579753876, 0.11691895872354507], [
0.011249794624745846, 0.0003711018362082541, 0.32693105936050415,
0.0010822461917996407, 0.0076926033943891525, 0.04566335678100586,
0.005700047593563795, 0.32916736602783203, 0.09476791322231293,
0.17737449705600739], [0.0001925578253576532, 7.067231763357995e-06,
0.0001896199828479439, 0.09954455494880676, 0.23005598783493042,
0.2152310460805893, 0.09002267569303513, 0.017976609990000725,
0.0920918807387352, 0.25468799471855164], [0.0006383731961250305,
3.095208057857235e-06, 0.0005969868507236242, 0.41469672322273254,
0.0053739529103040695, 0.40698617696762085, 0.08218759298324585,
0.0003528161614667624, 0.07473969459533691, 0.014424380846321583], [
0.19537049531936646, 3.243912300235352e-13, 0.005169959273189306,
0.17694340646266937, 2.949438930954784e-05, 0.1400780826807022,
0.18864554166793823, 3.857006959151477e-06, 0.18823771178722382,
0.10552132874727249], [0.009722508490085602, 3.8531984500878025e-06,
0.07383214682340622, 0.03598225489258766, 0.07267675548791885,
0.1459459662437439, 0.07249364256858826, 0.002293274737894535,
0.48588359355926514, 0.1011660099029541], [0.21651780605316162,
9.559274261050632e-09, 0.14371894299983978, 0.13431811332702637,
2.7394575226935558e-05, 0.1838626116514206, 0.17265450954437256,
0.00012304158008191735, 0.12219242751598358, 0.0265849307179451], [
4.430914850672707e-05, 0.2043066918849945, 0.0002825123374350369,
0.16263452172279358, 0.1939067542552948, 0.1427866667509079,
0.11921370774507523, 0.0028419536538422108, 0.06556723266839981,
0.10841585695743561], [0.004471424967050552, 0.1858968585729599,
0.17653658986091614, 0.01416453905403614, 0.008144107647240162,
0.0843614935874939, 0.05890577659010887, 0.18505530059337616,
0.10232891887426376, 0.18013498187065125], [0.00041712025995366275,
1.1021310228898074e-06, 0.08412905037403107, 0.0002837374631781131,
0.2740859091281891, 0.013903344981372356, 0.08929961919784546,
0.2733091115951538, 0.2233879268169403, 0.04118315503001213], [
0.04552318528294563, 0.020853176712989807, 0.26410210132598877,
0.23437173664569855, 2.1701146124541992e-06, 0.10220374912023544,
0.07447297871112823, 7.592303154524416e-05, 0.25814488530158997,
0.00025002588517963886], [0.024719374254345894, 0.00217414740473032,
0.26734668016433716, 0.17261573672294617, 0.003498602891340852,
0.05698162689805031, 0.2737174332141876, 8.039058593567461e-05,
0.19880186021327972, 6.410985952243209e-05], [0.12234598398208618,
6.703280632791575e-06, 0.015603234991431236, 0.013786871917545795,
0.21616478264331818, 0.005412149243056774, 0.11406012624502182,
0.12291428446769714, 0.18262456357479095, 0.20708128809928894], [
0.193313866853714, 6.033819488493464e-08, 0.14491458237171173,
0.2349807769060135, 0.0006736826617270708, 0.003743150969967246,
0.12457092851400375, 0.004962997976690531, 0.23268520832061768,
0.060154590755701065], [0.006641837302595377, 0.005113706924021244,
0.060135774314403534, 0.37294134497642517, 0.0001917753543239087,
0.35536521673202515, 0.003515040036290884, 0.00014136293611954898,
0.19584619998931885, 0.00010780058073578402], [0.00022568553686141968,
0.1758676916360855, 0.08169379830360413, 0.11927571147680283,
0.14987629652023315, 0.026822827756404877, 0.09613550454378128,
0.14441852271556854, 0.11029191315174103, 0.09539227187633514], [
0.028152454644441605, 0.04798303544521332, 0.06989692151546478,
0.07051544636487961, 0.07356826215982437, 0.05468234792351723,
0.11397064477205276, 0.2294078767299652, 0.0822836384177208,
0.22953952848911285], [0.0009083361364901066, 0.16873282194137573,
0.040142301470041275, 0.13509070873260498, 0.16045929491519928,
0.09148524701595306, 0.0939648225903511, 0.13889746367931366,
0.043392572551965714, 0.12692658603191376], [7.008769898675382e-05,
0.0012455701362341642, 0.4437786936759949, 0.03154001384973526,
0.0033613061532378197, 0.0024434190709143877, 0.3866567313671112,
0.0005211094976402819, 0.13020911812782288, 0.00017409549036528915], [
0.00034864526242017746, 0.21021592617034912, 0.005514794960618019,
0.11704950034618378, 0.08421261608600616, 0.13176649808883667,
0.11882488429546356, 0.008054501377046108, 0.1467529684305191,
0.1772596538066864], [0.036879003047943115, 0.0014911789912730455,
0.2685071527957916, 0.0029583016876131296, 0.011879128403961658,
0.030892902985215187, 0.08989892154932022, 0.29645001888275146,
0.04054954648017883, 0.2204938679933548], [0.0064177061431109905,
0.0045189931988716125, 0.013788403943181038, 0.18153700232505798,
0.0003662402159534395, 0.5257023572921753, 0.06426692008972168,
9.742573638504837e-06, 0.2026320844888687, 0.000760772149078548], [
0.0017538872780278325, 0.0002046643348876387, 0.04638877511024475,
0.11219469457864761, 0.1732793003320694, 0.000888414157088846,
0.1527005136013031, 0.171849325299263, 0.16653017699718475,
0.17421048879623413], [6.957617006264627e-05, 3.015168840647675e-05,
0.05601977929472923, 0.06104991212487221, 0.14622464776039124,
0.0013683908618986607, 0.004713970702141523, 0.26153290271759033,
0.21816983819007874, 0.25082090497016907], [0.001964711584150791,
0.14094221591949463, 0.04670453444123268, 0.11537310481071472,
0.1456061750650406, 0.021807175129652023, 0.1023702397942543,
0.14592182636260986, 0.1320936679840088, 0.14721626043319702], [
0.0013557883212342858, 5.542307803807489e-07, 0.015518834814429283,
0.020929962396621704, 0.12795883417129517, 0.012969551607966423,
0.011510342359542847, 0.3424086570739746, 0.3332746922969818,
0.1340728998184204], [0.0951327458024025, 0.03636496141552925,
0.018829435110092163, 0.060135968029499054, 0.1569897085428238,
0.1514764130115509, 0.13258931040763855, 0.1450430303812027,
0.04603665694594383, 0.15740196406841278], [0.17052830755710602,
1.5615187294315547e-06, 0.0013229812029749155, 0.12005076557397842,
0.021564221009612083, 0.024421295151114464, 0.17088675498962402,
0.15222683548927307, 0.1693890392780304, 0.16960804164409637], [
0.006946968380361795, 0.3011370897293091, 0.3187958002090454,
0.06604688614606857, 0.011190904304385185, 0.05437859520316124,
0.020502492785453796, 0.010224146768450737, 0.21062366664409637,
0.00015340560639742762], [0.003341993084177375, 0.0016007163794711232,
0.0007675797096453607, 0.18986503779888153, 0.1190534457564354,
0.02811228297650814, 0.09639428555965424, 0.21583504974842072,
0.13505271077156067, 0.2099769562482834], [0.042331017553806305,
0.00029962626285851, 0.0023094473872333765, 0.18676534295082092,
0.000317152967909351, 0.48982951045036316, 0.1871659755706787,
8.205944141082e-06, 0.09039845317602158, 0.0005752819124609232], [
0.27066469192504883, 0.0001488085399614647, 0.025224560871720314,
0.03236522525548935, 0.00022321399592328817, 0.3199988305568695,
0.20726615190505981, 2.1540354282478802e-05, 0.13308577239513397,
0.011001424863934517], [0.21046556532382965, 8.32586906085453e-08,
0.050842639058828354, 0.0012313498882576823, 0.17998859286308289,
0.005802170839160681, 0.22032563388347626, 9.771327313501388e-06,
0.2085702270269394, 0.12276387959718704], [0.278763085603714,
2.956639932882865e-10, 0.2363770455121994, 0.0021949675865471363,
0.024400619789958, 0.01081052329391241, 0.2788945734500885,
0.000592902593780309, 0.09800171107053757, 0.06996453553438187], [
0.0012440741993486881, 0.0002501744020264596, 0.039189230650663376,
0.003109667217358947, 0.1353403925895691, 0.17648975551128387,
0.29823172092437744, 0.0005026640137657523, 0.1873668134212494,
0.15827545523643494], [4.636057929019444e-05, 0.004471238702535629,
0.010865537449717522, 0.03406133875250816, 0.2391168773174286,
0.0102084307000041, 0.24508318305015564, 0.10957624763250351,
0.10304577648639679, 0.24352511763572693], [0.007771539501845837,
0.003819737583398819, 0.05605701357126236, 0.0013185413554310799,
0.026425426825881004, 0.37273845076560974, 0.39364394545555115,
3.468452996457927e-05, 0.13644644618034363, 0.0017443000106140971], [
0.0042862421832978725, 4.118454022261631e-09, 0.24541069567203522,
1.311416235694196e-05, 0.002639196580275893, 0.2002275139093399,
0.35612747073173523, 8.159701246768236e-05, 0.11912810802459717,
0.07208611816167831], [0.10790199786424637, 0.00018712706514634192,
0.001723292050883174, 0.3369658291339874, 0.005216643214225769,
0.323357492685318, 0.04629630222916603, 0.0006358266109600663,
0.17700347304344177, 0.0007120332447811961], [0.01004449650645256,
0.0038342783227562904, 0.0029477709904313087, 0.39860454201698303,
0.000900272571016103, 0.32782217860221863, 0.010686549358069897,
0.0006012170924805105, 0.23407192528247833, 0.010486727580428123], [
0.0015078516444191337, 0.23596949875354767, 0.4038705825805664,
0.04463784024119377, 0.00036313795135356486, 0.005906661506742239,
0.012559221126139164, 0.010579549707472324, 0.2843676507472992,
0.0002381248341407627], [0.1887362003326416, 0.0019065006636083126,
0.2840288579463959, 0.2984219193458557, 4.9067231884691864e-05,
0.1615515947341919, 0.012938770465552807, 0.00029289082158356905,
0.052058152854442596, 1.6269357729470357e-05], [0.0006827416946180165,
2.276465056638699e-05, 0.023704057559370995, 0.16121432185173035,
0.0033186341170221567, 0.004117893520742655, 0.03627816215157509,
0.009822812862694263, 0.7281517386436462, 0.032687313854694366], [
0.0011369712883606553, 0.27387163043022156, 0.07185991108417511,
0.15628814697265625, 0.002854800783097744, 0.23154565691947937,
0.03204796463251114, 0.003870188258588314, 0.22623319923877716,
0.00029159500263631344], [0.0035695999395102262, 0.26706114411354065,
0.1508740484714508, 0.0013921442441642284, 0.019328434020280838,
0.13771453499794006, 0.029891734942793846, 0.03509771451354027,
0.24692872166633606, 0.1081417053937912], [0.000882012362126261,
2.536918327677995e-05, 0.0450599268078804, 0.412322998046875,
0.0025211411993950605, 0.002278776839375496, 0.011372447945177555,
0.1770726591348648, 0.33388030529022217, 0.014584112912416458], [
0.21903501451015472, 5.910552047794226e-09, 0.022012481465935707,
0.20099963247776031, 1.0874355211853981e-05, 0.21909210085868835,
0.21668335795402527, 4.337367798257219e-08, 0.12212178856134415,
4.4732783862855285e-05], [0.014651631936430931, 0.00830799899995327,
0.005935078486800194, 0.3953670263290405, 1.1293817806290463e-05,
0.4299878776073456, 0.017106691375374794, 0.00014334742445498705,
0.11808823049068451, 0.010400976054370403], [0.010301091708242893,
0.01435689628124237, 0.07430031895637512, 0.06989920139312744,
0.2338510900735855, 0.053795550018548965, 0.22257547080516815,
0.0029012206941843033, 0.09203658252954483, 0.22598253190517426], [
0.033016644418239594, 0.0020125852897763252, 0.06661045551300049,
0.4920836091041565, 0.00025867935619316995, 0.07482428848743439,
0.13923810422420502, 0.00012527030776254833, 0.19180776178836823,
2.269313517899718e-05], [0.1325867474079132, 0.004940022714436054,
0.22300080955028534, 0.2727201282978058, 3.310650572529994e-05,
0.12915031611919403, 0.01339033618569374, 1.0927167750196531e-05,
0.22410929203033447, 5.8520683523966e-05], [0.126132994890213,
0.0013935434399172664, 0.17098797857761383, 0.00039779843064025044,
0.07732491940259933, 0.16493096947669983, 0.014501826837658882,
0.03405503183603287, 0.20594964921474457, 0.2043251097202301], [
0.0008475463255308568, 0.19114449620246887, 0.03174148499965668,
0.1596948355436325, 0.1830475926399231, 0.11398201435804367,
0.11080365628004074, 0.10536272078752518, 0.05745834857225418,
0.04591764137148857], [0.0009525367058813572, 0.0012388192117214203,
0.0006522738258354366, 0.15977761149406433, 0.2019728273153305,
0.037797972559928894, 0.19880010187625885, 0.008799873292446136,
0.18693988025188446, 0.20306788384914398], [0.21417981386184692,
1.8215121144748991e-07, 0.11546390503644943, 0.10518436878919601,
5.3784842748427764e-05, 0.17964830994606018, 0.1753360480070114,
0.005312803667038679, 0.07569659501314163, 0.1291242241859436], [
0.03322113677859306, 1.1228289409359604e-08, 0.11529551446437836,
0.006697801407426596, 0.020004654303193092, 0.2904326617717743,
0.3397071361541748, 6.173769179440569e-06, 0.1187906265258789,
0.07584403455257416], [0.00018722846289165318, 0.00015633362636435777,
0.027305739000439644, 0.30433472990989685, 0.12216899544000626,
0.0051543135195970535, 0.07717369496822357, 5.6467473768861964e-05,
0.46220865845680237, 0.0012535307323560119], [0.2223890870809555,
1.8010264568601997e-07, 0.051188305020332336, 0.06915734708309174,
0.007792292162775993, 0.13037307560443878, 0.4795873761177063,
6.65841726004146e-05, 0.03377178683876991, 0.0056741489097476006], [
0.0011432061437517405, 0.172257199883461, 0.08959532529115677,
0.09976792335510254, 0.13487820327281952, 0.025573352351784706,
0.11224105209112167, 0.1427890509366989, 0.12529729306697845,
0.09645748883485794], [0.00039081714930944145, 0.17529502511024475,
0.07816692441701889, 0.12808731198310852, 0.13959045708179474,
0.04451143741607666, 0.07863735407590866, 0.1518080085515976,
0.09225541353225708, 0.11125729233026505], [0.0005360758514143527,
0.1871286779642105, 0.09343081712722778, 0.10187795013189316,
0.15403643250465393, 0.03745483607053757, 0.10108820348978043,
0.1381213515996933, 0.1196260005235672, 0.0666997954249382], [
0.02377643622457981, 0.002874232828617096, 0.06835681945085526,
0.08628982305526733, 0.16734763979911804, 0.1884264051914215,
0.06887176632881165, 0.1883554309606552, 0.11966855823993683,
0.0860329195857048], [0.0019290593918412924, 0.0004132240719627589,
0.08087942749261856, 0.00133050128351897, 0.2057691514492035,
0.014698517508804798, 0.10668473690748215, 0.2002524882555008,
0.19643288850784302, 0.19160999357700348], [4.1589693864807487e-05,
3.0074079404585063e-06, 0.00946643017232418, 0.0028675245121121407,
0.339987188577652, 0.006530506536364555, 0.21062259376049042,
5.006019819120411e-06, 0.4303286373615265, 0.00014742799976374954], [
0.23467645049095154, 3.957170217048535e-14, 0.016559595242142677,
0.22702592611312866, 0.0004185910802334547, 0.0031147561967372894,
0.2260916531085968, 2.4497327899553056e-07, 0.2333890199661255,
0.05872354656457901], [0.1723964959383011, 1.4810979109824984e-07,
0.001400468056090176, 0.3012116253376007, 0.00017689657397568226,
0.29611334204673767, 0.013564502820372581, 0.04992862418293953,
0.15185707807540894, 0.013350787572562695], [0.18757264316082,
1.502647393181178e-07, 0.0013043361250311136, 0.08373606950044632,
0.0005724140792153776, 0.1799388974905014, 0.14538954198360443,
0.16594813764095306, 0.06483398377895355, 0.17070381343364716], [
0.008307700976729393, 0.0005032537155784667, 0.04173918813467026,
0.055757056921720505, 0.2954571545124054, 0.046274807304143906,
0.15145555138587952, 0.00160416669677943, 0.36763912439346313,
0.031262170523405075], [0.03202534094452858, 2.929154447883775e-07,
0.03331722691655159, 0.0002443870762363076, 0.021324075758457184,
0.3864181637763977, 0.39420267939567566, 3.2187076612899546e-06,
0.08215467631816864, 0.050310224294662476], [0.03041147254407406,
3.317395247393051e-10, 0.013215649873018265, 0.009000282734632492,
0.15260590612888336, 9.569835674483329e-05, 0.22718068957328796,
0.0983223170042038, 0.23328886926174164, 0.23587895929813385], [
0.0017376767937093973, 0.01800091378390789, 0.09461784362792969,
0.008886604569852352, 0.23299837112426758, 0.03532419353723526,
0.20058980584144592, 0.1702878624200821, 0.06943482160568237,
0.1681220531463623], [0.26592451333999634, 1.378083283043452e-07,
0.26663097739219666, 0.00043869472574442625, 0.0753256231546402,
0.000345755455782637, 0.2718716561794281, 0.09590824693441391,
0.021168876439332962, 0.0023856020998209715], [0.007719929795712233,
0.000273746729362756, 0.06954099237918854, 0.11292484402656555,
0.17693056166172028, 0.0036023242864757776, 0.16335690021514893,
0.1139131560921669, 0.17289915680885315, 0.17883846163749695], [
0.0002722161589190364, 0.0014734293799847364, 0.0001780118327587843,
0.0718056932091713, 0.219150573015213, 0.02937471494078636,
0.15243956446647644, 0.07647080719470978, 0.21917390823364258,
0.22966115176677704], [0.0008591399528086185, 0.27216723561286926,
0.030793067067861557, 0.040201541036367416, 0.07587726414203644,
0.06215333193540573, 0.16188929975032806, 0.04154059290885925,
0.21999017894268036, 0.09452840685844421], [0.156771719455719,
0.0009459690772928298, 0.08676373958587646, 0.012071664445102215,
0.046294376254081726, 0.1705559939146042, 0.05631829798221588,
0.16554586589336395, 0.14995504915714264, 0.15477733314037323], [
0.0036007703747600317, 0.0036146841011941433, 0.007429149001836777,
0.10190737992525101, 0.0016259902622550726, 0.45585712790489197,
0.04189519211649895, 7.317630092984473e-07, 0.3802386522293091,
0.003830441040918231]]
|
normal
|
{
"blob_id": "593d3221e34c0eef51228082d767d8516ec93ca2",
"index": 8002,
"step-1": "<mask token>\n",
"step-2": "y_true = [7, 3, 3, 4, 9, 9, 2, 5, 0, 0, 6, 3, 1, 6, 8, 7, 9, 7, 4, 2, 0, 1,\n 4, 1, 7, 7, 5, 0, 8, 0, 1, 7, 4, 2, 2, 4, 9, 3, 1, 7, 1, 2, 1, 7, 5, 9,\n 9, 4, 8, 5, 7, 2, 7, 5, 5, 6, 6, 1, 2, 6, 6, 5, 3, 2, 3, 8, 8, 8, 8, 5,\n 3, 4, 3, 2, 8, 1, 9, 0, 6, 8, 6, 1, 1, 1, 5, 4, 8, 8, 5, 5, 8, 6, 4, 4,\n 6, 9, 8, 1, 5, 5]\ny_pred_prob = [[0.0597563199698925, 0.1344364434480667, 0.1173347756266594,\n 0.11292721331119537, 0.10652001202106476, 0.13155865669250488, \n 0.10057594627141953, 0.10029518604278564, 0.10313529521226883, \n 0.03346000984311104], [0.0002930850023403764, 0.23393571376800537, \n 0.09061524271965027, 0.21862193942070007, 0.04659481346607208, \n 0.04461496323347092, 0.0952368974685669, 0.2075100988149643, \n 0.0616493821144104, 0.0009278177167288959], [0.22330643236637115, \n 1.0582012919257977e-06, 0.22777651250362396, 0.20880192518234253, \n 9.877869615593227e-07, 0.0006437229458242655, 0.1556401550769806, \n 7.201562368663872e-08, 0.18382851779460907, 5.064675860921852e-07], [\n 1.7682419638731517e-05, 0.001197152421809733, 0.015430454164743423, \n 0.0037515582516789436, 0.32882484793663025, 0.0003495111595839262, \n 0.012810198590159416, 0.054448556154966354, 0.30387693643569946, \n 0.27929291129112244], [0.16070464253425598, 4.810986276027052e-09, \n 0.15206283330917358, 0.004463076591491699, 0.1652054488658905, \n 0.0038724008481949568, 0.17216043174266815, 0.13407163321971893, \n 0.029512932524085045, 0.17794682085514069], [0.10922636836767197, \n 2.2864300319724862e-07, 0.11546860635280609, 0.001813476555980742, \n 0.1788507103919983, 0.005888130981475115, 0.18413811922073364, \n 0.10866158455610275, 0.10712066292762756, 0.18883220851421356], [\n 0.005557563621550798, 0.0001692363148322329, 0.35343053936958313, \n 0.0015008420450612903, 0.00037875055568292737, 0.2150292843580246, \n 0.014169459231197834, 0.03244209289550781, 0.33539846539497375, \n 0.041923996061086655], [0.193454310297966, 3.662989183794707e-05, \n 0.10065275430679321, 0.00039752188604325056, 0.16119857132434845, \n 0.19390884041786194, 0.07022294402122498, 0.02460072562098503, \n 0.16083283722400665, 0.0946948304772377], [0.28058794140815735, \n 1.1208027217435301e-06, 0.018203848972916603, 0.16030532121658325, \n 0.00018859952979255468, 0.21325571835041046, 0.2328961044549942, \n 0.007604319602251053, 0.04473938047885895, 0.04221738502383232], [\n 0.1718112975358963, 7.514636672567576e-05, 0.15386143326759338, \n 0.008414546959102154, 0.001738831982947886, 0.15720322728157043, \n 0.17100712656974792, 0.15586316585540771, 0.104509636759758, \n 0.07551562041044235], [0.001471314812079072, 0.008587654680013657, \n 0.0367623046040535, 0.011750160716474056, 0.07068527489900589, \n 0.4173307418823242, 0.12449752539396286, 0.014547907747328281, \n 0.2990296185016632, 0.01533727627247572], [0.005052714608609676, \n 0.0073812128975987434, 0.009834956377744675, 0.33292853832244873, \n 0.0018518454162403941, 0.0015299966325983405, 0.002040529390797019, \n 0.3055168688297272, 0.32741934061050415, 0.006443792954087257], [\n 0.0011697597801685333, 0.20749542117118835, 0.07009387016296387, \n 0.08994801342487335, 0.09965154528617859, 0.060963381081819534, \n 0.13158728182315826, 0.1365581601858139, 0.11990636587142944, \n 0.08262615650892258], [0.020798824727535248, 1.469431822442857e-06, \n 0.016172533854842186, 0.021048342809081078, 0.009139545261859894, \n 0.3956705331802368, 0.3814408779144287, 7.980810551089235e-06, \n 0.1391601711511612, 0.016559595242142677], [0.0008747534011490643, \n 0.0009511907119303942, 0.055323366075754166, 0.05426914989948273, \n 0.03363798186182976, 0.12827005982398987, 0.03197509050369263, \n 0.0008451330941170454, 0.37859639525413513, 0.3152569532394409], [\n 0.001832291018217802, 9.253426833311096e-05, 0.27192848920822144, \n 0.18078717589378357, 0.004130060318857431, 0.00929891224950552, \n 0.1695500910282135, 0.29965919256210327, 0.020460698753595352, \n 0.042260222136974335], [0.15259969234466553, 0.00015921871818136424, \n 0.16849327087402344, 0.002068838570266962, 0.17735524475574493, \n 0.02342645265161991, 0.18245863914489746, 0.00010533139720791951, \n 0.11123484373092651, 0.1820984184741974], [0.18936939537525177, \n 1.7293215250901994e-06, 0.029253976419568062, 0.1424887329339981, \n 0.01099975686520338, 0.0074686696752905846, 0.053486552089452744, \n 0.2111600935459137, 0.14551354944705963, 0.21025745570659637], [\n 3.861714503727853e-05, 0.1669524759054184, 0.00032175786327570677, \n 0.15850232541561127, 0.1955566704273224, 0.012984608300030231, \n 0.14730143547058105, 0.066555455327034, 0.1175893247127533, \n 0.13419757783412933], [0.1504199206829071, 0.006808706559240818, \n 0.22468900680541992, 0.18946652114391327, 1.2391226846375503e-05, \n 0.10332755744457245, 0.15032899379730225, 2.30663204092707e-06, \n 0.17487214505672455, 7.243863365147263e-05], [0.23918452858924866, \n 5.279692683046733e-09, 0.0671931579709053, 0.2041931003332138, \n 9.380520350532606e-05, 0.18892300128936768, 0.16166524589061737, \n 1.2340686907919007e-06, 0.1280936300754547, 0.010652361437678337], [\n 0.0019602354150265455, 0.17319674789905548, 0.16884981095790863, \n 0.025876348838210106, 0.11373495310544968, 0.034116633236408234, \n 0.09377618134021759, 0.16857513785362244, 0.10720878094434738, \n 0.11270517110824585], [0.006008224096149206, 7.275425741681829e-05, \n 0.002679133554920554, 0.005456522107124329, 0.2852444648742676, \n 0.007294526789337397, 0.26774612069129944, 0.0033797386568039656, \n 0.15357472002506256, 0.26854372024536133], [0.0020487161818891764, \n 0.18302913010120392, 0.17970730364322662, 0.03157859668135643, \n 0.10424197465181351, 0.028137331828475, 0.049388039857149124, \n 0.17323219776153564, 0.13171784579753876, 0.11691895872354507], [\n 0.011249794624745846, 0.0003711018362082541, 0.32693105936050415, \n 0.0010822461917996407, 0.0076926033943891525, 0.04566335678100586, \n 0.005700047593563795, 0.32916736602783203, 0.09476791322231293, \n 0.17737449705600739], [0.0001925578253576532, 7.067231763357995e-06, \n 0.0001896199828479439, 0.09954455494880676, 0.23005598783493042, \n 0.2152310460805893, 0.09002267569303513, 0.017976609990000725, \n 0.0920918807387352, 0.25468799471855164], [0.0006383731961250305, \n 3.095208057857235e-06, 0.0005969868507236242, 0.41469672322273254, \n 0.0053739529103040695, 0.40698617696762085, 0.08218759298324585, \n 0.0003528161614667624, 0.07473969459533691, 0.014424380846321583], [\n 0.19537049531936646, 3.243912300235352e-13, 0.005169959273189306, \n 0.17694340646266937, 2.949438930954784e-05, 0.1400780826807022, \n 0.18864554166793823, 3.857006959151477e-06, 0.18823771178722382, \n 0.10552132874727249], [0.009722508490085602, 3.8531984500878025e-06, \n 0.07383214682340622, 0.03598225489258766, 0.07267675548791885, \n 0.1459459662437439, 0.07249364256858826, 0.002293274737894535, \n 0.48588359355926514, 0.1011660099029541], [0.21651780605316162, \n 9.559274261050632e-09, 0.14371894299983978, 0.13431811332702637, \n 2.7394575226935558e-05, 0.1838626116514206, 0.17265450954437256, \n 0.00012304158008191735, 0.12219242751598358, 0.0265849307179451], [\n 4.430914850672707e-05, 0.2043066918849945, 0.0002825123374350369, \n 0.16263452172279358, 0.1939067542552948, 0.1427866667509079, \n 0.11921370774507523, 0.0028419536538422108, 0.06556723266839981, \n 0.10841585695743561], [0.004471424967050552, 0.1858968585729599, \n 0.17653658986091614, 0.01416453905403614, 0.008144107647240162, \n 0.0843614935874939, 0.05890577659010887, 0.18505530059337616, \n 0.10232891887426376, 0.18013498187065125], [0.00041712025995366275, \n 1.1021310228898074e-06, 0.08412905037403107, 0.0002837374631781131, \n 0.2740859091281891, 0.013903344981372356, 0.08929961919784546, \n 0.2733091115951538, 0.2233879268169403, 0.04118315503001213], [\n 0.04552318528294563, 0.020853176712989807, 0.26410210132598877, \n 0.23437173664569855, 2.1701146124541992e-06, 0.10220374912023544, \n 0.07447297871112823, 7.592303154524416e-05, 0.25814488530158997, \n 0.00025002588517963886], [0.024719374254345894, 0.00217414740473032, \n 0.26734668016433716, 0.17261573672294617, 0.003498602891340852, \n 0.05698162689805031, 0.2737174332141876, 8.039058593567461e-05, \n 0.19880186021327972, 6.410985952243209e-05], [0.12234598398208618, \n 6.703280632791575e-06, 0.015603234991431236, 0.013786871917545795, \n 0.21616478264331818, 0.005412149243056774, 0.11406012624502182, \n 0.12291428446769714, 0.18262456357479095, 0.20708128809928894], [\n 0.193313866853714, 6.033819488493464e-08, 0.14491458237171173, \n 0.2349807769060135, 0.0006736826617270708, 0.003743150969967246, \n 0.12457092851400375, 0.004962997976690531, 0.23268520832061768, \n 0.060154590755701065], [0.006641837302595377, 0.005113706924021244, \n 0.060135774314403534, 0.37294134497642517, 0.0001917753543239087, \n 0.35536521673202515, 0.003515040036290884, 0.00014136293611954898, \n 0.19584619998931885, 0.00010780058073578402], [0.00022568553686141968, \n 0.1758676916360855, 0.08169379830360413, 0.11927571147680283, \n 0.14987629652023315, 0.026822827756404877, 0.09613550454378128, \n 0.14441852271556854, 0.11029191315174103, 0.09539227187633514], [\n 0.028152454644441605, 0.04798303544521332, 0.06989692151546478, \n 0.07051544636487961, 0.07356826215982437, 0.05468234792351723, \n 0.11397064477205276, 0.2294078767299652, 0.0822836384177208, \n 0.22953952848911285], [0.0009083361364901066, 0.16873282194137573, \n 0.040142301470041275, 0.13509070873260498, 0.16045929491519928, \n 0.09148524701595306, 0.0939648225903511, 0.13889746367931366, \n 0.043392572551965714, 0.12692658603191376], [7.008769898675382e-05, \n 0.0012455701362341642, 0.4437786936759949, 0.03154001384973526, \n 0.0033613061532378197, 0.0024434190709143877, 0.3866567313671112, \n 0.0005211094976402819, 0.13020911812782288, 0.00017409549036528915], [\n 0.00034864526242017746, 0.21021592617034912, 0.005514794960618019, \n 0.11704950034618378, 0.08421261608600616, 0.13176649808883667, \n 0.11882488429546356, 0.008054501377046108, 0.1467529684305191, \n 0.1772596538066864], [0.036879003047943115, 0.0014911789912730455, \n 0.2685071527957916, 0.0029583016876131296, 0.011879128403961658, \n 0.030892902985215187, 0.08989892154932022, 0.29645001888275146, \n 0.04054954648017883, 0.2204938679933548], [0.0064177061431109905, \n 0.0045189931988716125, 0.013788403943181038, 0.18153700232505798, \n 0.0003662402159534395, 0.5257023572921753, 0.06426692008972168, \n 9.742573638504837e-06, 0.2026320844888687, 0.000760772149078548], [\n 0.0017538872780278325, 0.0002046643348876387, 0.04638877511024475, \n 0.11219469457864761, 0.1732793003320694, 0.000888414157088846, \n 0.1527005136013031, 0.171849325299263, 0.16653017699718475, \n 0.17421048879623413], [6.957617006264627e-05, 3.015168840647675e-05, \n 0.05601977929472923, 0.06104991212487221, 0.14622464776039124, \n 0.0013683908618986607, 0.004713970702141523, 0.26153290271759033, \n 0.21816983819007874, 0.25082090497016907], [0.001964711584150791, \n 0.14094221591949463, 0.04670453444123268, 0.11537310481071472, \n 0.1456061750650406, 0.021807175129652023, 0.1023702397942543, \n 0.14592182636260986, 0.1320936679840088, 0.14721626043319702], [\n 0.0013557883212342858, 5.542307803807489e-07, 0.015518834814429283, \n 0.020929962396621704, 0.12795883417129517, 0.012969551607966423, \n 0.011510342359542847, 0.3424086570739746, 0.3332746922969818, \n 0.1340728998184204], [0.0951327458024025, 0.03636496141552925, \n 0.018829435110092163, 0.060135968029499054, 0.1569897085428238, \n 0.1514764130115509, 0.13258931040763855, 0.1450430303812027, \n 0.04603665694594383, 0.15740196406841278], [0.17052830755710602, \n 1.5615187294315547e-06, 0.0013229812029749155, 0.12005076557397842, \n 0.021564221009612083, 0.024421295151114464, 0.17088675498962402, \n 0.15222683548927307, 0.1693890392780304, 0.16960804164409637], [\n 0.006946968380361795, 0.3011370897293091, 0.3187958002090454, \n 0.06604688614606857, 0.011190904304385185, 0.05437859520316124, \n 0.020502492785453796, 0.010224146768450737, 0.21062366664409637, \n 0.00015340560639742762], [0.003341993084177375, 0.0016007163794711232, \n 0.0007675797096453607, 0.18986503779888153, 0.1190534457564354, \n 0.02811228297650814, 0.09639428555965424, 0.21583504974842072, \n 0.13505271077156067, 0.2099769562482834], [0.042331017553806305, \n 0.00029962626285851, 0.0023094473872333765, 0.18676534295082092, \n 0.000317152967909351, 0.48982951045036316, 0.1871659755706787, \n 8.205944141082e-06, 0.09039845317602158, 0.0005752819124609232], [\n 0.27066469192504883, 0.0001488085399614647, 0.025224560871720314, \n 0.03236522525548935, 0.00022321399592328817, 0.3199988305568695, \n 0.20726615190505981, 2.1540354282478802e-05, 0.13308577239513397, \n 0.011001424863934517], [0.21046556532382965, 8.32586906085453e-08, \n 0.050842639058828354, 0.0012313498882576823, 0.17998859286308289, \n 0.005802170839160681, 0.22032563388347626, 9.771327313501388e-06, \n 0.2085702270269394, 0.12276387959718704], [0.278763085603714, \n 2.956639932882865e-10, 0.2363770455121994, 0.0021949675865471363, \n 0.024400619789958, 0.01081052329391241, 0.2788945734500885, \n 0.000592902593780309, 0.09800171107053757, 0.06996453553438187], [\n 0.0012440741993486881, 0.0002501744020264596, 0.039189230650663376, \n 0.003109667217358947, 0.1353403925895691, 0.17648975551128387, \n 0.29823172092437744, 0.0005026640137657523, 0.1873668134212494, \n 0.15827545523643494], [4.636057929019444e-05, 0.004471238702535629, \n 0.010865537449717522, 0.03406133875250816, 0.2391168773174286, \n 0.0102084307000041, 0.24508318305015564, 0.10957624763250351, \n 0.10304577648639679, 0.24352511763572693], [0.007771539501845837, \n 0.003819737583398819, 0.05605701357126236, 0.0013185413554310799, \n 0.026425426825881004, 0.37273845076560974, 0.39364394545555115, \n 3.468452996457927e-05, 0.13644644618034363, 0.0017443000106140971], [\n 0.0042862421832978725, 4.118454022261631e-09, 0.24541069567203522, \n 1.311416235694196e-05, 0.002639196580275893, 0.2002275139093399, \n 0.35612747073173523, 8.159701246768236e-05, 0.11912810802459717, \n 0.07208611816167831], [0.10790199786424637, 0.00018712706514634192, \n 0.001723292050883174, 0.3369658291339874, 0.005216643214225769, \n 0.323357492685318, 0.04629630222916603, 0.0006358266109600663, \n 0.17700347304344177, 0.0007120332447811961], [0.01004449650645256, \n 0.0038342783227562904, 0.0029477709904313087, 0.39860454201698303, \n 0.000900272571016103, 0.32782217860221863, 0.010686549358069897, \n 0.0006012170924805105, 0.23407192528247833, 0.010486727580428123], [\n 0.0015078516444191337, 0.23596949875354767, 0.4038705825805664, \n 0.04463784024119377, 0.00036313795135356486, 0.005906661506742239, \n 0.012559221126139164, 0.010579549707472324, 0.2843676507472992, \n 0.0002381248341407627], [0.1887362003326416, 0.0019065006636083126, \n 0.2840288579463959, 0.2984219193458557, 4.9067231884691864e-05, \n 0.1615515947341919, 0.012938770465552807, 0.00029289082158356905, \n 0.052058152854442596, 1.6269357729470357e-05], [0.0006827416946180165, \n 2.276465056638699e-05, 0.023704057559370995, 0.16121432185173035, \n 0.0033186341170221567, 0.004117893520742655, 0.03627816215157509, \n 0.009822812862694263, 0.7281517386436462, 0.032687313854694366], [\n 0.0011369712883606553, 0.27387163043022156, 0.07185991108417511, \n 0.15628814697265625, 0.002854800783097744, 0.23154565691947937, \n 0.03204796463251114, 0.003870188258588314, 0.22623319923877716, \n 0.00029159500263631344], [0.0035695999395102262, 0.26706114411354065, \n 0.1508740484714508, 0.0013921442441642284, 0.019328434020280838, \n 0.13771453499794006, 0.029891734942793846, 0.03509771451354027, \n 0.24692872166633606, 0.1081417053937912], [0.000882012362126261, \n 2.536918327677995e-05, 0.0450599268078804, 0.412322998046875, \n 0.0025211411993950605, 0.002278776839375496, 0.011372447945177555, \n 0.1770726591348648, 0.33388030529022217, 0.014584112912416458], [\n 0.21903501451015472, 5.910552047794226e-09, 0.022012481465935707, \n 0.20099963247776031, 1.0874355211853981e-05, 0.21909210085868835, \n 0.21668335795402527, 4.337367798257219e-08, 0.12212178856134415, \n 4.4732783862855285e-05], [0.014651631936430931, 0.00830799899995327, \n 0.005935078486800194, 0.3953670263290405, 1.1293817806290463e-05, \n 0.4299878776073456, 0.017106691375374794, 0.00014334742445498705, \n 0.11808823049068451, 0.010400976054370403], [0.010301091708242893, \n 0.01435689628124237, 0.07430031895637512, 0.06989920139312744, \n 0.2338510900735855, 0.053795550018548965, 0.22257547080516815, \n 0.0029012206941843033, 0.09203658252954483, 0.22598253190517426], [\n 0.033016644418239594, 0.0020125852897763252, 0.06661045551300049, \n 0.4920836091041565, 0.00025867935619316995, 0.07482428848743439, \n 0.13923810422420502, 0.00012527030776254833, 0.19180776178836823, \n 2.269313517899718e-05], [0.1325867474079132, 0.004940022714436054, \n 0.22300080955028534, 0.2727201282978058, 3.310650572529994e-05, \n 0.12915031611919403, 0.01339033618569374, 1.0927167750196531e-05, \n 0.22410929203033447, 5.8520683523966e-05], [0.126132994890213, \n 0.0013935434399172664, 0.17098797857761383, 0.00039779843064025044, \n 0.07732491940259933, 0.16493096947669983, 0.014501826837658882, \n 0.03405503183603287, 0.20594964921474457, 0.2043251097202301], [\n 0.0008475463255308568, 0.19114449620246887, 0.03174148499965668, \n 0.1596948355436325, 0.1830475926399231, 0.11398201435804367, \n 0.11080365628004074, 0.10536272078752518, 0.05745834857225418, \n 0.04591764137148857], [0.0009525367058813572, 0.0012388192117214203, \n 0.0006522738258354366, 0.15977761149406433, 0.2019728273153305, \n 0.037797972559928894, 0.19880010187625885, 0.008799873292446136, \n 0.18693988025188446, 0.20306788384914398], [0.21417981386184692, \n 1.8215121144748991e-07, 0.11546390503644943, 0.10518436878919601, \n 5.3784842748427764e-05, 0.17964830994606018, 0.1753360480070114, \n 0.005312803667038679, 0.07569659501314163, 0.1291242241859436], [\n 0.03322113677859306, 1.1228289409359604e-08, 0.11529551446437836, \n 0.006697801407426596, 0.020004654303193092, 0.2904326617717743, \n 0.3397071361541748, 6.173769179440569e-06, 0.1187906265258789, \n 0.07584403455257416], [0.00018722846289165318, 0.00015633362636435777, \n 0.027305739000439644, 0.30433472990989685, 0.12216899544000626, \n 0.0051543135195970535, 0.07717369496822357, 5.6467473768861964e-05, \n 0.46220865845680237, 0.0012535307323560119], [0.2223890870809555, \n 1.8010264568601997e-07, 0.051188305020332336, 0.06915734708309174, \n 0.007792292162775993, 0.13037307560443878, 0.4795873761177063, \n 6.65841726004146e-05, 0.03377178683876991, 0.0056741489097476006], [\n 0.0011432061437517405, 0.172257199883461, 0.08959532529115677, \n 0.09976792335510254, 0.13487820327281952, 0.025573352351784706, \n 0.11224105209112167, 0.1427890509366989, 0.12529729306697845, \n 0.09645748883485794], [0.00039081714930944145, 0.17529502511024475, \n 0.07816692441701889, 0.12808731198310852, 0.13959045708179474, \n 0.04451143741607666, 0.07863735407590866, 0.1518080085515976, \n 0.09225541353225708, 0.11125729233026505], [0.0005360758514143527, \n 0.1871286779642105, 0.09343081712722778, 0.10187795013189316, \n 0.15403643250465393, 0.03745483607053757, 0.10108820348978043, \n 0.1381213515996933, 0.1196260005235672, 0.0666997954249382], [\n 0.02377643622457981, 0.002874232828617096, 0.06835681945085526, \n 0.08628982305526733, 0.16734763979911804, 0.1884264051914215, \n 0.06887176632881165, 0.1883554309606552, 0.11966855823993683, \n 0.0860329195857048], [0.0019290593918412924, 0.0004132240719627589, \n 0.08087942749261856, 0.00133050128351897, 0.2057691514492035, \n 0.014698517508804798, 0.10668473690748215, 0.2002524882555008, \n 0.19643288850784302, 0.19160999357700348], [4.1589693864807487e-05, \n 3.0074079404585063e-06, 0.00946643017232418, 0.0028675245121121407, \n 0.339987188577652, 0.006530506536364555, 0.21062259376049042, \n 5.006019819120411e-06, 0.4303286373615265, 0.00014742799976374954], [\n 0.23467645049095154, 3.957170217048535e-14, 0.016559595242142677, \n 0.22702592611312866, 0.0004185910802334547, 0.0031147561967372894, \n 0.2260916531085968, 2.4497327899553056e-07, 0.2333890199661255, \n 0.05872354656457901], [0.1723964959383011, 1.4810979109824984e-07, \n 0.001400468056090176, 0.3012116253376007, 0.00017689657397568226, \n 0.29611334204673767, 0.013564502820372581, 0.04992862418293953, \n 0.15185707807540894, 0.013350787572562695], [0.18757264316082, \n 1.502647393181178e-07, 0.0013043361250311136, 0.08373606950044632, \n 0.0005724140792153776, 0.1799388974905014, 0.14538954198360443, \n 0.16594813764095306, 0.06483398377895355, 0.17070381343364716], [\n 0.008307700976729393, 0.0005032537155784667, 0.04173918813467026, \n 0.055757056921720505, 0.2954571545124054, 0.046274807304143906, \n 0.15145555138587952, 0.00160416669677943, 0.36763912439346313, \n 0.031262170523405075], [0.03202534094452858, 2.929154447883775e-07, \n 0.03331722691655159, 0.0002443870762363076, 0.021324075758457184, \n 0.3864181637763977, 0.39420267939567566, 3.2187076612899546e-06, \n 0.08215467631816864, 0.050310224294662476], [0.03041147254407406, \n 3.317395247393051e-10, 0.013215649873018265, 0.009000282734632492, \n 0.15260590612888336, 9.569835674483329e-05, 0.22718068957328796, \n 0.0983223170042038, 0.23328886926174164, 0.23587895929813385], [\n 0.0017376767937093973, 0.01800091378390789, 0.09461784362792969, \n 0.008886604569852352, 0.23299837112426758, 0.03532419353723526, \n 0.20058980584144592, 0.1702878624200821, 0.06943482160568237, \n 0.1681220531463623], [0.26592451333999634, 1.378083283043452e-07, \n 0.26663097739219666, 0.00043869472574442625, 0.0753256231546402, \n 0.000345755455782637, 0.2718716561794281, 0.09590824693441391, \n 0.021168876439332962, 0.0023856020998209715], [0.007719929795712233, \n 0.000273746729362756, 0.06954099237918854, 0.11292484402656555, \n 0.17693056166172028, 0.0036023242864757776, 0.16335690021514893, \n 0.1139131560921669, 0.17289915680885315, 0.17883846163749695], [\n 0.0002722161589190364, 0.0014734293799847364, 0.0001780118327587843, \n 0.0718056932091713, 0.219150573015213, 0.02937471494078636, \n 0.15243956446647644, 0.07647080719470978, 0.21917390823364258, \n 0.22966115176677704], [0.0008591399528086185, 0.27216723561286926, \n 0.030793067067861557, 0.040201541036367416, 0.07587726414203644, \n 0.06215333193540573, 0.16188929975032806, 0.04154059290885925, \n 0.21999017894268036, 0.09452840685844421], [0.156771719455719, \n 0.0009459690772928298, 0.08676373958587646, 0.012071664445102215, \n 0.046294376254081726, 0.1705559939146042, 0.05631829798221588, \n 0.16554586589336395, 0.14995504915714264, 0.15477733314037323], [\n 0.0036007703747600317, 0.0036146841011941433, 0.007429149001836777, \n 0.10190737992525101, 0.0016259902622550726, 0.45585712790489197, \n 0.04189519211649895, 7.317630092984473e-07, 0.3802386522293091, \n 0.003830441040918231]]\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
import requests
from pyrogram import Client as Bot
from samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN
from samantha.services.callsmusic import run
response = requests.get(BG_IMAGE)
file = open("./etc/tg_vc_bot.jpg", "wb")
file.write(response.content)
file.close()
bot = Bot(
":memory:",
API_ID,
API_HASH,
bot_token=BOT_TOKEN,
plugins=dict(root="samantha.modules"),
)
bot.start()
run()
|
normal
|
{
"blob_id": "c5ac37ce09f7cd76ccd9b93c64e602209a04c55c",
"index": 1824,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile.write(response.content)\nfile.close()\n<mask token>\nbot.start()\nrun()\n",
"step-3": "<mask token>\nresponse = requests.get(BG_IMAGE)\nfile = open('./etc/tg_vc_bot.jpg', 'wb')\nfile.write(response.content)\nfile.close()\nbot = Bot(':memory:', API_ID, API_HASH, bot_token=BOT_TOKEN, plugins=dict(\n root='samantha.modules'))\nbot.start()\nrun()\n",
"step-4": "import requests\nfrom pyrogram import Client as Bot\nfrom samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN\nfrom samantha.services.callsmusic import run\nresponse = requests.get(BG_IMAGE)\nfile = open('./etc/tg_vc_bot.jpg', 'wb')\nfile.write(response.content)\nfile.close()\nbot = Bot(':memory:', API_ID, API_HASH, bot_token=BOT_TOKEN, plugins=dict(\n root='samantha.modules'))\nbot.start()\nrun()\n",
"step-5": "import requests\nfrom pyrogram import Client as Bot\n\nfrom samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN\nfrom samantha.services.callsmusic import run\n\nresponse = requests.get(BG_IMAGE)\nfile = open(\"./etc/tg_vc_bot.jpg\", \"wb\")\nfile.write(response.content)\nfile.close()\n\nbot = Bot(\n \":memory:\",\n API_ID,\n API_HASH,\n bot_token=BOT_TOKEN,\n plugins=dict(root=\"samantha.modules\"),\n)\n\nbot.start()\nrun()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import mysql.connector
from getpass import getpass
tables_schema = {
"Country": "SELECT 'Id','Name','Code' " +
"UNION ALL " +
"SELECT Id, Name, Code ",
"Indicator": "SELECT 'Id','Name','Code' " +
"UNION ALL " +
"SELECT Id, Name, Code ",
"Year": "SELECT 'Id','FiveYearPeriod','TenYearPeriod' " +
"UNION ALL " +
"SELECT Id, FiveYearPeriod, TenYearPeriod ",
"Metric": "SELECT 'CountryId','IndicatorId','YearId','Measurement' " +
"UNION ALL " +
"SELECT CountryId, IndicatorId, YearId, Measurement "
}
dbconnector = None
cursor = None
def backup_db(cursor):
for table in tables_schema: backup_table(cursor, table)
def backup_table(cursor, table):
cursor.execute(f"{tables_schema[table]}" +
f"INTO OUTFILE '/tmp/{table.lower()}_data.csv' " +
"FIELDS TERMINATED BY ',' " +
"LINES TERMINATED BY '\\n' " +
f"FROM {table}")
def print_report(db_name):
print (f"Database: '{db_name}' successfully backed up under '\\tmp' directory!")
def connect_db(password, db_name):
global dbconnector, cursor
dbconnector = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = password,
database = db_name,
autocommit = True
)
cursor = dbconnector.cursor()
def main():
password = getpass("MySQL password:")
db_name = "WORLDMETRIC"
connect_db(password, db_name)
backup_db(cursor)
print_report(db_name)
dbconnector.close()
main()
|
normal
|
{
"blob_id": "fd76a7dd90bac7c7ba9201b6db62e6cb3eedeced",
"index": 4390,
"step-1": "<mask token>\n\n\ndef backup_db(cursor):\n for table in tables_schema:\n backup_table(cursor, table)\n\n\ndef backup_table(cursor, table):\n cursor.execute(f'{tables_schema[table]}' +\n f\"INTO OUTFILE '/tmp/{table.lower()}_data.csv' \" +\n \"FIELDS TERMINATED BY ',' \" + \"LINES TERMINATED BY '\\\\n' \" +\n f'FROM {table}')\n\n\ndef print_report(db_name):\n print(\n f\"Database: '{db_name}' successfully backed up under '\\\\tmp' directory!\"\n )\n\n\n<mask token>\n\n\ndef main():\n password = getpass('MySQL password:')\n db_name = 'WORLDMETRIC'\n connect_db(password, db_name)\n backup_db(cursor)\n print_report(db_name)\n dbconnector.close()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef backup_db(cursor):\n for table in tables_schema:\n backup_table(cursor, table)\n\n\ndef backup_table(cursor, table):\n cursor.execute(f'{tables_schema[table]}' +\n f\"INTO OUTFILE '/tmp/{table.lower()}_data.csv' \" +\n \"FIELDS TERMINATED BY ',' \" + \"LINES TERMINATED BY '\\\\n' \" +\n f'FROM {table}')\n\n\ndef print_report(db_name):\n print(\n f\"Database: '{db_name}' successfully backed up under '\\\\tmp' directory!\"\n )\n\n\ndef connect_db(password, db_name):\n global dbconnector, cursor\n dbconnector = mysql.connector.connect(host='localhost', user='root',\n passwd=password, database=db_name, autocommit=True)\n cursor = dbconnector.cursor()\n\n\ndef main():\n password = getpass('MySQL password:')\n db_name = 'WORLDMETRIC'\n connect_db(password, db_name)\n backup_db(cursor)\n print_report(db_name)\n dbconnector.close()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef backup_db(cursor):\n for table in tables_schema:\n backup_table(cursor, table)\n\n\ndef backup_table(cursor, table):\n cursor.execute(f'{tables_schema[table]}' +\n f\"INTO OUTFILE '/tmp/{table.lower()}_data.csv' \" +\n \"FIELDS TERMINATED BY ',' \" + \"LINES TERMINATED BY '\\\\n' \" +\n f'FROM {table}')\n\n\ndef print_report(db_name):\n print(\n f\"Database: '{db_name}' successfully backed up under '\\\\tmp' directory!\"\n )\n\n\ndef connect_db(password, db_name):\n global dbconnector, cursor\n dbconnector = mysql.connector.connect(host='localhost', user='root',\n passwd=password, database=db_name, autocommit=True)\n cursor = dbconnector.cursor()\n\n\ndef main():\n password = getpass('MySQL password:')\n db_name = 'WORLDMETRIC'\n connect_db(password, db_name)\n backup_db(cursor)\n print_report(db_name)\n dbconnector.close()\n\n\nmain()\n",
"step-4": "<mask token>\ntables_schema = {'Country': \"SELECT 'Id','Name','Code' \" + 'UNION ALL ' +\n 'SELECT Id, Name, Code ', 'Indicator': \"SELECT 'Id','Name','Code' \" +\n 'UNION ALL ' + 'SELECT Id, Name, Code ', 'Year': \n \"SELECT 'Id','FiveYearPeriod','TenYearPeriod' \" + 'UNION ALL ' +\n 'SELECT Id, FiveYearPeriod, TenYearPeriod ', 'Metric': \n \"SELECT 'CountryId','IndicatorId','YearId','Measurement' \" +\n 'UNION ALL ' + 'SELECT CountryId, IndicatorId, YearId, Measurement '}\ndbconnector = None\ncursor = None\n\n\ndef backup_db(cursor):\n for table in tables_schema:\n backup_table(cursor, table)\n\n\ndef backup_table(cursor, table):\n cursor.execute(f'{tables_schema[table]}' +\n f\"INTO OUTFILE '/tmp/{table.lower()}_data.csv' \" +\n \"FIELDS TERMINATED BY ',' \" + \"LINES TERMINATED BY '\\\\n' \" +\n f'FROM {table}')\n\n\ndef print_report(db_name):\n print(\n f\"Database: '{db_name}' successfully backed up under '\\\\tmp' directory!\"\n )\n\n\ndef connect_db(password, db_name):\n global dbconnector, cursor\n dbconnector = mysql.connector.connect(host='localhost', user='root',\n passwd=password, database=db_name, autocommit=True)\n cursor = dbconnector.cursor()\n\n\ndef main():\n password = getpass('MySQL password:')\n db_name = 'WORLDMETRIC'\n connect_db(password, db_name)\n backup_db(cursor)\n print_report(db_name)\n dbconnector.close()\n\n\nmain()\n",
"step-5": "import mysql.connector\nfrom getpass import getpass\n\ntables_schema = {\n\t\t\t\t\"Country\": \"SELECT 'Id','Name','Code' \" +\n\t\t\t\t\t\t\t \"UNION ALL \" +\n\t\t\t\t\t\t\t \"SELECT Id, Name, Code \",\n\n\t\t\t\t\"Indicator\": \"SELECT 'Id','Name','Code' \" +\n\t\t\t\t\t\t\t \"UNION ALL \" +\n\t\t\t\t\t\t\t \"SELECT Id, Name, Code \",\n\n\t\t \t\t\"Year\": \"SELECT 'Id','FiveYearPeriod','TenYearPeriod' \" +\n\t\t\t\t\t\t \"UNION ALL \" +\n\t\t\t\t\t\t \"SELECT Id, FiveYearPeriod, TenYearPeriod \",\n\n\t\t\t\t\"Metric\": \"SELECT 'CountryId','IndicatorId','YearId','Measurement' \" +\n\t\t\t\t\t\t \"UNION ALL \" +\n\t\t\t\t\t\t \"SELECT CountryId, IndicatorId, YearId, Measurement \"\n\t\t\t\t}\n\ndbconnector = None\ncursor = None\n\ndef backup_db(cursor):\n\n\tfor table in tables_schema: backup_table(cursor, table)\n\ndef backup_table(cursor, table):\n\n\tcursor.execute(f\"{tables_schema[table]}\" +\n\t\t\t\t f\"INTO OUTFILE '/tmp/{table.lower()}_data.csv' \" +\n\t\t\t\t \"FIELDS TERMINATED BY ',' \" +\n\t\t\t\t \"LINES TERMINATED BY '\\\\n' \" +\n\t\t\t\t f\"FROM {table}\")\n\ndef print_report(db_name):\n\n\tprint (f\"Database: '{db_name}' successfully backed up under '\\\\tmp' directory!\")\n\ndef connect_db(password, db_name):\n\n\tglobal dbconnector, cursor\n\tdbconnector = mysql.connector.connect(\n\t\thost = \"localhost\",\n\t\tuser = \"root\",\n\t\tpasswd = password,\n\t\tdatabase = db_name,\n\t\tautocommit = True\n\t)\n\tcursor = dbconnector.cursor()\n\ndef main():\n\n\tpassword = getpass(\"MySQL password:\")\n\tdb_name = \"WORLDMETRIC\"\n\tconnect_db(password, db_name)\n\tbackup_db(cursor)\n\tprint_report(db_name)\n\tdbconnector.close()\n\nmain()",
"step-ids": [
4,
5,
6,
7,
9
]
}
|
[
4,
5,
6,
7,
9
] |
def main():
s1 = 'mabaabm'
s2 = 'moktko!'
s3 = ex7(s1, s2)
print(s3)
def ex7(in1, in2):
out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0
] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]
return out1
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "f45cae397aa3b7bdba6e3f36e20b926487cb160d",
"index": 9238,
"step-1": "<mask token>\n",
"step-2": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\n<mask token>\n",
"step-3": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\ndef ex7(in1, in2):\n out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0\n ] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]\n return out1\n\n\n<mask token>\n",
"step-4": "def main():\n s1 = 'mabaabm'\n s2 = 'moktko!'\n s3 = ex7(s1, s2)\n print(s3)\n\n\ndef ex7(in1, in2):\n out1 = in1[0] + in1[int(len(in1) / 2)] + in1[int(len(in1) - 1)] + in2[0\n ] + in2[int(len(in2) / 2)] + in2[int(len(in2) - 1)]\n return out1\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name= 'contact'),
path('category/', views.category, name='category'),
path('product/<str:id>/<slug:slug>',views.product_list, name='product_list'),
path('product-detail/<str:id>/<slug:slug>', views.prod_detail, name= 'prod_detail'),
]
|
normal
|
{
"blob_id": "0588aad1536a81d047a2a2b91f83fdde4d1be974",
"index": 3869,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('', views.index, name='index'), path('about/', views.\n about, name='about'), path('contact/', views.contact, name='contact'),\n path('category/', views.category, name='category'), path(\n 'product/<str:id>/<slug:slug>', views.product_list, name='product_list'\n ), path('product-detail/<str:id>/<slug:slug>', views.prod_detail, name=\n 'prod_detail')]\n",
"step-3": "from django.urls import path\nfrom . import views\nurlpatterns = [path('', views.index, name='index'), path('about/', views.\n about, name='about'), path('contact/', views.contact, name='contact'),\n path('category/', views.category, name='category'), path(\n 'product/<str:id>/<slug:slug>', views.product_list, name='product_list'\n ), path('product-detail/<str:id>/<slug:slug>', views.prod_detail, name=\n 'prod_detail')]\n",
"step-4": "from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('about/', views.about, name='about'),\n path('contact/', views.contact, name= 'contact'),\n path('category/', views.category, name='category'),\n path('product/<str:id>/<slug:slug>',views.product_list, name='product_list'),\n path('product-detail/<str:id>/<slug:slug>', views.prod_detail, name= 'prod_detail'),\n]",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_visual_coding_2p_analysis
----------------------------------
Tests for `visual_coding_2p_analysis` module.
"""
import pytest
@pytest.fixture
def decorated_example():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
def test_example(decorated_example):
"""Sample pytest test function with the pytest fixture as an argument.
"""
import visual_coding_2p_analysis
|
normal
|
{
"blob_id": "ae3198e68d9479605327b729c01fb15eae87ab98",
"index": 3282,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\[email protected]\ndef decorated_example():\n \"\"\"Sample pytest fixture.\n See more at: http://doc.pytest.org/en/latest/fixture.html\n \"\"\"\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\[email protected]\ndef decorated_example():\n \"\"\"Sample pytest fixture.\n See more at: http://doc.pytest.org/en/latest/fixture.html\n \"\"\"\n\n\ndef test_example(decorated_example):\n \"\"\"Sample pytest test function with the pytest fixture as an argument.\n \"\"\"\n import visual_coding_2p_analysis\n",
"step-4": "<mask token>\nimport pytest\n\n\[email protected]\ndef decorated_example():\n \"\"\"Sample pytest fixture.\n See more at: http://doc.pytest.org/en/latest/fixture.html\n \"\"\"\n\n\ndef test_example(decorated_example):\n \"\"\"Sample pytest test function with the pytest fixture as an argument.\n \"\"\"\n import visual_coding_2p_analysis\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_visual_coding_2p_analysis\n----------------------------------\n\nTests for `visual_coding_2p_analysis` module.\n\"\"\"\nimport pytest\n\n\[email protected]\ndef decorated_example():\n \"\"\"Sample pytest fixture.\n See more at: http://doc.pytest.org/en/latest/fixture.html\n \"\"\"\n\ndef test_example(decorated_example):\n \"\"\"Sample pytest test function with the pytest fixture as an argument.\n \"\"\"\n import visual_coding_2p_analysis\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from .ctoybox import Game, State as FrameState, Input
import numpy as np
from PIL import Image
import json
from typing import Dict, Any, List, Tuple, Union, Optional
def json_str(js: Union[Dict[str, Any], Input, str]) -> str:
"""
Turn an object into a JSON string -- handles dictionaries, the Input class, and JSON you've already prepared (e.g., strings).
"""
if type(js) is dict:
js = json.dumps(js)
elif type(js) is Input:
js = json.dumps(js.__dict__)
elif type(js) is not str:
raise ValueError(
"Unknown json type: %s (only str and dict supported)" % type(js)
)
return js
class Simulator(object):
"""
The Simulator is an instance of a game configuration.
You can call new_game on it to begin.
"""
def __init__(self, game_name, sim=None):
"""
Construct a new instance.
Parameters:
game_name: one of "breakout", "amidar", etc.
sim: optionally a Rust pointer to an existing simulator.
"""
if sim is None:
sim = Game(game_name)
self.__sim = sim
# sim should be a pointer
self.game_name = game_name
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def set_seed(self, seed: int):
"""Configure the random number generator that spawns new game states.
Parameters:
seed: a parameter to reset the built-in random number generator.
"""
self.__sim.seed(seed)
def get_frame_size(self) -> Tuple[int, int]:
"""Get the width in pixels of the frames this game renders."""
return self.__sim.frame_size()
def get_frame_width(self) -> int:
"""Get the width in pixels of the frames this game renders."""
return self.__sim.frame_size()[0]
def get_frame_height(self) -> int:
"""Get the height in pixels of the frames this game renders."""
return self.__sim.frame_size()[1]
def get_simulator(self) -> Game:
"""Get access to the raw simulator pointer."""
return self.__sim
def new_game(self) -> "State":
"""Start a new game."""
return State(self, self.__sim.new_game())
def state_from_json(self, js: Union[Dict[str, Any], str]) -> "State":
"""Generate a State from the state json and this configuration.
Parameters:
js: a JSON object or string containing a serialized state.
"""
state: FrameState = self.__sim.new_state(json_str(js))
return State(self, state=state)
def to_json(self) -> Dict[str, Any]:
"""Get the configuration of this simulator/config as JSON"""
return json.loads(self.__sim.to_json())
def from_json(self, config_js: Union[Dict[str, Any], str]):
"""Mutably update this simulator/config with the replacement json."""
self.__sim = self.__sim.from_json(json_str(config_js))
def schema_for_state(self) -> Dict[str, Any]:
"""Get the JSON Schema for any state for this game."""
return json.loads(self.__sim.frame_schema())
def schema_for_config(self) -> Dict[str, Any]:
"""Get the JSON Schema for any config for this game."""
return json.loads(self.__sim.config_schema())
class State(object):
"""
The State object represents everything the game needs to know about any single simulated frame.
You can rewind in time by storing and restoring these state representations.
- Access the json: ``to_json``
- Access the image: ``render_frame``
"""
def __init__(self, sim: Simulator, state=None):
"""
Construct a new State instance wrapper.
Parameters:
sim: The simulator responsible for this state.
state: Optional pointer to a state to use (otherwise it will create one).
"""
self.sim = sim
"""A reference to the simulator that created this state."""
self.__state = state or sim.__sim.new_game()
"""The raw pointer to the state itself."""
self.game_name = sim.game_name
"""The name of the game that created this state."""
def __enter__(self):
return self
def __del__(self):
self.__state = None
self.sim = None
def __exit__(self, exc_type, exc_value, traceback):
self.__del__()
def clone(self) -> 'State':
"""Quickly make a copy of this state; should be more efficient than saving the JSON."""
return State(self.sim, state=self.get_state().copy())
def get_state(self) -> FrameState:
"""Get the raw state pointer."""
assert self.__state is not None
return self.__state
def lives(self) -> int:
"""How many lives are remaining in the current state?"""
return self.__state.lives()
def level(self) -> int:
"""How many levels have been completed in the current state?"""
return self.__state.level()
def score(self) -> int:
"""How many points have been earned in the current state?"""
return self.__state.score()
def game_over(self):
"""Determine whether the game has ended; i.e., the player has run out of lives.
>>> assert self.lives() < 0 == self.game_over()
"""
return self.lives() < 0
def query_json(
self, query: str, args: Union[Dict[str, Any], str] = "null"
) -> Dict[str, Any]:
"""
Ask a question of the Rust state; queries are currently implemented manually.
Parameters:
query: the message to send to the rust state.
args: the arguments to send to the rust state, defaults to "null".
Returns:
response: A JSON response loaded to python objects.
Raises:
ValueError: if anything goes wrong with the query
```python
with Toybox("breakout") as tb:
tb.query_json("bricks_remaining")
```
"""
return json.loads(self.__state.query(json_str(query), json_str(args)))
def render_frame(self, sim: Simulator, grayscale: bool = True) -> np.array:
"""Generate an image from the current frame state object.
Parameters:
sim: the simulator to use; this tells us the width/height necessary.
grayscale: True if we want to render in grayscale rather than in color (RGBA).
"""
if grayscale:
return self.render_frame_rgb(sim)
else:
return self.render_frame_color(sim)
def render_frame_color(self, sim: Simulator) -> np.array:
"""Generate an RGBA image from the current frame state object.
Parameters:
sim: the simulator to use; this tells us the width/height necessary.
"""
(w, h) = sim.get_frame_size()
rgba = 4
size = h * w * rgba
frame = bytearray(size)
self.get_state().render_into_buffer(frame, True)
return np.asarray(frame, dtype=np.uint8).reshape(h, w, rgba)
def render_frame_rgb(self, sim: Simulator) -> np.array:
"""Generate an RGB image from the current frame state object.
Parameters:
sim: the simulator to use; this tells us the width/height necessary.
"""
rgba_frame = self.render_frame_color(sim)
return rgba_frame[:, :, :3]
def render_frame_grayscale(self, sim: Simulator) -> np.array:
"""Generate a grayscale image from the current frame state object.
Parameters:
sim: the simulator to use; this tells us the width/height necessary.
"""
(w, h) = sim.get_frame_size()
depth = 1
size = h * w * depth
frame = bytearray(size)
self.get_state().render_into_buffer(frame, False)
return np.asarray(frame, dtype=np.uint8).reshape(h, w, depth)
def to_json(self) -> Dict[str, Any]:
"""Get a JSON representation of the state."""
return json.loads(self.get_state().to_json())
class Toybox(object):
"""
This is a stateful representation of Toybox -- since it manages memory, we provide ``__enter__`` and ``__exit__`` usage for Python's with-blocks:
```python
with Toybox("amidar") as tb:
print(tb.get_score())
# the 'tb' variable only lives in the block.
```
Important:
Note how we should use this in a with-block; this will clean up pointers and prevent memory leaks.
"""
def __init__(self,
game_name: str,
grayscale: bool = True,
frameskip: int = 0,
seed: Optional[int] = None,
withstate: Optional[dict] = None):
"""
Construct a new Toybox state/game wrapper. Use this in a with block!
Parameters:
game_name: One of "breakout", "space_invaders", "amidar", etc.
grayscale: Toybox can render directly to grayscale, saving time. Default is True.
frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.
seed: The seed
"""
self.game_name = game_name
self.frames_per_action = frameskip + 1
self.rsimulator = Simulator(game_name)
self.rstate = self.rsimulator.new_game()
self.grayscale = grayscale
if seed:
self.set_seed(seed)
self.new_game()
if withstate:
self.write_state_json(withstate)
def new_game(self):
"""
Modify this Toybox wrapper to have a new_game state.
Important:
This discards the old state!
"""
old_state = self.rstate
del old_state
self.rstate = self.rsimulator.new_game()
def get_height(self) -> int:
"""Get the height of the rendered game in pixels."""
return self.rsimulator.get_frame_height()
def get_width(self) -> int:
"""Get the width of the rendered game in pixels."""
return self.rsimulator.get_frame_width()
def get_legal_action_set(self) -> List[int]:
"""Get the set of actions consumed by this game: they are ALE numbered."""
sim = self.rsimulator.get_simulator()
return sim.legal_actions()
def apply_ale_action(self, action_int: int):
"""Takes an integer corresponding to an action, as specified in ALE.
This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.
```python
ALE_INPUT_MAPPING = {
0 : "NOOP",
1 : "FIRE",
2 : "UP",
3 : "RIGHT",
4 : "LEFT",
5 : "DOWN",
6 : "UPRIGHT",
7 : "UPLEFT",
8 : "DOWNRIGHT",
9 : "DOWNLEFT",
10 : "UPFIRE",
11 : "RIGHTFIRE",
12 : "LEFTFIRE",
13 : "DOWNFIRE",
14 : "UPRIGHTFIRE",
15 : "UPLEFTFIRE",
16 : "DOWNRIGHTFIRE",
17 : "DOWNLEFTFIRE"
}
```
Parameters:
action_int: A number from 0 to 17 inclusive.
"""
# implement frameskip(k) by sending the action (k+1) times every time we have an action.
for _ in range(self.frames_per_action):
if not self.rstate.get_state().apply_ale_action(action_int):
raise ValueError(
"Expected to apply action, but failed: {0}".format(action_int)
)
def apply_action(self, action_input_obj: Input):
"""Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.
This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.
Parameters:
action_input_obj: An instance of the [ctoybox.Input][] class.
"""
# implement frameskip(k) by sending the action (k+1) times every time we have an action.
for _ in range(self.frames_per_action):
self.rstate.get_state().apply_action(action_input_obj)
def get_state(self) -> np.array:
"""This state here actually refers to the graphical, RGBA or grayscale representation of the current state."""
return self.rstate.render_frame(self.rsimulator, self.grayscale)
def set_seed(self, seed: int):
"""Control the random number generator of the config -- only affects a new_game.
Parameters:
seed: a parameter to reset the built-in random number generator.
"""
self.rsimulator.set_seed(seed)
# Maybe call new game here?
def save_frame_image(self, path: str, grayscale: bool = False):
"""Save the current frame image to a PNG file.
Parameters:
path: the filename to save to.
grayscale: whether images should be saved in color or black & white.
"""
img = None
if grayscale:
img = Image.fromarray(
self.rstate.render_frame_grayscale(self.rsimulator), "L"
)
else:
img = Image.fromarray(
self.rstate.render_frame_color(self.rsimulator), "RGBA"
)
img.save(path, format="png")
def get_rgb_frame(self) -> np.array:
"""Get the RGB frame as a numpy array."""
return self.rstate.render_frame_rgb(self.rsimulator)
def get_score(self) -> int:
"""Access the current score.
Returns:
The number of points earned in the current state."""
return self.rstate.score()
def get_lives(self) -> int:
"""Access the number of lives.
Returns:
The number of lives remaining in the current state."""
return self.rstate.lives()
def get_level(self) -> int:
"""
Access the number of levels.
Returns:
The number of levels completed in the current state."""
return self.rstate.level()
def game_over(self) -> bool:
"""
Check for game over condition.
Returns:
``True`` if the player has run out of lives in the current state.
"""
return self.rstate.game_over()
def state_to_json(self) -> Dict[str, Any]:
"""Get the state's JSON representation as a python object."""
return self.rstate.to_json()
def to_state_json(self) -> Dict[str, Any]:
"""Get the state's JSON representation as a python dict.
Important:
This method is deprecated; please use ``state_to_json`` instead!
"""
return self.state_to_json()
def config_to_json(self) -> Dict[str, Any]:
"""Get the state's JSON representation as a python dict."""
return self.rsimulator.to_json()
def write_state_json(self, js: Dict[str, Any]):
"""Overwrite the state's JSON representation from a python dict.
Parameters:
js: the python representation of the JSON state.
"""
old_state = self.rstate
del old_state
self.rstate = self.rsimulator.state_from_json(js)
def write_config_json(self, config_js: Dict[str, Any]):
"""Overwrite the config's JSON representation from a python dict.
It is likely that some changes will be seen until you call new_game()
Parameters:
config_js: the python representation of the config JSON
"""
# from_json replaces simulator!
self.rsimulator.from_json(config_js)
# new_game replaces state!
self.new_game()
def query_state_json(
self, query: str, args: Union[Dict[str, Any], str] = "null"
) -> Dict[str, Any]:
"""Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.
Parameters:
query: the query string to send to the game.
args: a JSON argument to attach to the query string.
"""
return self.rstate.query_json(query, args)
def __del__(self):
self.rstate = None
self.rsimulator = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.__del__()
def schema_for_state(self) -> Dict[str, Any]:
"""Get the JSON Schema for the frame State object."""
return self.rsimulator.schema_for_state()
def schema_for_config(self) -> Dict[str, Any]:
"""Get the JSON Schema for the Config object."""
return self.rsimulator.schema_for_config()
|
normal
|
{
"blob_id": "c77e320cee90e8210e4c13d854649b15f6e24180",
"index": 2798,
"step-1": "<mask token>\n\n\nclass Toybox(object):\n <mask token>\n\n def __init__(self, game_name: str, grayscale: bool=True, frameskip: int\n =0, seed: Optional[int]=None, withstate: Optional[dict]=None):\n \"\"\"\n Construct a new Toybox state/game wrapper. Use this in a with block!\n\n Parameters:\n game_name: One of \"breakout\", \"space_invaders\", \"amidar\", etc.\n grayscale: Toybox can render directly to grayscale, saving time. Default is True.\n frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.\n seed: The seed \n \"\"\"\n self.game_name = game_name\n self.frames_per_action = frameskip + 1\n self.rsimulator = Simulator(game_name)\n self.rstate = self.rsimulator.new_game()\n self.grayscale = grayscale\n if seed:\n self.set_seed(seed)\n self.new_game()\n if withstate:\n self.write_state_json(withstate)\n\n def new_game(self):\n \"\"\"\n Modify this Toybox wrapper to have a new_game state.\n\n Important:\n This discards the old state!\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.new_game()\n\n def get_height(self) ->int:\n \"\"\"Get the height of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_height()\n\n def get_width(self) ->int:\n \"\"\"Get the width of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_width()\n\n def get_legal_action_set(self) ->List[int]:\n \"\"\"Get the set of actions consumed by this game: they are ALE numbered.\"\"\"\n sim = self.rsimulator.get_simulator()\n return sim.legal_actions()\n\n def apply_ale_action(self, action_int: int):\n \"\"\"Takes an integer corresponding to an action, as specified in ALE.\n \n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n ```python\n ALE_INPUT_MAPPING = {\n 0 : \"NOOP\",\n 1 : \"FIRE\",\n 2 : \"UP\",\n 3 : \"RIGHT\",\n 4 : \"LEFT\",\n 5 : \"DOWN\",\n 6 : \"UPRIGHT\",\n 7 : \"UPLEFT\",\n 8 : \"DOWNRIGHT\",\n 9 : \"DOWNLEFT\",\n 10 : \"UPFIRE\",\n 11 : \"RIGHTFIRE\",\n 12 : \"LEFTFIRE\",\n 13 : \"DOWNFIRE\",\n 14 : \"UPRIGHTFIRE\",\n 15 : \"UPLEFTFIRE\",\n 16 : \"DOWNRIGHTFIRE\",\n 17 : \"DOWNLEFTFIRE\"\n }\n ```\n\n Parameters:\n action_int: A number from 0 to 17 inclusive.\n \"\"\"\n for _ in range(self.frames_per_action):\n if not self.rstate.get_state().apply_ale_action(action_int):\n raise ValueError('Expected to apply action, but failed: {0}'\n .format(action_int))\n\n def apply_action(self, action_input_obj: Input):\n \"\"\"Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.\n\n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n Parameters:\n action_input_obj: An instance of the [ctoybox.Input][] class.\n \"\"\"\n for _ in range(self.frames_per_action):\n self.rstate.get_state().apply_action(action_input_obj)\n\n def get_state(self) ->np.array:\n \"\"\"This state here actually refers to the graphical, RGBA or grayscale representation of the current state.\"\"\"\n return self.rstate.render_frame(self.rsimulator, self.grayscale)\n\n def set_seed(self, seed: int):\n \"\"\"Control the random number generator of the config -- only affects a new_game.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.rsimulator.set_seed(seed)\n\n def save_frame_image(self, path: str, grayscale: bool=False):\n \"\"\"Save the current frame image to a PNG file.\n \n Parameters:\n path: the filename to save to.\n grayscale: whether images should be saved in color or black & white.\n \"\"\"\n img = None\n if grayscale:\n img = Image.fromarray(self.rstate.render_frame_grayscale(self.\n rsimulator), 'L')\n else:\n img = Image.fromarray(self.rstate.render_frame_color(self.\n rsimulator), 'RGBA')\n img.save(path, format='png')\n\n def get_rgb_frame(self) ->np.array:\n \"\"\"Get the RGB frame as a numpy array.\"\"\"\n return self.rstate.render_frame_rgb(self.rsimulator)\n\n def get_score(self) ->int:\n \"\"\"Access the current score.\n\n Returns:\n The number of points earned in the current state.\"\"\"\n return self.rstate.score()\n\n def get_lives(self) ->int:\n \"\"\"Access the number of lives.\n\n Returns:\n The number of lives remaining in the current state.\"\"\"\n return self.rstate.lives()\n\n def get_level(self) ->int:\n \"\"\"\n Access the number of levels.\n \n Returns:\n The number of levels completed in the current state.\"\"\"\n return self.rstate.level()\n\n def game_over(self) ->bool:\n \"\"\"\n Check for game over condition.\n\n Returns:\n ``True`` if the player has run out of lives in the current state.\n \"\"\"\n return self.rstate.game_over()\n\n def state_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python object.\"\"\"\n return self.rstate.to_json()\n\n def to_state_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\n \n Important:\n This method is deprecated; please use ``state_to_json`` instead!\n \"\"\"\n return self.state_to_json()\n\n def config_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\"\"\"\n return self.rsimulator.to_json()\n\n def write_state_json(self, js: Dict[str, Any]):\n \"\"\"Overwrite the state's JSON representation from a python dict.\n \n Parameters:\n js: the python representation of the JSON state.\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.state_from_json(js)\n\n def write_config_json(self, config_js: Dict[str, Any]):\n \"\"\"Overwrite the config's JSON representation from a python dict. \n \n It is likely that some changes will be seen until you call new_game()\n\n Parameters:\n config_js: the python representation of the config JSON\n \"\"\"\n self.rsimulator.from_json(config_js)\n self.new_game()\n\n def query_state_json(self, query: str, args: Union[Dict[str, Any], str]\n ='null') ->Dict[str, Any]:\n \"\"\"Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.\n\n Parameters:\n query: the query string to send to the game.\n args: a JSON argument to attach to the query string.\n \"\"\"\n return self.rstate.query_json(query, args)\n\n def __del__(self):\n self.rstate = None\n self.rsimulator = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def schema_for_state(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the frame State object.\"\"\"\n return self.rsimulator.schema_for_state()\n\n def schema_for_config(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the Config object.\"\"\"\n return self.rsimulator.schema_for_config()\n",
"step-2": "<mask token>\n\n\nclass State(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def render_frame_color(self, sim: Simulator) ->np.array:\n \"\"\"Generate an RGBA image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n w, h = sim.get_frame_size()\n rgba = 4\n size = h * w * rgba\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, True)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, rgba)\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Toybox(object):\n \"\"\"\n This is a stateful representation of Toybox -- since it manages memory, we provide ``__enter__`` and ``__exit__`` usage for Python's with-blocks:\n \n ```python\n with Toybox(\"amidar\") as tb:\n print(tb.get_score())\n # the 'tb' variable only lives in the block.\n ```\n\n Important:\n Note how we should use this in a with-block; this will clean up pointers and prevent memory leaks.\n\n \"\"\"\n\n def __init__(self, game_name: str, grayscale: bool=True, frameskip: int\n =0, seed: Optional[int]=None, withstate: Optional[dict]=None):\n \"\"\"\n Construct a new Toybox state/game wrapper. Use this in a with block!\n\n Parameters:\n game_name: One of \"breakout\", \"space_invaders\", \"amidar\", etc.\n grayscale: Toybox can render directly to grayscale, saving time. Default is True.\n frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.\n seed: The seed \n \"\"\"\n self.game_name = game_name\n self.frames_per_action = frameskip + 1\n self.rsimulator = Simulator(game_name)\n self.rstate = self.rsimulator.new_game()\n self.grayscale = grayscale\n if seed:\n self.set_seed(seed)\n self.new_game()\n if withstate:\n self.write_state_json(withstate)\n\n def new_game(self):\n \"\"\"\n Modify this Toybox wrapper to have a new_game state.\n\n Important:\n This discards the old state!\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.new_game()\n\n def get_height(self) ->int:\n \"\"\"Get the height of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_height()\n\n def get_width(self) ->int:\n \"\"\"Get the width of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_width()\n\n def get_legal_action_set(self) ->List[int]:\n \"\"\"Get the set of actions consumed by this game: they are ALE numbered.\"\"\"\n sim = self.rsimulator.get_simulator()\n return sim.legal_actions()\n\n def apply_ale_action(self, action_int: int):\n \"\"\"Takes an integer corresponding to an action, as specified in ALE.\n \n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n ```python\n ALE_INPUT_MAPPING = {\n 0 : \"NOOP\",\n 1 : \"FIRE\",\n 2 : \"UP\",\n 3 : \"RIGHT\",\n 4 : \"LEFT\",\n 5 : \"DOWN\",\n 6 : \"UPRIGHT\",\n 7 : \"UPLEFT\",\n 8 : \"DOWNRIGHT\",\n 9 : \"DOWNLEFT\",\n 10 : \"UPFIRE\",\n 11 : \"RIGHTFIRE\",\n 12 : \"LEFTFIRE\",\n 13 : \"DOWNFIRE\",\n 14 : \"UPRIGHTFIRE\",\n 15 : \"UPLEFTFIRE\",\n 16 : \"DOWNRIGHTFIRE\",\n 17 : \"DOWNLEFTFIRE\"\n }\n ```\n\n Parameters:\n action_int: A number from 0 to 17 inclusive.\n \"\"\"\n for _ in range(self.frames_per_action):\n if not self.rstate.get_state().apply_ale_action(action_int):\n raise ValueError('Expected to apply action, but failed: {0}'\n .format(action_int))\n\n def apply_action(self, action_input_obj: Input):\n \"\"\"Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.\n\n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n Parameters:\n action_input_obj: An instance of the [ctoybox.Input][] class.\n \"\"\"\n for _ in range(self.frames_per_action):\n self.rstate.get_state().apply_action(action_input_obj)\n\n def get_state(self) ->np.array:\n \"\"\"This state here actually refers to the graphical, RGBA or grayscale representation of the current state.\"\"\"\n return self.rstate.render_frame(self.rsimulator, self.grayscale)\n\n def set_seed(self, seed: int):\n \"\"\"Control the random number generator of the config -- only affects a new_game.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.rsimulator.set_seed(seed)\n\n def save_frame_image(self, path: str, grayscale: bool=False):\n \"\"\"Save the current frame image to a PNG file.\n \n Parameters:\n path: the filename to save to.\n grayscale: whether images should be saved in color or black & white.\n \"\"\"\n img = None\n if grayscale:\n img = Image.fromarray(self.rstate.render_frame_grayscale(self.\n rsimulator), 'L')\n else:\n img = Image.fromarray(self.rstate.render_frame_color(self.\n rsimulator), 'RGBA')\n img.save(path, format='png')\n\n def get_rgb_frame(self) ->np.array:\n \"\"\"Get the RGB frame as a numpy array.\"\"\"\n return self.rstate.render_frame_rgb(self.rsimulator)\n\n def get_score(self) ->int:\n \"\"\"Access the current score.\n\n Returns:\n The number of points earned in the current state.\"\"\"\n return self.rstate.score()\n\n def get_lives(self) ->int:\n \"\"\"Access the number of lives.\n\n Returns:\n The number of lives remaining in the current state.\"\"\"\n return self.rstate.lives()\n\n def get_level(self) ->int:\n \"\"\"\n Access the number of levels.\n \n Returns:\n The number of levels completed in the current state.\"\"\"\n return self.rstate.level()\n\n def game_over(self) ->bool:\n \"\"\"\n Check for game over condition.\n\n Returns:\n ``True`` if the player has run out of lives in the current state.\n \"\"\"\n return self.rstate.game_over()\n\n def state_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python object.\"\"\"\n return self.rstate.to_json()\n\n def to_state_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\n \n Important:\n This method is deprecated; please use ``state_to_json`` instead!\n \"\"\"\n return self.state_to_json()\n\n def config_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\"\"\"\n return self.rsimulator.to_json()\n\n def write_state_json(self, js: Dict[str, Any]):\n \"\"\"Overwrite the state's JSON representation from a python dict.\n \n Parameters:\n js: the python representation of the JSON state.\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.state_from_json(js)\n\n def write_config_json(self, config_js: Dict[str, Any]):\n \"\"\"Overwrite the config's JSON representation from a python dict. \n \n It is likely that some changes will be seen until you call new_game()\n\n Parameters:\n config_js: the python representation of the config JSON\n \"\"\"\n self.rsimulator.from_json(config_js)\n self.new_game()\n\n def query_state_json(self, query: str, args: Union[Dict[str, Any], str]\n ='null') ->Dict[str, Any]:\n \"\"\"Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.\n\n Parameters:\n query: the query string to send to the game.\n args: a JSON argument to attach to the query string.\n \"\"\"\n return self.rstate.query_json(query, args)\n\n def __del__(self):\n self.rstate = None\n self.rsimulator = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def schema_for_state(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the frame State object.\"\"\"\n return self.rsimulator.schema_for_state()\n\n def schema_for_config(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the Config object.\"\"\"\n return self.rsimulator.schema_for_config()\n",
"step-3": "<mask token>\n\n\nclass State(object):\n <mask token>\n\n def __init__(self, sim: Simulator, state=None):\n \"\"\"\n Construct a new State instance wrapper.\n\n Parameters:\n sim: The simulator responsible for this state.\n state: Optional pointer to a state to use (otherwise it will create one). \n \"\"\"\n self.sim = sim\n \"\"\"A reference to the simulator that created this state.\"\"\"\n self.__state = state or sim.__sim.new_game()\n \"\"\"The raw pointer to the state itself.\"\"\"\n self.game_name = sim.game_name\n \"\"\"The name of the game that created this state.\"\"\"\n <mask token>\n\n def __del__(self):\n self.__state = None\n self.sim = None\n <mask token>\n\n def clone(self) ->'State':\n \"\"\"Quickly make a copy of this state; should be more efficient than saving the JSON.\"\"\"\n return State(self.sim, state=self.get_state().copy())\n\n def get_state(self) ->FrameState:\n \"\"\"Get the raw state pointer.\"\"\"\n assert self.__state is not None\n return self.__state\n\n def lives(self) ->int:\n \"\"\"How many lives are remaining in the current state?\"\"\"\n return self.__state.lives()\n\n def level(self) ->int:\n \"\"\"How many levels have been completed in the current state?\"\"\"\n return self.__state.level()\n <mask token>\n <mask token>\n\n def query_json(self, query: str, args: Union[Dict[str, Any], str]='null'\n ) ->Dict[str, Any]:\n \"\"\"\n Ask a question of the Rust state; queries are currently implemented manually.\n\n Parameters:\n query: the message to send to the rust state.\n args: the arguments to send to the rust state, defaults to \"null\".\n\n Returns:\n response: A JSON response loaded to python objects.\n\n Raises:\n ValueError: if anything goes wrong with the query\n\n ```python\n with Toybox(\"breakout\") as tb:\n tb.query_json(\"bricks_remaining\")\n ```\n \"\"\"\n return json.loads(self.__state.query(json_str(query), json_str(args)))\n\n def render_frame(self, sim: Simulator, grayscale: bool=True) ->np.array:\n \"\"\"Generate an image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n grayscale: True if we want to render in grayscale rather than in color (RGBA).\n \"\"\"\n if grayscale:\n return self.render_frame_rgb(sim)\n else:\n return self.render_frame_color(sim)\n\n def render_frame_color(self, sim: Simulator) ->np.array:\n \"\"\"Generate an RGBA image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n w, h = sim.get_frame_size()\n rgba = 4\n size = h * w * rgba\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, True)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, rgba)\n <mask token>\n <mask token>\n\n def to_json(self) ->Dict[str, Any]:\n \"\"\"Get a JSON representation of the state.\"\"\"\n return json.loads(self.get_state().to_json())\n\n\nclass Toybox(object):\n \"\"\"\n This is a stateful representation of Toybox -- since it manages memory, we provide ``__enter__`` and ``__exit__`` usage for Python's with-blocks:\n \n ```python\n with Toybox(\"amidar\") as tb:\n print(tb.get_score())\n # the 'tb' variable only lives in the block.\n ```\n\n Important:\n Note how we should use this in a with-block; this will clean up pointers and prevent memory leaks.\n\n \"\"\"\n\n def __init__(self, game_name: str, grayscale: bool=True, frameskip: int\n =0, seed: Optional[int]=None, withstate: Optional[dict]=None):\n \"\"\"\n Construct a new Toybox state/game wrapper. Use this in a with block!\n\n Parameters:\n game_name: One of \"breakout\", \"space_invaders\", \"amidar\", etc.\n grayscale: Toybox can render directly to grayscale, saving time. Default is True.\n frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.\n seed: The seed \n \"\"\"\n self.game_name = game_name\n self.frames_per_action = frameskip + 1\n self.rsimulator = Simulator(game_name)\n self.rstate = self.rsimulator.new_game()\n self.grayscale = grayscale\n if seed:\n self.set_seed(seed)\n self.new_game()\n if withstate:\n self.write_state_json(withstate)\n\n def new_game(self):\n \"\"\"\n Modify this Toybox wrapper to have a new_game state.\n\n Important:\n This discards the old state!\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.new_game()\n\n def get_height(self) ->int:\n \"\"\"Get the height of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_height()\n\n def get_width(self) ->int:\n \"\"\"Get the width of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_width()\n\n def get_legal_action_set(self) ->List[int]:\n \"\"\"Get the set of actions consumed by this game: they are ALE numbered.\"\"\"\n sim = self.rsimulator.get_simulator()\n return sim.legal_actions()\n\n def apply_ale_action(self, action_int: int):\n \"\"\"Takes an integer corresponding to an action, as specified in ALE.\n \n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n ```python\n ALE_INPUT_MAPPING = {\n 0 : \"NOOP\",\n 1 : \"FIRE\",\n 2 : \"UP\",\n 3 : \"RIGHT\",\n 4 : \"LEFT\",\n 5 : \"DOWN\",\n 6 : \"UPRIGHT\",\n 7 : \"UPLEFT\",\n 8 : \"DOWNRIGHT\",\n 9 : \"DOWNLEFT\",\n 10 : \"UPFIRE\",\n 11 : \"RIGHTFIRE\",\n 12 : \"LEFTFIRE\",\n 13 : \"DOWNFIRE\",\n 14 : \"UPRIGHTFIRE\",\n 15 : \"UPLEFTFIRE\",\n 16 : \"DOWNRIGHTFIRE\",\n 17 : \"DOWNLEFTFIRE\"\n }\n ```\n\n Parameters:\n action_int: A number from 0 to 17 inclusive.\n \"\"\"\n for _ in range(self.frames_per_action):\n if not self.rstate.get_state().apply_ale_action(action_int):\n raise ValueError('Expected to apply action, but failed: {0}'\n .format(action_int))\n\n def apply_action(self, action_input_obj: Input):\n \"\"\"Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.\n\n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n Parameters:\n action_input_obj: An instance of the [ctoybox.Input][] class.\n \"\"\"\n for _ in range(self.frames_per_action):\n self.rstate.get_state().apply_action(action_input_obj)\n\n def get_state(self) ->np.array:\n \"\"\"This state here actually refers to the graphical, RGBA or grayscale representation of the current state.\"\"\"\n return self.rstate.render_frame(self.rsimulator, self.grayscale)\n\n def set_seed(self, seed: int):\n \"\"\"Control the random number generator of the config -- only affects a new_game.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.rsimulator.set_seed(seed)\n\n def save_frame_image(self, path: str, grayscale: bool=False):\n \"\"\"Save the current frame image to a PNG file.\n \n Parameters:\n path: the filename to save to.\n grayscale: whether images should be saved in color or black & white.\n \"\"\"\n img = None\n if grayscale:\n img = Image.fromarray(self.rstate.render_frame_grayscale(self.\n rsimulator), 'L')\n else:\n img = Image.fromarray(self.rstate.render_frame_color(self.\n rsimulator), 'RGBA')\n img.save(path, format='png')\n\n def get_rgb_frame(self) ->np.array:\n \"\"\"Get the RGB frame as a numpy array.\"\"\"\n return self.rstate.render_frame_rgb(self.rsimulator)\n\n def get_score(self) ->int:\n \"\"\"Access the current score.\n\n Returns:\n The number of points earned in the current state.\"\"\"\n return self.rstate.score()\n\n def get_lives(self) ->int:\n \"\"\"Access the number of lives.\n\n Returns:\n The number of lives remaining in the current state.\"\"\"\n return self.rstate.lives()\n\n def get_level(self) ->int:\n \"\"\"\n Access the number of levels.\n \n Returns:\n The number of levels completed in the current state.\"\"\"\n return self.rstate.level()\n\n def game_over(self) ->bool:\n \"\"\"\n Check for game over condition.\n\n Returns:\n ``True`` if the player has run out of lives in the current state.\n \"\"\"\n return self.rstate.game_over()\n\n def state_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python object.\"\"\"\n return self.rstate.to_json()\n\n def to_state_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\n \n Important:\n This method is deprecated; please use ``state_to_json`` instead!\n \"\"\"\n return self.state_to_json()\n\n def config_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\"\"\"\n return self.rsimulator.to_json()\n\n def write_state_json(self, js: Dict[str, Any]):\n \"\"\"Overwrite the state's JSON representation from a python dict.\n \n Parameters:\n js: the python representation of the JSON state.\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.state_from_json(js)\n\n def write_config_json(self, config_js: Dict[str, Any]):\n \"\"\"Overwrite the config's JSON representation from a python dict. \n \n It is likely that some changes will be seen until you call new_game()\n\n Parameters:\n config_js: the python representation of the config JSON\n \"\"\"\n self.rsimulator.from_json(config_js)\n self.new_game()\n\n def query_state_json(self, query: str, args: Union[Dict[str, Any], str]\n ='null') ->Dict[str, Any]:\n \"\"\"Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.\n\n Parameters:\n query: the query string to send to the game.\n args: a JSON argument to attach to the query string.\n \"\"\"\n return self.rstate.query_json(query, args)\n\n def __del__(self):\n self.rstate = None\n self.rsimulator = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def schema_for_state(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the frame State object.\"\"\"\n return self.rsimulator.schema_for_state()\n\n def schema_for_config(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the Config object.\"\"\"\n return self.rsimulator.schema_for_config()\n",
"step-4": "<mask token>\n\n\nclass Simulator(object):\n <mask token>\n\n def __init__(self, game_name, sim=None):\n \"\"\"\n Construct a new instance.\n\n Parameters:\n game_name: one of \"breakout\", \"amidar\", etc.\n sim: optionally a Rust pointer to an existing simulator.\n \"\"\"\n if sim is None:\n sim = Game(game_name)\n self.__sim = sim\n self.game_name = game_name\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n <mask token>\n\n def get_frame_size(self) ->Tuple[int, int]:\n \"\"\"Get the width in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()\n\n def get_frame_width(self) ->int:\n \"\"\"Get the width in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()[0]\n\n def get_frame_height(self) ->int:\n \"\"\"Get the height in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()[1]\n\n def get_simulator(self) ->Game:\n \"\"\"Get access to the raw simulator pointer.\"\"\"\n return self.__sim\n\n def new_game(self) ->'State':\n \"\"\"Start a new game.\"\"\"\n return State(self, self.__sim.new_game())\n <mask token>\n\n def to_json(self) ->Dict[str, Any]:\n \"\"\"Get the configuration of this simulator/config as JSON\"\"\"\n return json.loads(self.__sim.to_json())\n\n def from_json(self, config_js: Union[Dict[str, Any], str]):\n \"\"\"Mutably update this simulator/config with the replacement json.\"\"\"\n self.__sim = self.__sim.from_json(json_str(config_js))\n\n def schema_for_state(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for any state for this game.\"\"\"\n return json.loads(self.__sim.frame_schema())\n\n def schema_for_config(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for any config for this game.\"\"\"\n return json.loads(self.__sim.config_schema())\n\n\nclass State(object):\n \"\"\"\n The State object represents everything the game needs to know about any single simulated frame.\n\n You can rewind in time by storing and restoring these state representations.\n\n - Access the json: ``to_json``\n - Access the image: ``render_frame``\n \"\"\"\n\n def __init__(self, sim: Simulator, state=None):\n \"\"\"\n Construct a new State instance wrapper.\n\n Parameters:\n sim: The simulator responsible for this state.\n state: Optional pointer to a state to use (otherwise it will create one). \n \"\"\"\n self.sim = sim\n \"\"\"A reference to the simulator that created this state.\"\"\"\n self.__state = state or sim.__sim.new_game()\n \"\"\"The raw pointer to the state itself.\"\"\"\n self.game_name = sim.game_name\n \"\"\"The name of the game that created this state.\"\"\"\n\n def __enter__(self):\n return self\n\n def __del__(self):\n self.__state = None\n self.sim = None\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def clone(self) ->'State':\n \"\"\"Quickly make a copy of this state; should be more efficient than saving the JSON.\"\"\"\n return State(self.sim, state=self.get_state().copy())\n\n def get_state(self) ->FrameState:\n \"\"\"Get the raw state pointer.\"\"\"\n assert self.__state is not None\n return self.__state\n\n def lives(self) ->int:\n \"\"\"How many lives are remaining in the current state?\"\"\"\n return self.__state.lives()\n\n def level(self) ->int:\n \"\"\"How many levels have been completed in the current state?\"\"\"\n return self.__state.level()\n\n def score(self) ->int:\n \"\"\"How many points have been earned in the current state?\"\"\"\n return self.__state.score()\n\n def game_over(self):\n \"\"\"Determine whether the game has ended; i.e., the player has run out of lives.\n\n >>> assert self.lives() < 0 == self.game_over()\n \"\"\"\n return self.lives() < 0\n\n def query_json(self, query: str, args: Union[Dict[str, Any], str]='null'\n ) ->Dict[str, Any]:\n \"\"\"\n Ask a question of the Rust state; queries are currently implemented manually.\n\n Parameters:\n query: the message to send to the rust state.\n args: the arguments to send to the rust state, defaults to \"null\".\n\n Returns:\n response: A JSON response loaded to python objects.\n\n Raises:\n ValueError: if anything goes wrong with the query\n\n ```python\n with Toybox(\"breakout\") as tb:\n tb.query_json(\"bricks_remaining\")\n ```\n \"\"\"\n return json.loads(self.__state.query(json_str(query), json_str(args)))\n\n def render_frame(self, sim: Simulator, grayscale: bool=True) ->np.array:\n \"\"\"Generate an image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n grayscale: True if we want to render in grayscale rather than in color (RGBA).\n \"\"\"\n if grayscale:\n return self.render_frame_rgb(sim)\n else:\n return self.render_frame_color(sim)\n\n def render_frame_color(self, sim: Simulator) ->np.array:\n \"\"\"Generate an RGBA image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n w, h = sim.get_frame_size()\n rgba = 4\n size = h * w * rgba\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, True)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, rgba)\n\n def render_frame_rgb(self, sim: Simulator) ->np.array:\n \"\"\"Generate an RGB image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n rgba_frame = self.render_frame_color(sim)\n return rgba_frame[:, :, :3]\n\n def render_frame_grayscale(self, sim: Simulator) ->np.array:\n \"\"\"Generate a grayscale image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n w, h = sim.get_frame_size()\n depth = 1\n size = h * w * depth\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, False)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, depth)\n\n def to_json(self) ->Dict[str, Any]:\n \"\"\"Get a JSON representation of the state.\"\"\"\n return json.loads(self.get_state().to_json())\n\n\nclass Toybox(object):\n \"\"\"\n This is a stateful representation of Toybox -- since it manages memory, we provide ``__enter__`` and ``__exit__`` usage for Python's with-blocks:\n \n ```python\n with Toybox(\"amidar\") as tb:\n print(tb.get_score())\n # the 'tb' variable only lives in the block.\n ```\n\n Important:\n Note how we should use this in a with-block; this will clean up pointers and prevent memory leaks.\n\n \"\"\"\n\n def __init__(self, game_name: str, grayscale: bool=True, frameskip: int\n =0, seed: Optional[int]=None, withstate: Optional[dict]=None):\n \"\"\"\n Construct a new Toybox state/game wrapper. Use this in a with block!\n\n Parameters:\n game_name: One of \"breakout\", \"space_invaders\", \"amidar\", etc.\n grayscale: Toybox can render directly to grayscale, saving time. Default is True.\n frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.\n seed: The seed \n \"\"\"\n self.game_name = game_name\n self.frames_per_action = frameskip + 1\n self.rsimulator = Simulator(game_name)\n self.rstate = self.rsimulator.new_game()\n self.grayscale = grayscale\n if seed:\n self.set_seed(seed)\n self.new_game()\n if withstate:\n self.write_state_json(withstate)\n\n def new_game(self):\n \"\"\"\n Modify this Toybox wrapper to have a new_game state.\n\n Important:\n This discards the old state!\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.new_game()\n\n def get_height(self) ->int:\n \"\"\"Get the height of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_height()\n\n def get_width(self) ->int:\n \"\"\"Get the width of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_width()\n\n def get_legal_action_set(self) ->List[int]:\n \"\"\"Get the set of actions consumed by this game: they are ALE numbered.\"\"\"\n sim = self.rsimulator.get_simulator()\n return sim.legal_actions()\n\n def apply_ale_action(self, action_int: int):\n \"\"\"Takes an integer corresponding to an action, as specified in ALE.\n \n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n ```python\n ALE_INPUT_MAPPING = {\n 0 : \"NOOP\",\n 1 : \"FIRE\",\n 2 : \"UP\",\n 3 : \"RIGHT\",\n 4 : \"LEFT\",\n 5 : \"DOWN\",\n 6 : \"UPRIGHT\",\n 7 : \"UPLEFT\",\n 8 : \"DOWNRIGHT\",\n 9 : \"DOWNLEFT\",\n 10 : \"UPFIRE\",\n 11 : \"RIGHTFIRE\",\n 12 : \"LEFTFIRE\",\n 13 : \"DOWNFIRE\",\n 14 : \"UPRIGHTFIRE\",\n 15 : \"UPLEFTFIRE\",\n 16 : \"DOWNRIGHTFIRE\",\n 17 : \"DOWNLEFTFIRE\"\n }\n ```\n\n Parameters:\n action_int: A number from 0 to 17 inclusive.\n \"\"\"\n for _ in range(self.frames_per_action):\n if not self.rstate.get_state().apply_ale_action(action_int):\n raise ValueError('Expected to apply action, but failed: {0}'\n .format(action_int))\n\n def apply_action(self, action_input_obj: Input):\n \"\"\"Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.\n\n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n Parameters:\n action_input_obj: An instance of the [ctoybox.Input][] class.\n \"\"\"\n for _ in range(self.frames_per_action):\n self.rstate.get_state().apply_action(action_input_obj)\n\n def get_state(self) ->np.array:\n \"\"\"This state here actually refers to the graphical, RGBA or grayscale representation of the current state.\"\"\"\n return self.rstate.render_frame(self.rsimulator, self.grayscale)\n\n def set_seed(self, seed: int):\n \"\"\"Control the random number generator of the config -- only affects a new_game.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.rsimulator.set_seed(seed)\n\n def save_frame_image(self, path: str, grayscale: bool=False):\n \"\"\"Save the current frame image to a PNG file.\n \n Parameters:\n path: the filename to save to.\n grayscale: whether images should be saved in color or black & white.\n \"\"\"\n img = None\n if grayscale:\n img = Image.fromarray(self.rstate.render_frame_grayscale(self.\n rsimulator), 'L')\n else:\n img = Image.fromarray(self.rstate.render_frame_color(self.\n rsimulator), 'RGBA')\n img.save(path, format='png')\n\n def get_rgb_frame(self) ->np.array:\n \"\"\"Get the RGB frame as a numpy array.\"\"\"\n return self.rstate.render_frame_rgb(self.rsimulator)\n\n def get_score(self) ->int:\n \"\"\"Access the current score.\n\n Returns:\n The number of points earned in the current state.\"\"\"\n return self.rstate.score()\n\n def get_lives(self) ->int:\n \"\"\"Access the number of lives.\n\n Returns:\n The number of lives remaining in the current state.\"\"\"\n return self.rstate.lives()\n\n def get_level(self) ->int:\n \"\"\"\n Access the number of levels.\n \n Returns:\n The number of levels completed in the current state.\"\"\"\n return self.rstate.level()\n\n def game_over(self) ->bool:\n \"\"\"\n Check for game over condition.\n\n Returns:\n ``True`` if the player has run out of lives in the current state.\n \"\"\"\n return self.rstate.game_over()\n\n def state_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python object.\"\"\"\n return self.rstate.to_json()\n\n def to_state_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\n \n Important:\n This method is deprecated; please use ``state_to_json`` instead!\n \"\"\"\n return self.state_to_json()\n\n def config_to_json(self) ->Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\"\"\"\n return self.rsimulator.to_json()\n\n def write_state_json(self, js: Dict[str, Any]):\n \"\"\"Overwrite the state's JSON representation from a python dict.\n \n Parameters:\n js: the python representation of the JSON state.\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.state_from_json(js)\n\n def write_config_json(self, config_js: Dict[str, Any]):\n \"\"\"Overwrite the config's JSON representation from a python dict. \n \n It is likely that some changes will be seen until you call new_game()\n\n Parameters:\n config_js: the python representation of the config JSON\n \"\"\"\n self.rsimulator.from_json(config_js)\n self.new_game()\n\n def query_state_json(self, query: str, args: Union[Dict[str, Any], str]\n ='null') ->Dict[str, Any]:\n \"\"\"Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.\n\n Parameters:\n query: the query string to send to the game.\n args: a JSON argument to attach to the query string.\n \"\"\"\n return self.rstate.query_json(query, args)\n\n def __del__(self):\n self.rstate = None\n self.rsimulator = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def schema_for_state(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the frame State object.\"\"\"\n return self.rsimulator.schema_for_state()\n\n def schema_for_config(self) ->Dict[str, Any]:\n \"\"\"Get the JSON Schema for the Config object.\"\"\"\n return self.rsimulator.schema_for_config()\n",
"step-5": "from .ctoybox import Game, State as FrameState, Input\nimport numpy as np\nfrom PIL import Image\nimport json\nfrom typing import Dict, Any, List, Tuple, Union, Optional\n\n\n\ndef json_str(js: Union[Dict[str, Any], Input, str]) -> str:\n \"\"\"\n Turn an object into a JSON string -- handles dictionaries, the Input class, and JSON you've already prepared (e.g., strings).\n \"\"\"\n if type(js) is dict:\n js = json.dumps(js)\n elif type(js) is Input:\n js = json.dumps(js.__dict__)\n elif type(js) is not str:\n raise ValueError(\n \"Unknown json type: %s (only str and dict supported)\" % type(js)\n )\n return js\n\n\nclass Simulator(object):\n \"\"\"\n The Simulator is an instance of a game configuration.\n You can call new_game on it to begin.\n\n \"\"\"\n\n def __init__(self, game_name, sim=None):\n \"\"\"\n Construct a new instance.\n\n Parameters:\n game_name: one of \"breakout\", \"amidar\", etc.\n sim: optionally a Rust pointer to an existing simulator.\n \"\"\"\n if sim is None:\n sim = Game(game_name)\n self.__sim = sim\n # sim should be a pointer\n self.game_name = game_name\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def set_seed(self, seed: int):\n \"\"\"Configure the random number generator that spawns new game states.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.__sim.seed(seed)\n \n def get_frame_size(self) -> Tuple[int, int]:\n \"\"\"Get the width in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()\n\n def get_frame_width(self) -> int:\n \"\"\"Get the width in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()[0]\n\n def get_frame_height(self) -> int:\n \"\"\"Get the height in pixels of the frames this game renders.\"\"\"\n return self.__sim.frame_size()[1]\n\n def get_simulator(self) -> Game:\n \"\"\"Get access to the raw simulator pointer.\"\"\"\n return self.__sim\n\n def new_game(self) -> \"State\":\n \"\"\"Start a new game.\"\"\"\n return State(self, self.__sim.new_game())\n\n def state_from_json(self, js: Union[Dict[str, Any], str]) -> \"State\":\n \"\"\"Generate a State from the state json and this configuration.\n \n Parameters:\n js: a JSON object or string containing a serialized state.\n \"\"\"\n state: FrameState = self.__sim.new_state(json_str(js))\n return State(self, state=state)\n\n def to_json(self) -> Dict[str, Any]:\n \"\"\"Get the configuration of this simulator/config as JSON\"\"\"\n return json.loads(self.__sim.to_json())\n\n def from_json(self, config_js: Union[Dict[str, Any], str]):\n \"\"\"Mutably update this simulator/config with the replacement json.\"\"\"\n self.__sim = self.__sim.from_json(json_str(config_js))\n\n def schema_for_state(self) -> Dict[str, Any]:\n \"\"\"Get the JSON Schema for any state for this game.\"\"\"\n return json.loads(self.__sim.frame_schema())\n\n def schema_for_config(self) -> Dict[str, Any]:\n \"\"\"Get the JSON Schema for any config for this game.\"\"\"\n return json.loads(self.__sim.config_schema())\n\n\nclass State(object):\n \"\"\"\n The State object represents everything the game needs to know about any single simulated frame.\n\n You can rewind in time by storing and restoring these state representations.\n\n - Access the json: ``to_json``\n - Access the image: ``render_frame``\n \"\"\"\n\n def __init__(self, sim: Simulator, state=None):\n \"\"\"\n Construct a new State instance wrapper.\n\n Parameters:\n sim: The simulator responsible for this state.\n state: Optional pointer to a state to use (otherwise it will create one). \n \"\"\"\n self.sim = sim\n \"\"\"A reference to the simulator that created this state.\"\"\"\n self.__state = state or sim.__sim.new_game()\n \"\"\"The raw pointer to the state itself.\"\"\"\n self.game_name = sim.game_name\n \"\"\"The name of the game that created this state.\"\"\"\n\n def __enter__(self):\n return self\n\n def __del__(self):\n self.__state = None\n self.sim = None\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def clone(self) -> 'State':\n \"\"\"Quickly make a copy of this state; should be more efficient than saving the JSON.\"\"\"\n return State(self.sim, state=self.get_state().copy())\n\n def get_state(self) -> FrameState:\n \"\"\"Get the raw state pointer.\"\"\"\n assert self.__state is not None\n return self.__state\n\n def lives(self) -> int:\n \"\"\"How many lives are remaining in the current state?\"\"\"\n return self.__state.lives()\n\n def level(self) -> int:\n \"\"\"How many levels have been completed in the current state?\"\"\"\n return self.__state.level()\n\n def score(self) -> int:\n \"\"\"How many points have been earned in the current state?\"\"\"\n return self.__state.score()\n\n def game_over(self):\n \"\"\"Determine whether the game has ended; i.e., the player has run out of lives.\n\n >>> assert self.lives() < 0 == self.game_over()\n \"\"\"\n return self.lives() < 0\n\n def query_json(\n self, query: str, args: Union[Dict[str, Any], str] = \"null\"\n ) -> Dict[str, Any]:\n \"\"\"\n Ask a question of the Rust state; queries are currently implemented manually.\n\n Parameters:\n query: the message to send to the rust state.\n args: the arguments to send to the rust state, defaults to \"null\".\n\n Returns:\n response: A JSON response loaded to python objects.\n\n Raises:\n ValueError: if anything goes wrong with the query\n\n ```python\n with Toybox(\"breakout\") as tb:\n tb.query_json(\"bricks_remaining\")\n ```\n \"\"\"\n return json.loads(self.__state.query(json_str(query), json_str(args)))\n\n def render_frame(self, sim: Simulator, grayscale: bool = True) -> np.array:\n \"\"\"Generate an image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n grayscale: True if we want to render in grayscale rather than in color (RGBA).\n \"\"\"\n if grayscale:\n return self.render_frame_rgb(sim)\n else:\n return self.render_frame_color(sim)\n\n def render_frame_color(self, sim: Simulator) -> np.array:\n \"\"\"Generate an RGBA image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n (w, h) = sim.get_frame_size()\n rgba = 4\n size = h * w * rgba\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, True)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, rgba)\n\n def render_frame_rgb(self, sim: Simulator) -> np.array:\n \"\"\"Generate an RGB image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n rgba_frame = self.render_frame_color(sim)\n return rgba_frame[:, :, :3]\n\n def render_frame_grayscale(self, sim: Simulator) -> np.array:\n \"\"\"Generate a grayscale image from the current frame state object.\n\n Parameters:\n sim: the simulator to use; this tells us the width/height necessary.\n \"\"\"\n (w, h) = sim.get_frame_size()\n depth = 1\n size = h * w * depth\n frame = bytearray(size)\n self.get_state().render_into_buffer(frame, False)\n return np.asarray(frame, dtype=np.uint8).reshape(h, w, depth)\n\n def to_json(self) -> Dict[str, Any]:\n \"\"\"Get a JSON representation of the state.\"\"\"\n return json.loads(self.get_state().to_json())\n\n\n\nclass Toybox(object):\n \"\"\"\n This is a stateful representation of Toybox -- since it manages memory, we provide ``__enter__`` and ``__exit__`` usage for Python's with-blocks:\n \n ```python\n with Toybox(\"amidar\") as tb:\n print(tb.get_score())\n # the 'tb' variable only lives in the block.\n ```\n\n Important:\n Note how we should use this in a with-block; this will clean up pointers and prevent memory leaks.\n\n \"\"\"\n\n def __init__(self, \n game_name: str, \n grayscale: bool = True, \n frameskip: int = 0, \n seed: Optional[int] = None, \n withstate: Optional[dict] = None):\n \"\"\"\n Construct a new Toybox state/game wrapper. Use this in a with block!\n\n Parameters:\n game_name: One of \"breakout\", \"space_invaders\", \"amidar\", etc.\n grayscale: Toybox can render directly to grayscale, saving time. Default is True.\n frameskip: When an action is submitted, for how many extra frames should it be applied? Default is 0.\n seed: The seed \n \"\"\"\n self.game_name = game_name\n self.frames_per_action = frameskip + 1\n self.rsimulator = Simulator(game_name)\n self.rstate = self.rsimulator.new_game()\n self.grayscale = grayscale\n if seed:\n self.set_seed(seed)\n self.new_game()\n if withstate:\n self.write_state_json(withstate)\n\n def new_game(self):\n \"\"\"\n Modify this Toybox wrapper to have a new_game state.\n\n Important:\n This discards the old state!\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.new_game()\n\n def get_height(self) -> int:\n \"\"\"Get the height of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_height()\n\n def get_width(self) -> int:\n \"\"\"Get the width of the rendered game in pixels.\"\"\"\n return self.rsimulator.get_frame_width()\n\n def get_legal_action_set(self) -> List[int]:\n \"\"\"Get the set of actions consumed by this game: they are ALE numbered.\"\"\"\n sim = self.rsimulator.get_simulator()\n return sim.legal_actions()\n\n def apply_ale_action(self, action_int: int):\n \"\"\"Takes an integer corresponding to an action, as specified in ALE.\n \n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n ```python\n ALE_INPUT_MAPPING = {\n 0 : \"NOOP\",\n 1 : \"FIRE\",\n 2 : \"UP\",\n 3 : \"RIGHT\",\n 4 : \"LEFT\",\n 5 : \"DOWN\",\n 6 : \"UPRIGHT\",\n 7 : \"UPLEFT\",\n 8 : \"DOWNRIGHT\",\n 9 : \"DOWNLEFT\",\n 10 : \"UPFIRE\",\n 11 : \"RIGHTFIRE\",\n 12 : \"LEFTFIRE\",\n 13 : \"DOWNFIRE\",\n 14 : \"UPRIGHTFIRE\",\n 15 : \"UPLEFTFIRE\",\n 16 : \"DOWNRIGHTFIRE\",\n 17 : \"DOWNLEFTFIRE\"\n }\n ```\n\n Parameters:\n action_int: A number from 0 to 17 inclusive.\n \"\"\"\n # implement frameskip(k) by sending the action (k+1) times every time we have an action.\n for _ in range(self.frames_per_action):\n if not self.rstate.get_state().apply_ale_action(action_int):\n raise ValueError(\n \"Expected to apply action, but failed: {0}\".format(action_int)\n )\n\n def apply_action(self, action_input_obj: Input):\n \"\"\"Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing.\n\n This applies the action *k* times, where *k* based on the frameskip passed to the Toybox constructor.\n \n Parameters:\n action_input_obj: An instance of the [ctoybox.Input][] class.\n \"\"\"\n # implement frameskip(k) by sending the action (k+1) times every time we have an action.\n for _ in range(self.frames_per_action):\n self.rstate.get_state().apply_action(action_input_obj)\n\n def get_state(self) -> np.array:\n \"\"\"This state here actually refers to the graphical, RGBA or grayscale representation of the current state.\"\"\"\n return self.rstate.render_frame(self.rsimulator, self.grayscale)\n\n def set_seed(self, seed: int):\n \"\"\"Control the random number generator of the config -- only affects a new_game.\n \n Parameters:\n seed: a parameter to reset the built-in random number generator.\n \"\"\"\n self.rsimulator.set_seed(seed)\n # Maybe call new game here?\n\n def save_frame_image(self, path: str, grayscale: bool = False):\n \"\"\"Save the current frame image to a PNG file.\n \n Parameters:\n path: the filename to save to.\n grayscale: whether images should be saved in color or black & white.\n \"\"\"\n img = None\n if grayscale:\n img = Image.fromarray(\n self.rstate.render_frame_grayscale(self.rsimulator), \"L\"\n )\n else:\n img = Image.fromarray(\n self.rstate.render_frame_color(self.rsimulator), \"RGBA\"\n )\n img.save(path, format=\"png\")\n\n def get_rgb_frame(self) -> np.array:\n \"\"\"Get the RGB frame as a numpy array.\"\"\"\n return self.rstate.render_frame_rgb(self.rsimulator)\n\n def get_score(self) -> int:\n \"\"\"Access the current score.\n\n Returns:\n The number of points earned in the current state.\"\"\"\n return self.rstate.score()\n\n def get_lives(self) -> int:\n \"\"\"Access the number of lives.\n\n Returns:\n The number of lives remaining in the current state.\"\"\"\n return self.rstate.lives()\n\n def get_level(self) -> int:\n \"\"\"\n Access the number of levels.\n \n Returns:\n The number of levels completed in the current state.\"\"\"\n return self.rstate.level()\n\n def game_over(self) -> bool:\n \"\"\"\n Check for game over condition.\n\n Returns:\n ``True`` if the player has run out of lives in the current state.\n \"\"\"\n return self.rstate.game_over()\n\n def state_to_json(self) -> Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python object.\"\"\"\n return self.rstate.to_json()\n\n def to_state_json(self) -> Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\n \n Important:\n This method is deprecated; please use ``state_to_json`` instead!\n \"\"\"\n return self.state_to_json()\n\n def config_to_json(self) -> Dict[str, Any]:\n \"\"\"Get the state's JSON representation as a python dict.\"\"\"\n return self.rsimulator.to_json()\n\n def write_state_json(self, js: Dict[str, Any]):\n \"\"\"Overwrite the state's JSON representation from a python dict.\n \n Parameters:\n js: the python representation of the JSON state.\n \"\"\"\n old_state = self.rstate\n del old_state\n self.rstate = self.rsimulator.state_from_json(js)\n\n def write_config_json(self, config_js: Dict[str, Any]):\n \"\"\"Overwrite the config's JSON representation from a python dict. \n \n It is likely that some changes will be seen until you call new_game()\n\n Parameters:\n config_js: the python representation of the config JSON\n \"\"\"\n # from_json replaces simulator!\n self.rsimulator.from_json(config_js)\n # new_game replaces state!\n self.new_game()\n\n def query_state_json(\n self, query: str, args: Union[Dict[str, Any], str] = \"null\"\n ) -> Dict[str, Any]:\n \"\"\"Submit a query to the game's query system -- faster than accessing the whole JSON for quick introspection.\n\n Parameters:\n query: the query string to send to the game.\n args: a JSON argument to attach to the query string.\n \"\"\"\n return self.rstate.query_json(query, args)\n\n def __del__(self):\n self.rstate = None\n self.rsimulator = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.__del__()\n\n def schema_for_state(self) -> Dict[str, Any]:\n \"\"\"Get the JSON Schema for the frame State object.\"\"\"\n return self.rsimulator.schema_for_state()\n\n def schema_for_config(self) -> Dict[str, Any]:\n \"\"\"Get the JSON Schema for the Config object.\"\"\"\n return self.rsimulator.schema_for_config()\n",
"step-ids": [
27,
30,
39,
59,
65
]
}
|
[
27,
30,
39,
59,
65
] |
import os
import sys
import random
import string
trainingData = open('./Data.txt').readlines()
# Used for storing the Markov states
table = {}
# Stores all the words
words = []
# The size of the tuple that represents the Markov State
ChainLength = 2
# Length of hte output chain
Size = int(sys.argv[1])
if(len(sys.argv) >= 3): ChainLength = int(sys.argv[2])
# Read in data and split into words
for line in trainingData:
for word in line.split():
#word = word.translate(string.maketrans("",""), string.punctuation)
words.append(word)
# For each set of words
for idx in xrange(0,len(words)-ChainLength):
# Now we have ChainLength+1 amount of words
ws = words[idx:idx+ChainLength+1]
# Construct our table
# For example Chain Lenght of 2
# A valid key val pair would be
# table[('see', 'spot')] = ['run','play']
# Indicating that if you are in teh state of ('see', 'spot') the next word has a 50% chance of being run and a 50% chance of being play
key = tuple(ws[:ChainLength])
val = ws[ChainLength]
if key in table:
table[key].append(val)
else:
table[key] = [val]
seed = random.randint(0, len(words)-ChainLength+1)
ws = words[seed:seed+ChainLength]
gen = []
for i in xrange(0,int(sys.argv[1])):
gen.append(ws[0])
# Actually find the next word randomally given the current state Ie: the tuple of words
val = random.choice(table[tuple(ws)])
ws.append(val)
ws.pop(0)
print ' '.join(gen)
|
normal
|
{
"blob_id": "379ab72f5cc74cf6ed4319fff76437ce84aaca23",
"index": 4185,
"step-1": "import os\nimport sys\nimport random\nimport string\n\n\ntrainingData = open('./Data.txt').readlines()\n\n# Used for storing the Markov states\ntable = {} \n\n# Stores all the words\nwords = []\n\n# The size of the tuple that represents the Markov State\nChainLength = 2\n# Length of hte output chain\nSize = int(sys.argv[1])\nif(len(sys.argv) >= 3): ChainLength = int(sys.argv[2])\n\n# Read in data and split into words\nfor line in trainingData:\n\tfor word in line.split():\n\t\t#word = word.translate(string.maketrans(\"\",\"\"), string.punctuation)\n\t\twords.append(word)\n# For each set of words\nfor idx in xrange(0,len(words)-ChainLength):\n\t# Now we have ChainLength+1 amount of words\n\tws = words[idx:idx+ChainLength+1]\n\t\n\t# Construct our table\n\t# For example Chain Lenght of 2\n\t# A valid key val pair would be \n # table[('see', 'spot')] = ['run','play']\n # Indicating that if you are in teh state of ('see', 'spot') the next word has a 50% chance of being run and a 50% chance of being play\n\tkey = tuple(ws[:ChainLength])\n\tval = ws[ChainLength]\n\tif key in table:\n\t\ttable[key].append(val)\n\telse:\n\t\ttable[key] = [val]\n\t\n\nseed = random.randint(0, len(words)-ChainLength+1)\nws = words[seed:seed+ChainLength] \ngen = []\nfor i in xrange(0,int(sys.argv[1])):\n\tgen.append(ws[0])\n\t# Actually find the next word randomally given the current state Ie: the tuple of words \n\tval = random.choice(table[tuple(ws)])\n\tws.append(val)\n\tws.pop(0)\n\nprint ' '.join(gen)\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from django.shortcuts import render, render_to_response, get_object_or_404, redirect
from .models import Club
from .forms import InputForm
# Create your views here.
def base(request):
return render(request, 'VICHealth_app/base.html')
def index(request):
return render(request, 'VICHealth_app/index.html')
def check_activity_level(request):
return render(request, 'VICHealth_app/check_activity_level.html')
def health_tips(request):
return render(request, 'VICHealth_app/health_tips.html')
def sub_info(request):
club=Club.objects.all()
form=InputForm()
context = { "club":club, "form":form }
return render(request, 'VICHealth_app/sub_info.html', context)
|
normal
|
{
"blob_id": "b0818b545ab47c27c705f2ccfa3b9edb741602f7",
"index": 4757,
"step-1": "<mask token>\n\n\ndef base(request):\n return render(request, 'VICHealth_app/base.html')\n\n\n<mask token>\n\n\ndef check_activity_level(request):\n return render(request, 'VICHealth_app/check_activity_level.html')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef base(request):\n return render(request, 'VICHealth_app/base.html')\n\n\ndef index(request):\n return render(request, 'VICHealth_app/index.html')\n\n\ndef check_activity_level(request):\n return render(request, 'VICHealth_app/check_activity_level.html')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef base(request):\n return render(request, 'VICHealth_app/base.html')\n\n\ndef index(request):\n return render(request, 'VICHealth_app/index.html')\n\n\ndef check_activity_level(request):\n return render(request, 'VICHealth_app/check_activity_level.html')\n\n\ndef health_tips(request):\n return render(request, 'VICHealth_app/health_tips.html')\n\n\ndef sub_info(request):\n club = Club.objects.all()\n form = InputForm()\n context = {'club': club, 'form': form}\n return render(request, 'VICHealth_app/sub_info.html', context)\n",
"step-4": "from django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom .models import Club\nfrom .forms import InputForm\n\n\ndef base(request):\n return render(request, 'VICHealth_app/base.html')\n\n\ndef index(request):\n return render(request, 'VICHealth_app/index.html')\n\n\ndef check_activity_level(request):\n return render(request, 'VICHealth_app/check_activity_level.html')\n\n\ndef health_tips(request):\n return render(request, 'VICHealth_app/health_tips.html')\n\n\ndef sub_info(request):\n club = Club.objects.all()\n form = InputForm()\n context = {'club': club, 'form': form}\n return render(request, 'VICHealth_app/sub_info.html', context)\n",
"step-5": "from django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom .models import Club\nfrom .forms import InputForm\n\n# Create your views here.\ndef base(request):\n return render(request, 'VICHealth_app/base.html')\n\ndef index(request):\n return render(request, 'VICHealth_app/index.html')\n\ndef check_activity_level(request):\n return render(request, 'VICHealth_app/check_activity_level.html')\n\ndef health_tips(request):\n return render(request, 'VICHealth_app/health_tips.html')\n\ndef sub_info(request):\n club=Club.objects.all()\n form=InputForm()\n\n\n context = { \"club\":club, \"form\":form }\n return render(request, 'VICHealth_app/sub_info.html', context)\n",
"step-ids": [
2,
3,
5,
6,
7
]
}
|
[
2,
3,
5,
6,
7
] |
import math
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def create_point(self):
point = [self.x, self.y]
return point
@staticmethod
def calculate_distance(point_1: [], point_2: []):
side_a = abs(point_1.x - point_2.x)
side_b = abs(point_1.y - point_2.y)
side_c = math.sqrt(side_a ** 2 + side_b ** 2)
return side_c
n = int(input())
total_points = []
while n > 0:
n -= 1
a, b = [int(x) for x in input().split()]
point = Point(a, b).create_point()
total_points.append(point)
segment_list = []
for index_1 in range(len(total_points)):
for index_2 in range(len(total_points)):
if index_1 != index_2:
segment = Point(total_points[index_1][0], total_points[index_2][0])
segment_list.append(segment)
|
normal
|
{
"blob_id": "cda7595e46528739cad49a5d62a80bc7b2087157",
"index": 1911,
"step-1": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n def create_point(self):\n point = [self.x, self.y]\n return point\n\n @staticmethod\n def calculate_distance(point_1: [], point_2: []):\n side_a = abs(point_1.x - point_2.x)\n side_b = abs(point_1.y - point_2.y)\n side_c = math.sqrt(side_a ** 2 + side_b ** 2)\n return side_c\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n def create_point(self):\n point = [self.x, self.y]\n return point\n\n @staticmethod\n def calculate_distance(point_1: [], point_2: []):\n side_a = abs(point_1.x - point_2.x)\n side_b = abs(point_1.y - point_2.y)\n side_c = math.sqrt(side_a ** 2 + side_b ** 2)\n return side_c\n\n\n<mask token>\nwhile n > 0:\n n -= 1\n a, b = [int(x) for x in input().split()]\n point = Point(a, b).create_point()\n total_points.append(point)\n<mask token>\nfor index_1 in range(len(total_points)):\n for index_2 in range(len(total_points)):\n if index_1 != index_2:\n segment = Point(total_points[index_1][0], total_points[index_2][0])\n segment_list.append(segment)\n",
"step-3": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n def create_point(self):\n point = [self.x, self.y]\n return point\n\n @staticmethod\n def calculate_distance(point_1: [], point_2: []):\n side_a = abs(point_1.x - point_2.x)\n side_b = abs(point_1.y - point_2.y)\n side_c = math.sqrt(side_a ** 2 + side_b ** 2)\n return side_c\n\n\nn = int(input())\ntotal_points = []\nwhile n > 0:\n n -= 1\n a, b = [int(x) for x in input().split()]\n point = Point(a, b).create_point()\n total_points.append(point)\nsegment_list = []\nfor index_1 in range(len(total_points)):\n for index_2 in range(len(total_points)):\n if index_1 != index_2:\n segment = Point(total_points[index_1][0], total_points[index_2][0])\n segment_list.append(segment)\n",
"step-4": "import math\n\n\nclass Point:\n\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n def create_point(self):\n point = [self.x, self.y]\n return point\n\n @staticmethod\n def calculate_distance(point_1: [], point_2: []):\n side_a = abs(point_1.x - point_2.x)\n side_b = abs(point_1.y - point_2.y)\n side_c = math.sqrt(side_a ** 2 + side_b ** 2)\n return side_c\n\n\nn = int(input())\ntotal_points = []\nwhile n > 0:\n n -= 1\n a, b = [int(x) for x in input().split()]\n point = Point(a, b).create_point()\n total_points.append(point)\nsegment_list = []\nfor index_1 in range(len(total_points)):\n for index_2 in range(len(total_points)):\n if index_1 != index_2:\n segment = Point(total_points[index_1][0], total_points[index_2][0])\n segment_list.append(segment)\n",
"step-5": null,
"step-ids": [
4,
5,
6,
7
]
}
|
[
4,
5,
6,
7
] |
__author__ = 'dongdaqing'
import threading,time
class MyThread(threading.Thread):
def __init__(self, name=None):
threading.Thread.__init__(self)
self.name = name
def run(self):
print time.strftime('%Y-%m-%d %H-%M-%S',time.localtime())
print self.name
def test():
for i in range(0, 100):
t = MyThread("thread_" + str(i))
t.start()
if __name__=='__main__':
test()
|
normal
|
{
"blob_id": "9c277030ef384d60e62c2c48e38a1271a43826d6",
"index": 3557,
"step-1": "__author__ = 'dongdaqing'\n\nimport threading,time\nclass MyThread(threading.Thread):\n def __init__(self, name=None):\n threading.Thread.__init__(self)\n self.name = name\n\n def run(self):\n print time.strftime('%Y-%m-%d %H-%M-%S',time.localtime())\n print self.name\n\ndef test():\n for i in range(0, 100):\n t = MyThread(\"thread_\" + str(i))\n t.start()\n\nif __name__=='__main__':\n test()",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
#!/usr/bin/python3
# encoding: utf-8
"""
@author: ShuoChang
@license: (C) MIT.
@contact: [email protected]
@software: CRNN_STN_SEQ
@file: decoder_base.py
@time: 2019/7/22 17:21
@blog: https://www.zhihu.com/people/chang-shuo-59/activities
"""
from abc import ABCMeta
from abc import abstractmethod
class DecoderBase(object):
"""
Base model for decoder
"""
__metaclass__ = ABCMeta
def __init__(self):
self._predictor = 'decoder'
self._label = None
pass
@abstractmethod
def set_label(self, label):
self._label = label
@abstractmethod
def predict(self, input_data):
pass
@abstractmethod
def loss(self, input_data):
pass
@abstractmethod
def sequence_dist(self, input_data):
pass
|
normal
|
{
"blob_id": "0d8a26ef4077b40e8255d5bb2ce9217b51118780",
"index": 7364,
"step-1": "<mask token>\n\n\nclass DecoderBase(object):\n <mask token>\n <mask token>\n\n def __init__(self):\n self._predictor = 'decoder'\n self._label = None\n pass\n\n @abstractmethod\n def set_label(self, label):\n self._label = label\n <mask token>\n\n @abstractmethod\n def loss(self, input_data):\n pass\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass DecoderBase(object):\n <mask token>\n <mask token>\n\n def __init__(self):\n self._predictor = 'decoder'\n self._label = None\n pass\n\n @abstractmethod\n def set_label(self, label):\n self._label = label\n <mask token>\n\n @abstractmethod\n def loss(self, input_data):\n pass\n\n @abstractmethod\n def sequence_dist(self, input_data):\n pass\n",
"step-3": "<mask token>\n\n\nclass DecoderBase(object):\n <mask token>\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self._predictor = 'decoder'\n self._label = None\n pass\n\n @abstractmethod\n def set_label(self, label):\n self._label = label\n\n @abstractmethod\n def predict(self, input_data):\n pass\n\n @abstractmethod\n def loss(self, input_data):\n pass\n\n @abstractmethod\n def sequence_dist(self, input_data):\n pass\n",
"step-4": "<mask token>\n\n\nclass DecoderBase(object):\n \"\"\"\n Base model for decoder\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self._predictor = 'decoder'\n self._label = None\n pass\n\n @abstractmethod\n def set_label(self, label):\n self._label = label\n\n @abstractmethod\n def predict(self, input_data):\n pass\n\n @abstractmethod\n def loss(self, input_data):\n pass\n\n @abstractmethod\n def sequence_dist(self, input_data):\n pass\n",
"step-5": "#!/usr/bin/python3\n# encoding: utf-8\n\"\"\"\n@author: ShuoChang\n@license: (C) MIT.\n@contact: [email protected]\n@software: CRNN_STN_SEQ\n@file: decoder_base.py\n@time: 2019/7/22 17:21\n@blog: https://www.zhihu.com/people/chang-shuo-59/activities\n\"\"\"\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\n\n\nclass DecoderBase(object):\n \"\"\"\n Base model for decoder\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self._predictor = 'decoder'\n self._label = None\n pass\n\n @abstractmethod\n def set_label(self, label):\n self._label = label\n\n @abstractmethod\n def predict(self, input_data):\n pass\n\n @abstractmethod\n def loss(self, input_data):\n pass\n\n @abstractmethod\n def sequence_dist(self, input_data):\n pass\n",
"step-ids": [
4,
5,
7,
8,
10
]
}
|
[
4,
5,
7,
8,
10
] |
from selenium import webdriver;
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("http://demo.automationtesting.in/Register.html")
interactions = driver.find_element_by_xpath("//a[@class='dropdown-toggle' and contains(text(),'Interactions ')]")
drag = driver.find_element_by_xpath("//a[@class='dropdown-toggle' and contains(text(),'Drag and Drop ')]")
static = driver.find_element_by_xpath("//ul[@class='childmenu ']//a[contains(text(),'Static ')]")
actions = ActionChains(driver)
actions.move_to_element(interactions).move_to_element(drag).move_to_element(static).click().perform()
time.sleep(5)
driver.get("http://testautomationpractice.blogspot.com/")
ele = driver.find_element_by_xpath("//*[@id='HTML10']/div[1]/button")
actions.double_click(ele).perform()
time.sleep(5)
driver.close()
|
normal
|
{
"blob_id": "1a1a217b382f3c58c6c4cd3c1c3f556ae945f5a7",
"index": 7850,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndriver.implicitly_wait(10)\ndriver.maximize_window()\ndriver.get('http://demo.automationtesting.in/Register.html')\n<mask token>\nactions.move_to_element(interactions).move_to_element(drag).move_to_element(\n static).click().perform()\ntime.sleep(5)\ndriver.get('http://testautomationpractice.blogspot.com/')\n<mask token>\nactions.double_click(ele).perform()\ntime.sleep(5)\ndriver.close()\n",
"step-3": "<mask token>\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\ndriver.maximize_window()\ndriver.get('http://demo.automationtesting.in/Register.html')\ninteractions = driver.find_element_by_xpath(\n \"//a[@class='dropdown-toggle' and contains(text(),'Interactions ')]\")\ndrag = driver.find_element_by_xpath(\n \"//a[@class='dropdown-toggle' and contains(text(),'Drag and Drop ')]\")\nstatic = driver.find_element_by_xpath(\n \"//ul[@class='childmenu ']//a[contains(text(),'Static ')]\")\nactions = ActionChains(driver)\nactions.move_to_element(interactions).move_to_element(drag).move_to_element(\n static).click().perform()\ntime.sleep(5)\ndriver.get('http://testautomationpractice.blogspot.com/')\nele = driver.find_element_by_xpath(\"//*[@id='HTML10']/div[1]/button\")\nactions.double_click(ele).perform()\ntime.sleep(5)\ndriver.close()\n",
"step-4": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.keys import Keys\nimport time\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\ndriver.maximize_window()\ndriver.get('http://demo.automationtesting.in/Register.html')\ninteractions = driver.find_element_by_xpath(\n \"//a[@class='dropdown-toggle' and contains(text(),'Interactions ')]\")\ndrag = driver.find_element_by_xpath(\n \"//a[@class='dropdown-toggle' and contains(text(),'Drag and Drop ')]\")\nstatic = driver.find_element_by_xpath(\n \"//ul[@class='childmenu ']//a[contains(text(),'Static ')]\")\nactions = ActionChains(driver)\nactions.move_to_element(interactions).move_to_element(drag).move_to_element(\n static).click().perform()\ntime.sleep(5)\ndriver.get('http://testautomationpractice.blogspot.com/')\nele = driver.find_element_by_xpath(\"//*[@id='HTML10']/div[1]/button\")\nactions.double_click(ele).perform()\ntime.sleep(5)\ndriver.close()\n",
"step-5": "from selenium import webdriver;\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\ndriver.maximize_window()\ndriver.get(\"http://demo.automationtesting.in/Register.html\")\ninteractions = driver.find_element_by_xpath(\"//a[@class='dropdown-toggle' and contains(text(),'Interactions ')]\")\ndrag = driver.find_element_by_xpath(\"//a[@class='dropdown-toggle' and contains(text(),'Drag and Drop ')]\")\nstatic = driver.find_element_by_xpath(\"//ul[@class='childmenu ']//a[contains(text(),'Static ')]\")\nactions = ActionChains(driver)\nactions.move_to_element(interactions).move_to_element(drag).move_to_element(static).click().perform()\ntime.sleep(5)\ndriver.get(\"http://testautomationpractice.blogspot.com/\")\nele = driver.find_element_by_xpath(\"//*[@id='HTML10']/div[1]/button\")\nactions.double_click(ele).perform()\ntime.sleep(5)\ndriver.close()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# Generated by Django 3.1.4 on 2020-12-11 17:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0016_auto_20201211_2158'),
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=256)),
('date', models.DateTimeField(auto_now_add=True)),
('std', models.IntegerField()),
('description', models.TextField(blank=True)),
('asker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='core.person')),
],
),
]
|
normal
|
{
"blob_id": "e8011e98da342e501070febf421e9f8d0b74d64e",
"index": 6813,
"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', '0016_auto_20201211_2158')]\n operations = [migrations.CreateModel(name='Question', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('title', models.CharField(max_length=\n 256)), ('date', models.DateTimeField(auto_now_add=True)), ('std',\n models.IntegerField()), ('description', models.TextField(blank=True\n )), ('asker', models.ForeignKey(on_delete=django.db.models.deletion\n .CASCADE, related_name='questions', to='core.person'))])]\n",
"step-4": "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [('core', '0016_auto_20201211_2158')]\n operations = [migrations.CreateModel(name='Question', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('title', models.CharField(max_length=\n 256)), ('date', models.DateTimeField(auto_now_add=True)), ('std',\n models.IntegerField()), ('description', models.TextField(blank=True\n )), ('asker', models.ForeignKey(on_delete=django.db.models.deletion\n .CASCADE, related_name='questions', to='core.person'))])]\n",
"step-5": "# Generated by Django 3.1.4 on 2020-12-11 17:50\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0016_auto_20201211_2158'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=256)),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('std', models.IntegerField()),\n ('description', models.TextField(blank=True)),\n ('asker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='core.person')),\n ],\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# 把函数视作对象
def factorial(n):
"""returns n!"""
return 1 if n < 2 else n * factorial(n - 1)
fact = factorial
print(list(map(fact, range(6)))) # 构建 0! 和 5! 的一个阶乘列表。
print([fact(n) for n in range(6)]) # 使用列表推导执行相同的操作。
# filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
# 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,
# 最后将返回 True 的元素放到新列表中。
print(list(map(factorial, filter(lambda n: n % 2, range(6))))) # 使用 map 和 filter 计算直到 5! 的奇数阶乘列表。
print([factorial(n) for n in range(6) if n % 2]) # 使用列表推导做相同的工作,换掉 map 和 filter,并避免了使用 lambda 表达式。
|
normal
|
{
"blob_id": "4411c81351ac76d72512faaa6b498cd577815691",
"index": 2572,
"step-1": "<mask token>\n",
"step-2": "def factorial(n):\n \"\"\"returns n!\"\"\"\n return 1 if n < 2 else n * factorial(n - 1)\n\n\n<mask token>\n",
"step-3": "def factorial(n):\n \"\"\"returns n!\"\"\"\n return 1 if n < 2 else n * factorial(n - 1)\n\n\n<mask token>\nprint(list(map(fact, range(6))))\nprint([fact(n) for n in range(6)])\nprint(list(map(factorial, filter(lambda n: n % 2, range(6)))))\nprint([factorial(n) for n in range(6) if n % 2])\n",
"step-4": "def factorial(n):\n \"\"\"returns n!\"\"\"\n return 1 if n < 2 else n * factorial(n - 1)\n\n\nfact = factorial\nprint(list(map(fact, range(6))))\nprint([fact(n) for n in range(6)])\nprint(list(map(factorial, filter(lambda n: n % 2, range(6)))))\nprint([factorial(n) for n in range(6) if n % 2])\n",
"step-5": "# 把函数视作对象\r\ndef factorial(n):\r\n \"\"\"returns n!\"\"\"\r\n return 1 if n < 2 else n * factorial(n - 1)\r\n\r\n\r\nfact = factorial\r\n\r\nprint(list(map(fact, range(6)))) # 构建 0! 和 5! 的一个阶乘列表。\r\n\r\nprint([fact(n) for n in range(6)]) # 使用列表推导执行相同的操作。\r\n\r\n# filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。\r\n# 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,\r\n# 最后将返回 True 的元素放到新列表中。\r\nprint(list(map(factorial, filter(lambda n: n % 2, range(6))))) # 使用 map 和 filter 计算直到 5! 的奇数阶乘列表。\r\n\r\nprint([factorial(n) for n in range(6) if n % 2]) # 使用列表推导做相同的工作,换掉 map 和 filter,并避免了使用 lambda 表达式。\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.action_chains import ActionChains
import time
import json
import re
import os
import datetime
###########################################################################
driver_path = "/home/arnab/Codes/00_Libs/chromedriver_linux64/chromedriver"
###########################################################################
def simplify_string(inp):
inp = inp.lower().strip()
inp = re.sub(r'[^A-Za-z0-9]', '_', inp)
return inp
def makeDirectory(path):
print("creating directory " + path)
try:
os.mkdir(path)
except FileExistsError:
pass
def initialize(url, browser=None):
if(browser == None):
print("creating browser for the first and last time")
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
# chrome_options.add_argument('--no-sandbox')
# chrome_options.add_argument('--disable-dev-shm-usage')
browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)
browser.implicitly_wait(3)
browser.get(url)
browser.implicitly_wait(3)
return browser
def performClick(driver, element):
driver.execute_script("arguments[0].click();", element)
def getSoupFromElement(element):
html = element.get_attribute('innerHTML')
soup = BeautifulSoup(html, 'html.parser')
return soup
def processPageAnchor(anchorElem):
url = anchorElem['href']
text = anchorElem.find(text=True).strip()
return url, text
def getCastInfo(page_soup):
cast_table = page_soup.find("table", {"class": "cast_list"})
# print(" >>>>>>>>>>>>>>>>>>>>>>>>> ")
# print(cast_table.prettify())
cast_elem_arr = cast_table.findAll("tr", {"class": "odd"}) + cast_table.findAll("tr", {"class": "even"})
# print(len(cast_elem_arr))
# print(cast_elem_arr[0].prettify())
cast_and_character = []
for cast_elem in cast_elem_arr:
td_arr = cast_elem.findAll("td")
if(len(td_arr) < 4):
continue
# print(td_arr[1].prettify())
actor_elem = td_arr[1]
actor_anchor = actor_elem.find("a")
actor_url, actor_name = processPageAnchor(actor_anchor)
actor_info = {
"@type" : "Person",
"url" : actor_url,
"name" : actor_name
}
# print(actor_info)
# print(td_arr[3].prettify())
character_elem = td_arr[3]
character_info = []
character_anchor_arr = character_elem.findAll('a')
for character_anchor in character_anchor_arr:
character_url, character_name = processPageAnchor(character_anchor)
character_info.append({
"url" : character_url,
"name" : character_name
})
# print(character_info)
cast_and_character.append({
"actor" : actor_info,
"character_and_episodes" : character_info
})
# print(cast_and_character)
# print(len(cast_and_character))
return cast_and_character
def checkvalidtext(txt):
if(txt.isspace()):
return False
arr = ["|", "See more", "\u00bb", ","]
if txt in arr:
return False
if txt.strip() in arr:
return False
return True
def filter(arr):
ret = []
attr = "#"
for val in arr:
if(checkvalidtext(val) == False):
continue
if(val[-1] == ":"):
attr = val[0:-1]
continue
ret.append(val.strip())
return attr, ret
def parseDetailInfo(page_soup):
detail_elem = page_soup.find("div", {
'class': 'article',
'id': "titleDetails"
})
divs = detail_elem.findAll("div")
details = {}
for div in divs:
vrr = div.findAll()
attr, value = filter(div.findAll(text=True))
if(attr == "Official Sites" or attr == "#" or attr == "Color"):
continue
# print(attr, " >>>>>> ", value)
details[attr] = value
return details
def processOneMovie(movie_url, folder_path, driver, try_cnt = 0):
# if(True):
try:
if(try_cnt == 0):
driver = initialize(movie_url, driver)
page_html = driver.page_source
page_soup = BeautifulSoup(page_html, 'html.parser')
# print(page_soup.prettify())
query_result = page_soup.find("script", {"type": "application/ld+json"})
# print(query_result.string)
meta_data = json.loads(query_result.string)
try:
meta_data["cast_and_character"] = getCastInfo(page_soup)
except:
meta_data["cast_and_character"] = "Error loading cast information -- checked {}".format(datetime.datetime.now())
meta_data['details'] = parseDetailInfo(page_soup)
movie_id = meta_data["url"].split('/')[-2]
movie_name = meta_data["name"]
file_name = "{}__{}".format(movie_id, simplify_string(movie_name)) + ".json"
# print(file_name)
# print(meta_data)
with open(folder_path + "/" + file_name, "w") as f:
json.dump(meta_data, f)
print("saved movie < {} > to < {} >".format(movie_name, file_name))
return True
except:
if(try_cnt == 17):
print("Error loading movie -- skip this")
return False
print("maybe temporary internet connection problem. trying again < {} >".format(try_cnt + 1))
driver.refresh()
time.sleep(2)
return processOneMovie(movie_url, folder_path, driver, try_cnt+1)
#############################################################################################################
url_root = "https://www.imdb.com/"
save_path = "MOVIES"
summary_path = "IMDB_SUMMARY/SUMMARY_DATA"
frm = 1
rng = 250
limit = 600000 # set it to -1 for all processing
#############################################################################################################
makeDirectory(save_path)
summary_files = sorted(os.listdir(summary_path))
driver = initialize(url_root)
def loadFailCases():
try:
with open("fail_cases.json", "r") as f:
fail_cases = json.load(f)
except:
print("Could not find fail_cases.json -- initializing with empty folder")
fail_cases = []
return fail_cases
print(summary_files)
# for summary in summary_files:
while(True):
summary = "{} - {}.json".format(frm, frm+rng-1)
if(summary not in summary_files):
print("Could not fild summary file < {} >".format(summary))
break
print("Now processing < {} >".format(summary))
folder_name = summary.split('.')[0]
folder_path = save_path + "/" + folder_name
makeDirectory(folder_path)
with open(summary_path + "/" + summary) as f:
movie_arr = json.load(f)
# print(type(movie_arr))
# print(movie_arr)
process_cnt = 0
st = 0
# if(frm == 65251):
# st = 173
for idx in range(st, len(movie_arr)):
movie = movie_arr[idx]
# print(movie["link"])
movie_url = url_root + movie["link"]
success = processOneMovie(movie_url, folder_path, driver)
if(success == False):
fail_cases = loadFailCases()
fail_cases.append(movie)
with open("fail_cases.json", "w") as f:
json.dump(fail_cases, f)
process_cnt += 1
print(">>>>>>>>>>>>>>>>>>>>>>>>>> processed {} of {} --- of :: {}".format(st + process_cnt, len(movie_arr), summary))
frm += rng
if limit == -1:
continue
elif (frm > limit):
break
|
normal
|
{
"blob_id": "43b9d308bb8d2b38c5f539e8700f5c2d8fe2287d",
"index": 2157,
"step-1": "<mask token>\n\n\ndef simplify_string(inp):\n inp = inp.lower().strip()\n inp = re.sub('[^A-Za-z0-9]', '_', inp)\n return inp\n\n\ndef makeDirectory(path):\n print('creating directory ' + path)\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\n\ndef initialize(url, browser=None):\n if browser == None:\n print('creating browser for the first and last time')\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n browser.implicitly_wait(3)\n browser.get(url)\n browser.implicitly_wait(3)\n return browser\n\n\n<mask token>\n\n\ndef getCastInfo(page_soup):\n cast_table = page_soup.find('table', {'class': 'cast_list'})\n cast_elem_arr = cast_table.findAll('tr', {'class': 'odd'}\n ) + cast_table.findAll('tr', {'class': 'even'})\n cast_and_character = []\n for cast_elem in cast_elem_arr:\n td_arr = cast_elem.findAll('td')\n if len(td_arr) < 4:\n continue\n actor_elem = td_arr[1]\n actor_anchor = actor_elem.find('a')\n actor_url, actor_name = processPageAnchor(actor_anchor)\n actor_info = {'@type': 'Person', 'url': actor_url, 'name': actor_name}\n character_elem = td_arr[3]\n character_info = []\n character_anchor_arr = character_elem.findAll('a')\n for character_anchor in character_anchor_arr:\n character_url, character_name = processPageAnchor(character_anchor)\n character_info.append({'url': character_url, 'name':\n character_name})\n cast_and_character.append({'actor': actor_info,\n 'character_and_episodes': character_info})\n return cast_and_character\n\n\ndef checkvalidtext(txt):\n if txt.isspace():\n return False\n arr = ['|', 'See more', '»', ',']\n if txt in arr:\n return False\n if txt.strip() in arr:\n return False\n return True\n\n\ndef filter(arr):\n ret = []\n attr = '#'\n for val in arr:\n if checkvalidtext(val) == False:\n continue\n if val[-1] == ':':\n attr = val[0:-1]\n continue\n ret.append(val.strip())\n return attr, ret\n\n\ndef parseDetailInfo(page_soup):\n detail_elem = page_soup.find('div', {'class': 'article', 'id':\n 'titleDetails'})\n divs = detail_elem.findAll('div')\n details = {}\n for div in divs:\n vrr = div.findAll()\n attr, value = filter(div.findAll(text=True))\n if attr == 'Official Sites' or attr == '#' or attr == 'Color':\n continue\n details[attr] = value\n return details\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef simplify_string(inp):\n inp = inp.lower().strip()\n inp = re.sub('[^A-Za-z0-9]', '_', inp)\n return inp\n\n\ndef makeDirectory(path):\n print('creating directory ' + path)\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\n\ndef initialize(url, browser=None):\n if browser == None:\n print('creating browser for the first and last time')\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n browser.implicitly_wait(3)\n browser.get(url)\n browser.implicitly_wait(3)\n return browser\n\n\n<mask token>\n\n\ndef getSoupFromElement(element):\n html = element.get_attribute('innerHTML')\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\n\ndef processPageAnchor(anchorElem):\n url = anchorElem['href']\n text = anchorElem.find(text=True).strip()\n return url, text\n\n\ndef getCastInfo(page_soup):\n cast_table = page_soup.find('table', {'class': 'cast_list'})\n cast_elem_arr = cast_table.findAll('tr', {'class': 'odd'}\n ) + cast_table.findAll('tr', {'class': 'even'})\n cast_and_character = []\n for cast_elem in cast_elem_arr:\n td_arr = cast_elem.findAll('td')\n if len(td_arr) < 4:\n continue\n actor_elem = td_arr[1]\n actor_anchor = actor_elem.find('a')\n actor_url, actor_name = processPageAnchor(actor_anchor)\n actor_info = {'@type': 'Person', 'url': actor_url, 'name': actor_name}\n character_elem = td_arr[3]\n character_info = []\n character_anchor_arr = character_elem.findAll('a')\n for character_anchor in character_anchor_arr:\n character_url, character_name = processPageAnchor(character_anchor)\n character_info.append({'url': character_url, 'name':\n character_name})\n cast_and_character.append({'actor': actor_info,\n 'character_and_episodes': character_info})\n return cast_and_character\n\n\ndef checkvalidtext(txt):\n if txt.isspace():\n return False\n arr = ['|', 'See more', '»', ',']\n if txt in arr:\n return False\n if txt.strip() in arr:\n return False\n return True\n\n\ndef filter(arr):\n ret = []\n attr = '#'\n for val in arr:\n if checkvalidtext(val) == False:\n continue\n if val[-1] == ':':\n attr = val[0:-1]\n continue\n ret.append(val.strip())\n return attr, ret\n\n\ndef parseDetailInfo(page_soup):\n detail_elem = page_soup.find('div', {'class': 'article', 'id':\n 'titleDetails'})\n divs = detail_elem.findAll('div')\n details = {}\n for div in divs:\n vrr = div.findAll()\n attr, value = filter(div.findAll(text=True))\n if attr == 'Official Sites' or attr == '#' or attr == 'Color':\n continue\n details[attr] = value\n return details\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef simplify_string(inp):\n inp = inp.lower().strip()\n inp = re.sub('[^A-Za-z0-9]', '_', inp)\n return inp\n\n\ndef makeDirectory(path):\n print('creating directory ' + path)\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\n\ndef initialize(url, browser=None):\n if browser == None:\n print('creating browser for the first and last time')\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n browser.implicitly_wait(3)\n browser.get(url)\n browser.implicitly_wait(3)\n return browser\n\n\ndef performClick(driver, element):\n driver.execute_script('arguments[0].click();', element)\n\n\ndef getSoupFromElement(element):\n html = element.get_attribute('innerHTML')\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\n\ndef processPageAnchor(anchorElem):\n url = anchorElem['href']\n text = anchorElem.find(text=True).strip()\n return url, text\n\n\ndef getCastInfo(page_soup):\n cast_table = page_soup.find('table', {'class': 'cast_list'})\n cast_elem_arr = cast_table.findAll('tr', {'class': 'odd'}\n ) + cast_table.findAll('tr', {'class': 'even'})\n cast_and_character = []\n for cast_elem in cast_elem_arr:\n td_arr = cast_elem.findAll('td')\n if len(td_arr) < 4:\n continue\n actor_elem = td_arr[1]\n actor_anchor = actor_elem.find('a')\n actor_url, actor_name = processPageAnchor(actor_anchor)\n actor_info = {'@type': 'Person', 'url': actor_url, 'name': actor_name}\n character_elem = td_arr[3]\n character_info = []\n character_anchor_arr = character_elem.findAll('a')\n for character_anchor in character_anchor_arr:\n character_url, character_name = processPageAnchor(character_anchor)\n character_info.append({'url': character_url, 'name':\n character_name})\n cast_and_character.append({'actor': actor_info,\n 'character_and_episodes': character_info})\n return cast_and_character\n\n\ndef checkvalidtext(txt):\n if txt.isspace():\n return False\n arr = ['|', 'See more', '»', ',']\n if txt in arr:\n return False\n if txt.strip() in arr:\n return False\n return True\n\n\ndef filter(arr):\n ret = []\n attr = '#'\n for val in arr:\n if checkvalidtext(val) == False:\n continue\n if val[-1] == ':':\n attr = val[0:-1]\n continue\n ret.append(val.strip())\n return attr, ret\n\n\ndef parseDetailInfo(page_soup):\n detail_elem = page_soup.find('div', {'class': 'article', 'id':\n 'titleDetails'})\n divs = detail_elem.findAll('div')\n details = {}\n for div in divs:\n vrr = div.findAll()\n attr, value = filter(div.findAll(text=True))\n if attr == 'Official Sites' or attr == '#' or attr == 'Color':\n continue\n details[attr] = value\n return details\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef simplify_string(inp):\n inp = inp.lower().strip()\n inp = re.sub('[^A-Za-z0-9]', '_', inp)\n return inp\n\n\ndef makeDirectory(path):\n print('creating directory ' + path)\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\n\ndef initialize(url, browser=None):\n if browser == None:\n print('creating browser for the first and last time')\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n browser.implicitly_wait(3)\n browser.get(url)\n browser.implicitly_wait(3)\n return browser\n\n\ndef performClick(driver, element):\n driver.execute_script('arguments[0].click();', element)\n\n\ndef getSoupFromElement(element):\n html = element.get_attribute('innerHTML')\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\n\ndef processPageAnchor(anchorElem):\n url = anchorElem['href']\n text = anchorElem.find(text=True).strip()\n return url, text\n\n\ndef getCastInfo(page_soup):\n cast_table = page_soup.find('table', {'class': 'cast_list'})\n cast_elem_arr = cast_table.findAll('tr', {'class': 'odd'}\n ) + cast_table.findAll('tr', {'class': 'even'})\n cast_and_character = []\n for cast_elem in cast_elem_arr:\n td_arr = cast_elem.findAll('td')\n if len(td_arr) < 4:\n continue\n actor_elem = td_arr[1]\n actor_anchor = actor_elem.find('a')\n actor_url, actor_name = processPageAnchor(actor_anchor)\n actor_info = {'@type': 'Person', 'url': actor_url, 'name': actor_name}\n character_elem = td_arr[3]\n character_info = []\n character_anchor_arr = character_elem.findAll('a')\n for character_anchor in character_anchor_arr:\n character_url, character_name = processPageAnchor(character_anchor)\n character_info.append({'url': character_url, 'name':\n character_name})\n cast_and_character.append({'actor': actor_info,\n 'character_and_episodes': character_info})\n return cast_and_character\n\n\ndef checkvalidtext(txt):\n if txt.isspace():\n return False\n arr = ['|', 'See more', '»', ',']\n if txt in arr:\n return False\n if txt.strip() in arr:\n return False\n return True\n\n\ndef filter(arr):\n ret = []\n attr = '#'\n for val in arr:\n if checkvalidtext(val) == False:\n continue\n if val[-1] == ':':\n attr = val[0:-1]\n continue\n ret.append(val.strip())\n return attr, ret\n\n\ndef parseDetailInfo(page_soup):\n detail_elem = page_soup.find('div', {'class': 'article', 'id':\n 'titleDetails'})\n divs = detail_elem.findAll('div')\n details = {}\n for div in divs:\n vrr = div.findAll()\n attr, value = filter(div.findAll(text=True))\n if attr == 'Official Sites' or attr == '#' or attr == 'Color':\n continue\n details[attr] = value\n return details\n\n\ndef processOneMovie(movie_url, folder_path, driver, try_cnt=0):\n try:\n if try_cnt == 0:\n driver = initialize(movie_url, driver)\n page_html = driver.page_source\n page_soup = BeautifulSoup(page_html, 'html.parser')\n query_result = page_soup.find('script', {'type': 'application/ld+json'}\n )\n meta_data = json.loads(query_result.string)\n try:\n meta_data['cast_and_character'] = getCastInfo(page_soup)\n except:\n meta_data['cast_and_character'\n ] = 'Error loading cast information -- checked {}'.format(\n datetime.datetime.now())\n meta_data['details'] = parseDetailInfo(page_soup)\n movie_id = meta_data['url'].split('/')[-2]\n movie_name = meta_data['name']\n file_name = '{}__{}'.format(movie_id, simplify_string(movie_name)\n ) + '.json'\n with open(folder_path + '/' + file_name, 'w') as f:\n json.dump(meta_data, f)\n print('saved movie < {} > to < {} >'.format(movie_name, file_name))\n return True\n except:\n if try_cnt == 17:\n print('Error loading movie -- skip this')\n return False\n print(\n 'maybe temporary internet connection problem. trying again < {} >'\n .format(try_cnt + 1))\n driver.refresh()\n time.sleep(2)\n return processOneMovie(movie_url, folder_path, driver, try_cnt + 1)\n\n\n<mask token>\n\n\ndef loadFailCases():\n try:\n with open('fail_cases.json', 'r') as f:\n fail_cases = json.load(f)\n except:\n print(\n 'Could not find fail_cases.json -- initializing with empty folder')\n fail_cases = []\n return fail_cases\n\n\n<mask token>\n",
"step-5": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\nimport json\nimport re\nimport os\nimport datetime\n\n###########################################################################\ndriver_path = \"/home/arnab/Codes/00_Libs/chromedriver_linux64/chromedriver\"\n###########################################################################\n\ndef simplify_string(inp):\n inp = inp.lower().strip()\n inp = re.sub(r'[^A-Za-z0-9]', '_', inp)\n\n return inp\n\ndef makeDirectory(path):\n print(\"creating directory \" + path)\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\ndef initialize(url, browser=None):\n if(browser == None):\n print(\"creating browser for the first and last time\")\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n # chrome_options.add_argument('--no-sandbox')\n # chrome_options.add_argument('--disable-dev-shm-usage')\n\n browser = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n browser.implicitly_wait(3)\n\n browser.get(url)\n browser.implicitly_wait(3)\n\n return browser\n\n\ndef performClick(driver, element):\n driver.execute_script(\"arguments[0].click();\", element)\n\n\ndef getSoupFromElement(element):\n html = element.get_attribute('innerHTML')\n soup = BeautifulSoup(html, 'html.parser')\n return soup\n\n\ndef processPageAnchor(anchorElem):\n url = anchorElem['href']\n text = anchorElem.find(text=True).strip()\n return url, text\n\ndef getCastInfo(page_soup):\n cast_table = page_soup.find(\"table\", {\"class\": \"cast_list\"})\n # print(\" >>>>>>>>>>>>>>>>>>>>>>>>> \")\n # print(cast_table.prettify())\n\n cast_elem_arr = cast_table.findAll(\"tr\", {\"class\": \"odd\"}) + cast_table.findAll(\"tr\", {\"class\": \"even\"})\n # print(len(cast_elem_arr))\n # print(cast_elem_arr[0].prettify())\n\n cast_and_character = []\n\n for cast_elem in cast_elem_arr:\n td_arr = cast_elem.findAll(\"td\")\n if(len(td_arr) < 4):\n continue\n \n # print(td_arr[1].prettify())\n actor_elem = td_arr[1]\n\n\n actor_anchor = actor_elem.find(\"a\")\n actor_url, actor_name = processPageAnchor(actor_anchor)\n actor_info = {\n \"@type\" : \"Person\",\n \"url\" : actor_url,\n \"name\" : actor_name\n }\n # print(actor_info)\n\n # print(td_arr[3].prettify())\n character_elem = td_arr[3]\n character_info = []\n character_anchor_arr = character_elem.findAll('a')\n for character_anchor in character_anchor_arr:\n character_url, character_name = processPageAnchor(character_anchor)\n character_info.append({\n \"url\" : character_url,\n \"name\" : character_name\n })\n\n # print(character_info)\n\n cast_and_character.append({\n \"actor\" : actor_info,\n \"character_and_episodes\" : character_info\n })\n\n\n # print(cast_and_character)\n # print(len(cast_and_character))\n return cast_and_character\n\ndef checkvalidtext(txt):\n if(txt.isspace()):\n return False\n arr = [\"|\", \"See more\", \"\\u00bb\", \",\"]\n if txt in arr:\n return False\n if txt.strip() in arr:\n return False\n return True\n\n\ndef filter(arr):\n ret = []\n attr = \"#\"\n for val in arr:\n if(checkvalidtext(val) == False):\n continue\n if(val[-1] == \":\"):\n attr = val[0:-1]\n continue\n ret.append(val.strip())\n return attr, ret \n\ndef parseDetailInfo(page_soup):\n detail_elem = page_soup.find(\"div\", {\n 'class': 'article',\n 'id': \"titleDetails\"\n })\n divs = detail_elem.findAll(\"div\")\n \n details = {}\n for div in divs:\n vrr = div.findAll()\n attr, value = filter(div.findAll(text=True))\n if(attr == \"Official Sites\" or attr == \"#\" or attr == \"Color\"):\n continue\n # print(attr, \" >>>>>> \", value)\n details[attr] = value\n\n return details\n\n\ndef processOneMovie(movie_url, folder_path, driver, try_cnt = 0):\n\n # if(True):\n try:\n if(try_cnt == 0):\n driver = initialize(movie_url, driver)\n\n page_html = driver.page_source\n page_soup = BeautifulSoup(page_html, 'html.parser')\n\n # print(page_soup.prettify())\n\n query_result = page_soup.find(\"script\", {\"type\": \"application/ld+json\"})\n # print(query_result.string)\n meta_data = json.loads(query_result.string)\n try:\n meta_data[\"cast_and_character\"] = getCastInfo(page_soup)\n except:\n meta_data[\"cast_and_character\"] = \"Error loading cast information -- checked {}\".format(datetime.datetime.now())\n \n meta_data['details'] = parseDetailInfo(page_soup)\n\n movie_id = meta_data[\"url\"].split('/')[-2]\n movie_name = meta_data[\"name\"]\n\n file_name = \"{}__{}\".format(movie_id, simplify_string(movie_name)) + \".json\"\n # print(file_name)\n # print(meta_data)\n\n with open(folder_path + \"/\" + file_name, \"w\") as f:\n json.dump(meta_data, f)\n print(\"saved movie < {} > to < {} >\".format(movie_name, file_name))\n\n return True\n \n except:\n if(try_cnt == 17):\n print(\"Error loading movie -- skip this\")\n return False\n\n print(\"maybe temporary internet connection problem. trying again < {} >\".format(try_cnt + 1))\n driver.refresh()\n time.sleep(2)\n return processOneMovie(movie_url, folder_path, driver, try_cnt+1)\n\n\n\n#############################################################################################################\nurl_root = \"https://www.imdb.com/\"\nsave_path = \"MOVIES\"\nsummary_path = \"IMDB_SUMMARY/SUMMARY_DATA\"\nfrm = 1\nrng = 250\nlimit = 600000 # set it to -1 for all processing\n\n#############################################################################################################\n\nmakeDirectory(save_path)\nsummary_files = sorted(os.listdir(summary_path))\ndriver = initialize(url_root)\n\n\ndef loadFailCases():\n try:\n with open(\"fail_cases.json\", \"r\") as f:\n fail_cases = json.load(f)\n except:\n print(\"Could not find fail_cases.json -- initializing with empty folder\")\n fail_cases = []\n return fail_cases\n\nprint(summary_files)\n# for summary in summary_files:\nwhile(True):\n summary = \"{} - {}.json\".format(frm, frm+rng-1)\n\n if(summary not in summary_files):\n print(\"Could not fild summary file < {} >\".format(summary))\n break\n\n\n print(\"Now processing < {} >\".format(summary))\n\n folder_name = summary.split('.')[0]\n folder_path = save_path + \"/\" + folder_name\n makeDirectory(folder_path)\n\n with open(summary_path + \"/\" + summary) as f:\n movie_arr = json.load(f)\n # print(type(movie_arr))\n # print(movie_arr)\n process_cnt = 0\n\n st = 0\n # if(frm == 65251):\n # st = 173\n\n for idx in range(st, len(movie_arr)):\n movie = movie_arr[idx]\n # print(movie[\"link\"])\n movie_url = url_root + movie[\"link\"]\n success = processOneMovie(movie_url, folder_path, driver)\n\n if(success == False):\n fail_cases = loadFailCases()\n fail_cases.append(movie)\n with open(\"fail_cases.json\", \"w\") as f:\n json.dump(fail_cases, f)\n\n process_cnt += 1\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>> processed {} of {} --- of :: {}\".format(st + process_cnt, len(movie_arr), summary))\n \n frm += rng\n\n if limit == -1:\n continue\n elif (frm > limit):\n break\n ",
"step-ids": [
7,
9,
10,
12,
16
]
}
|
[
7,
9,
10,
12,
16
] |
../PyFoam/bin/pyFoamPlotWatcher.py
|
normal
|
{
"blob_id": "ec2d3bbfce06c498790afd491931df3f391dafbe",
"index": 8686,
"step-1": "../PyFoam/bin/pyFoamPlotWatcher.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from django.http import response
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
from .serializers import UserSerializer,UserCreationSerialier,UserEditionSerializer
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
class Users(APIView):
# permission_classes = [IsAuthenticated]
def get(self,request):
users = User.objects.filter(is_removed=False)
serialized_users = UserSerializer(instance=users,many=True)
return Response(serialized_users.data,status=status.HTTP_200_OK)
class UserDetail(APIView):
def get(self,request,pk):
user = User.objects.filter(pk=pk,is_removed=False).first()
if user is None:
return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)
serailized_data = UserSerializer(instance=user)
return Response(serailized_data.data,status=status.HTTP_200_OK)
class CreateUser(APIView):
def post(self,request):
serialized_data = UserCreationSerialier(data=request.data)
if serialized_data.is_valid():
data = serialized_data.validated_data
user = User.objects.filter(email=data['email'],is_removed=False).first()
if user is not None:
return Response({'error':'This email is Already Taken!','success':False},status=status.HTTP_400_BAD_REQUEST)
user = User(email=data['email'],full_name=data['full_name'])
user.set_password(data['password'])
user.save()
serialized_user = UserSerializer(instance=user)
return Response(serialized_user.data,status=status.HTTP_201_CREATED)
return Response(serialized_data.errors,status=status.HTTP_400_BAD_REQUEST)
class EditUser(APIView):
def put(self,request,pk):
user = User.objects.filter(pk=pk,is_removed=False).first()
if user is None:
return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)
serialized_user = UserEditionSerializer(data=request.data,instance=user)
if serialized_user.is_valid():
user = serialized_user.save()
return Response(UserSerializer(instance=user).data,status=status.HTTP_202_ACCEPTED)
return Response(serialized_user.errors,status=status.HTTP_400_BAD_REQUEST)
class RemoveUser(APIView):
def delete(self,request,pk):
user = User.objects.filter(pk=pk,is_removed=False).first()
if user is None:
return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)
user.is_removed = True
user.save()
return Response(status=status.HTTP_204_NO_CONTENT)
class GetUserFromToken(APIView):
permission_classes = [IsAuthenticated]
def get(self,request):
user = request.user
serialized_user = UserSerializer(instance=user)
return Response(serialized_user.data)
|
normal
|
{
"blob_id": "dff454cbde985a08b34377b80dd8e3b22f1cc13a",
"index": 3948,
"step-1": "<mask token>\n\n\nclass CreateUser(APIView):\n <mask token>\n\n\nclass EditUser(APIView):\n\n def put(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serialized_user = UserEditionSerializer(data=request.data, instance\n =user)\n if serialized_user.is_valid():\n user = serialized_user.save()\n return Response(UserSerializer(instance=user).data, status=\n status.HTTP_202_ACCEPTED)\n return Response(serialized_user.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass RemoveUser(APIView):\n\n def delete(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n user.is_removed = True\n user.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass GetUserFromToken(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data)\n",
"step-2": "<mask token>\n\n\nclass UserDetail(APIView):\n <mask token>\n\n\nclass CreateUser(APIView):\n\n def post(self, request):\n serialized_data = UserCreationSerialier(data=request.data)\n if serialized_data.is_valid():\n data = serialized_data.validated_data\n user = User.objects.filter(email=data['email'], is_removed=False\n ).first()\n if user is not None:\n return Response({'error': 'This email is Already Taken!',\n 'success': False}, status=status.HTTP_400_BAD_REQUEST)\n user = User(email=data['email'], full_name=data['full_name'])\n user.set_password(data['password'])\n user.save()\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data, status=status.\n HTTP_201_CREATED)\n return Response(serialized_data.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass EditUser(APIView):\n\n def put(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serialized_user = UserEditionSerializer(data=request.data, instance\n =user)\n if serialized_user.is_valid():\n user = serialized_user.save()\n return Response(UserSerializer(instance=user).data, status=\n status.HTTP_202_ACCEPTED)\n return Response(serialized_user.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass RemoveUser(APIView):\n\n def delete(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n user.is_removed = True\n user.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass GetUserFromToken(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data)\n",
"step-3": "<mask token>\n\n\nclass UserDetail(APIView):\n\n def get(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serailized_data = UserSerializer(instance=user)\n return Response(serailized_data.data, status=status.HTTP_200_OK)\n\n\nclass CreateUser(APIView):\n\n def post(self, request):\n serialized_data = UserCreationSerialier(data=request.data)\n if serialized_data.is_valid():\n data = serialized_data.validated_data\n user = User.objects.filter(email=data['email'], is_removed=False\n ).first()\n if user is not None:\n return Response({'error': 'This email is Already Taken!',\n 'success': False}, status=status.HTTP_400_BAD_REQUEST)\n user = User(email=data['email'], full_name=data['full_name'])\n user.set_password(data['password'])\n user.save()\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data, status=status.\n HTTP_201_CREATED)\n return Response(serialized_data.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass EditUser(APIView):\n\n def put(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serialized_user = UserEditionSerializer(data=request.data, instance\n =user)\n if serialized_user.is_valid():\n user = serialized_user.save()\n return Response(UserSerializer(instance=user).data, status=\n status.HTTP_202_ACCEPTED)\n return Response(serialized_user.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass RemoveUser(APIView):\n\n def delete(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n user.is_removed = True\n user.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass GetUserFromToken(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data)\n",
"step-4": "<mask token>\n\n\nclass Users(APIView):\n\n def get(self, request):\n users = User.objects.filter(is_removed=False)\n serialized_users = UserSerializer(instance=users, many=True)\n return Response(serialized_users.data, status=status.HTTP_200_OK)\n\n\nclass UserDetail(APIView):\n\n def get(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serailized_data = UserSerializer(instance=user)\n return Response(serailized_data.data, status=status.HTTP_200_OK)\n\n\nclass CreateUser(APIView):\n\n def post(self, request):\n serialized_data = UserCreationSerialier(data=request.data)\n if serialized_data.is_valid():\n data = serialized_data.validated_data\n user = User.objects.filter(email=data['email'], is_removed=False\n ).first()\n if user is not None:\n return Response({'error': 'This email is Already Taken!',\n 'success': False}, status=status.HTTP_400_BAD_REQUEST)\n user = User(email=data['email'], full_name=data['full_name'])\n user.set_password(data['password'])\n user.save()\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data, status=status.\n HTTP_201_CREATED)\n return Response(serialized_data.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass EditUser(APIView):\n\n def put(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serialized_user = UserEditionSerializer(data=request.data, instance\n =user)\n if serialized_user.is_valid():\n user = serialized_user.save()\n return Response(UserSerializer(instance=user).data, status=\n status.HTTP_202_ACCEPTED)\n return Response(serialized_user.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass RemoveUser(APIView):\n\n def delete(self, request, pk):\n user = User.objects.filter(pk=pk, is_removed=False).first()\n if user is None:\n return Response({'error': 'User Does Not Exists', 'success': \n False}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n user.is_removed = True\n user.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass GetUserFromToken(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data)\n",
"step-5": "from django.http import response\nfrom django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .models import User\nfrom .serializers import UserSerializer,UserCreationSerialier,UserEditionSerializer\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\n\nclass Users(APIView):\n # permission_classes = [IsAuthenticated]\n\n def get(self,request):\n users = User.objects.filter(is_removed=False)\n serialized_users = UserSerializer(instance=users,many=True)\n return Response(serialized_users.data,status=status.HTTP_200_OK)\n \n\nclass UserDetail(APIView):\n\n def get(self,request,pk):\n user = User.objects.filter(pk=pk,is_removed=False).first()\n if user is None:\n return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serailized_data = UserSerializer(instance=user)\n return Response(serailized_data.data,status=status.HTTP_200_OK)\n\n\nclass CreateUser(APIView):\n \n def post(self,request):\n serialized_data = UserCreationSerialier(data=request.data)\n if serialized_data.is_valid():\n data = serialized_data.validated_data\n user = User.objects.filter(email=data['email'],is_removed=False).first()\n if user is not None:\n return Response({'error':'This email is Already Taken!','success':False},status=status.HTTP_400_BAD_REQUEST)\n \n user = User(email=data['email'],full_name=data['full_name'])\n user.set_password(data['password'])\n user.save()\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data,status=status.HTTP_201_CREATED)\n return Response(serialized_data.errors,status=status.HTTP_400_BAD_REQUEST)\n\n\nclass EditUser(APIView):\n \n def put(self,request,pk):\n user = User.objects.filter(pk=pk,is_removed=False).first()\n if user is None:\n return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n serialized_user = UserEditionSerializer(data=request.data,instance=user)\n if serialized_user.is_valid():\n user = serialized_user.save()\n return Response(UserSerializer(instance=user).data,status=status.HTTP_202_ACCEPTED)\n return Response(serialized_user.errors,status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RemoveUser(APIView):\n\n def delete(self,request,pk):\n user = User.objects.filter(pk=pk,is_removed=False).first()\n if user is None:\n return Response({'error':'User Does Not Exists','success':False},status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n user.is_removed = True\n user.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nclass GetUserFromToken(APIView):\n permission_classes = [IsAuthenticated]\n \n def get(self,request):\n user = request.user\n serialized_user = UserSerializer(instance=user)\n return Response(serialized_user.data)",
"step-ids": [
8,
10,
11,
13,
15
]
}
|
[
8,
10,
11,
13,
15
] |
'''
'''
import numpy as np
from scipy.spatial import distance
def synonym_filter(WordVectors_npArray, WordLabels_npArray):
'''
'''
pass
def synonym_alternatives_range(WordVectors_npArray,
AlternativesVectorOne_npArray,
AlternativesVectorTwo_npArray,
AlternativesVectorThree_npArray,
AlternativesVectorFour_npArray):
'''
'''
synonym_alternatives_range = np.zeros(len(WordVectors_npArray))
for word_int in range(len(WordVectors_npArray)):
DistToAltOne = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorOne_npArray[word_int,:])
print(DistToAltOne)
DistToAltTwo = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorTwo_npArray[word_int,:])
print(DistToAltTwo)
DistToAltThree = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorThree_npArray[word_int,:])
print(DistToAltThree)
DistToAltFour = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorFour_npArray[word_int,:])
print(DistToAltFour)
synonym_alternatives_range[word_int] = (max(DistToAltOne, \
DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne, \
DistToAltTwo, DistToAltThree, DistToAltFour))
return synonym_alternatives_range
def synonym_alternatives_average(WordVectors_npArray,
AlternativesVectorOne_npArray,
AlternativesVectorTwo_npArray,
AlternativesVectorThree_npArray,
AlternativesVectorFour_npArray):
'''
'''
synonym_alternatives_average = np.zeros(len(WordVectors_npArray))
for word_int in range(len(WordVectors_npArray)):
DistToAltOne = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorOne_npArray[word_int,:])
print(DistToAltOne)
DistToAltTwo = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorTwo_npArray[word_int,:])
print(DistToAltTwo)
DistToAltThree = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorThree_npArray[word_int,:])
print(DistToAltThree)
DistToAltFour = distance.cosine(WordVectors_npArray[word_int,:], \
AlternativesVectorFour_npArray[word_int,:])
print(DistToAltFour)
synonym_alternatives_average[word_int] = (DistToAltOne +\
DistToAltTwo + DistToAltThree + DistToAltFour)/4
return synonym_alternatives_average
def nth_neighbor_filter():
''' Maybe we won't have this.
'''
pass
|
normal
|
{
"blob_id": "ea0a59953f2571f36e65f8f958774074b39a9ae5",
"index": 6996,
"step-1": "<mask token>\n\n\ndef synonym_alternatives_range(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_range = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_range[word_int] = max(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour)\n return synonym_alternatives_range\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef synonym_alternatives_range(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_range = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_range[word_int] = max(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour)\n return synonym_alternatives_range\n\n\ndef synonym_alternatives_average(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_average = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_average[word_int] = (DistToAltOne +\n DistToAltTwo + DistToAltThree + DistToAltFour) / 4\n return synonym_alternatives_average\n\n\ndef nth_neighbor_filter():\n \"\"\" Maybe we won't have this.\n \"\"\"\n pass\n",
"step-3": "<mask token>\n\n\ndef synonym_filter(WordVectors_npArray, WordLabels_npArray):\n \"\"\"\n \"\"\"\n pass\n\n\ndef synonym_alternatives_range(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_range = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_range[word_int] = max(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour)\n return synonym_alternatives_range\n\n\ndef synonym_alternatives_average(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_average = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_average[word_int] = (DistToAltOne +\n DistToAltTwo + DistToAltThree + DistToAltFour) / 4\n return synonym_alternatives_average\n\n\ndef nth_neighbor_filter():\n \"\"\" Maybe we won't have this.\n \"\"\"\n pass\n",
"step-4": "<mask token>\nimport numpy as np\nfrom scipy.spatial import distance\n\n\ndef synonym_filter(WordVectors_npArray, WordLabels_npArray):\n \"\"\"\n \"\"\"\n pass\n\n\ndef synonym_alternatives_range(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_range = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_range[word_int] = max(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne,\n DistToAltTwo, DistToAltThree, DistToAltFour)\n return synonym_alternatives_range\n\n\ndef synonym_alternatives_average(WordVectors_npArray,\n AlternativesVectorOne_npArray, AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray, AlternativesVectorFour_npArray):\n \"\"\"\n \"\"\"\n synonym_alternatives_average = np.zeros(len(WordVectors_npArray))\n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorOne_npArray[word_int, :])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorTwo_npArray[word_int, :])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorThree_npArray[word_int, :])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int, :],\n AlternativesVectorFour_npArray[word_int, :])\n print(DistToAltFour)\n synonym_alternatives_average[word_int] = (DistToAltOne +\n DistToAltTwo + DistToAltThree + DistToAltFour) / 4\n return synonym_alternatives_average\n\n\ndef nth_neighbor_filter():\n \"\"\" Maybe we won't have this.\n \"\"\"\n pass\n",
"step-5": "'''\n'''\n\nimport numpy as np\n\nfrom scipy.spatial import distance\n\n\ndef synonym_filter(WordVectors_npArray, WordLabels_npArray):\n '''\n '''\n \n \n pass\n\ndef synonym_alternatives_range(WordVectors_npArray, \n AlternativesVectorOne_npArray,\n AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray,\n AlternativesVectorFour_npArray):\n '''\n '''\n \n \n synonym_alternatives_range = np.zeros(len(WordVectors_npArray))\n \n for word_int in range(len(WordVectors_npArray)):\n \n DistToAltOne = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorOne_npArray[word_int,:])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorTwo_npArray[word_int,:])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorThree_npArray[word_int,:])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorFour_npArray[word_int,:])\n print(DistToAltFour)\n \n synonym_alternatives_range[word_int] = (max(DistToAltOne, \\\n DistToAltTwo, DistToAltThree, DistToAltFour) - min(DistToAltOne, \\\n DistToAltTwo, DistToAltThree, DistToAltFour))\n \n \n return synonym_alternatives_range\n \ndef synonym_alternatives_average(WordVectors_npArray, \n AlternativesVectorOne_npArray,\n AlternativesVectorTwo_npArray,\n AlternativesVectorThree_npArray,\n AlternativesVectorFour_npArray):\n '''\n '''\n \n \n synonym_alternatives_average = np.zeros(len(WordVectors_npArray))\n \n for word_int in range(len(WordVectors_npArray)):\n DistToAltOne = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorOne_npArray[word_int,:])\n print(DistToAltOne)\n DistToAltTwo = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorTwo_npArray[word_int,:])\n print(DistToAltTwo)\n DistToAltThree = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorThree_npArray[word_int,:])\n print(DistToAltThree)\n DistToAltFour = distance.cosine(WordVectors_npArray[word_int,:], \\\n AlternativesVectorFour_npArray[word_int,:])\n print(DistToAltFour)\n \n synonym_alternatives_average[word_int] = (DistToAltOne +\\\n DistToAltTwo + DistToAltThree + DistToAltFour)/4\n \n return synonym_alternatives_average\n \n \n\ndef nth_neighbor_filter():\n ''' Maybe we won't have this.\n '''\n \n \n pass\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
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)
|
normal
|
{
"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 -*-
"""
Created on Fri Dec 30 22:01:06 2016
@author: George
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 23:22:16 2016
@author: George
"""
import os
import clr
import numpy as np
clr.AddReference(os.getcwd() + "\\libs\\MyMediaLite\\MyMediaLite.dll")
from MyMediaLite import IO, RatingPrediction, Eval
from MyMediaLite import Random
from tools import timing as tim
class Base():
def __init__(self):
Random.set_Seed(1)
def fit(self, DATASET, model_name, _):
data_path = ".\\data\\" + DATASET + "\\"
file_prefix = DATASET + "-f"
file_train_suffix1 = "-train.csv"
file_test_suffix = "-test.csv"
fold_rmse = []
fold_mae = []
fold_time = []
print self.rec.ToString()
for cv_index in range(0, 5):
train_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_train_suffix1)
test_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_test_suffix)
print data_path + file_prefix + str(cv_index + 1) + file_train_suffix1
self.rec.Ratings = train_data
tim.startlog('Training model')
self.rec.Train()
fold_time.append(tim.endlog('Done training model'))
score = Eval.Ratings.Evaluate(self.rec, test_data)
fold_rmse.append(score.get_Item("RMSE"))
fold_mae.append(score.get_Item("MAE"))
print model_name
print "Mean RMSE: %.5f +- %.5f" % (np.array(fold_rmse, dtype=np.single).mean(), np.array(fold_rmse, dtype=np.single).std())
print "Mean MAE: %.5f +- %.5f" % (np.array(fold_mae, dtype=np.single).mean(), np.array(fold_mae, dtype=np.single).std())
return fold_rmse, fold_mae, fold_time, 0, 0, 0
class GlobalAverage(Base):
def __init__(self):
Base.__init__(self)
self.rec = RatingPrediction.GlobalAverage()
class UserAverage(Base):
def __init__(self):
Base.__init__(self)
self.rec = RatingPrediction.UserAverage()
class ItemAverage(Base):
def __init__(self):
Base.__init__(self)
self.rec = RatingPrediction.ItemAverage()
|
normal
|
{
"blob_id": "1292b894b75676abec3f97a8854fe406787baf1d",
"index": 7909,
"step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 30 22:01:06 2016\n\n@author: George\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 24 23:22:16 2016\n\n@author: George\n\"\"\"\n\nimport os\nimport clr\nimport numpy as np\n\nclr.AddReference(os.getcwd() + \"\\\\libs\\\\MyMediaLite\\\\MyMediaLite.dll\")\n\nfrom MyMediaLite import IO, RatingPrediction, Eval\nfrom MyMediaLite import Random\n\nfrom tools import timing as tim\n\nclass Base():\n \n def __init__(self):\n Random.set_Seed(1)\n \n \n def fit(self, DATASET, model_name, _):\n \n data_path = \".\\\\data\\\\\" + DATASET + \"\\\\\"\n file_prefix = DATASET + \"-f\"\n file_train_suffix1 = \"-train.csv\"\n file_test_suffix = \"-test.csv\"\n \n fold_rmse = []\n fold_mae = []\n fold_time = []\n \n print self.rec.ToString()\n for cv_index in range(0, 5):\n train_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_train_suffix1)\n test_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_test_suffix)\n \n print data_path + file_prefix + str(cv_index + 1) + file_train_suffix1\n \n self.rec.Ratings = train_data\n \n tim.startlog('Training model')\n self.rec.Train()\n fold_time.append(tim.endlog('Done training model'))\n \n score = Eval.Ratings.Evaluate(self.rec, test_data)\n \n fold_rmse.append(score.get_Item(\"RMSE\"))\n fold_mae.append(score.get_Item(\"MAE\"))\n \n print model_name\n print \"Mean RMSE: %.5f +- %.5f\" % (np.array(fold_rmse, dtype=np.single).mean(), np.array(fold_rmse, dtype=np.single).std())\n print \"Mean MAE: %.5f +- %.5f\" % (np.array(fold_mae, dtype=np.single).mean(), np.array(fold_mae, dtype=np.single).std())\n \n return fold_rmse, fold_mae, fold_time, 0, 0, 0\n \nclass GlobalAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.GlobalAverage()\n \nclass UserAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.UserAverage()\n \nclass ItemAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.ItemAverage()\n ",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
'''
A empresa Tchau de telefonia cobra:
-Abaixo de 200 minutos, R$ 0,20 por minuto
-Entre 200 e 400 minutos, R$ 0,18 por minuto
-Acima de 400 minutos, R$ 0,15 por minuto
- Bonus: - Acima de 800 minutos, R$ 0,08
Calcule a conta de telefone
'''
minutos = int(input('Minutos utilizados: '))
if minutos > 800:
total = minutos * 0.08
elif minutos > 400 and minutos <= 800:
total = minutos * 0.15
elif minutos < 200:
total = minutos * 0.2
else:
total = minutos * 0.18
print('Valor da conta: R$ %.2f' %total)
|
normal
|
{
"blob_id": "1b3e64be988495454535ca96c7a1b6c20aa27076",
"index": 2648,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\nprint('Valor da conta: R$ %.2f' % total)\n",
"step-3": "<mask token>\nminutos = int(input('Minutos utilizados: '))\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\nprint('Valor da conta: R$ %.2f' % total)\n",
"step-4": "'''\nA empresa Tchau de telefonia cobra:\n-Abaixo de 200 minutos, R$ 0,20 por minuto\n-Entre 200 e 400 minutos, R$ 0,18 por minuto\n-Acima de 400 minutos, R$ 0,15 por minuto\n\n\n- Bonus: - Acima de 800 minutos, R$ 0,08\nCalcule a conta de telefone\n'''\n\nminutos = int(input('Minutos utilizados: '))\n\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\n\nprint('Valor da conta: R$ %.2f' %total)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
a = float(input('Digite um valor: '))
b = float(input('Digite outro valor: '))
c = float(input('Digite mais um valor: '))
if a == b or b == c:
print('Com os números digitados, formam um triângulo EQUILATERO.')
elif a <> b and b <> c and c == a and b == c:
print('Com os números digitados, formam um triângulo ISOSELES.')
else:
print('Com os número digitados, formam triângulo ESCALENO.')
|
normal
|
{
"blob_id": "81233eb12b8447d017b31f200ab7902dcce45496",
"index": 1649,
"step-1": "a = float(input('Digite um valor: '))\nb = float(input('Digite outro valor: '))\nc = float(input('Digite mais um valor: '))\nif a == b or b == c:\n print('Com os números digitados, formam um triângulo EQUILATERO.')\nelif a <> b and b <> c and c == a and b == c:\n print('Com os números digitados, formam um triângulo ISOSELES.')\nelse:\n print('Com os número digitados, formam triângulo ESCALENO.')",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
from .exec_generator import *
|
normal
|
{
"blob_id": "b6ee3c980357ab22a7969c21207b34546c87092d",
"index": 7305,
"step-1": "<mask token>\n",
"step-2": "from .exec_generator import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
from .lasot import Lasot
from .got10k import Got10k
from .tracking_net import TrackingNet
from .imagenetvid import ImagenetVID
from .imagenetdet import ImagenetDET
from .coco_seq import MSCOCOSeq
from .vot import VOT
from .youtube_vos import YoutubeVOS
from .youtube_bb import YoutubeBB
|
normal
|
{
"blob_id": "e12ca2c4592a629ce78cae7211fedaf02352a603",
"index": 4700,
"step-1": "<mask token>\n",
"step-2": "from .lasot import Lasot\nfrom .got10k import Got10k\nfrom .tracking_net import TrackingNet\nfrom .imagenetvid import ImagenetVID\nfrom .imagenetdet import ImagenetDET\nfrom .coco_seq import MSCOCOSeq\nfrom .vot import VOT\nfrom .youtube_vos import YoutubeVOS\nfrom .youtube_bb import YoutubeBB\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
from application.routes import pad_num, tracking_gen
from flask import url_for
from flask_testing import TestCase
from application import app, db
from application.models import Users, Orders
from os import getenv
class TestCase(TestCase):
def create_app(self):
app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:///test.db",
SECRET_KEY="TEST_SECRET_KEY",
DEBUG=True,
WTF_CSRF_ENABLED=False,
)
return app
def setUp(self):
db.create_all()
new_user = Users(
email="[email protected]",
name="Test",
house_number="8",
postcode="G3 8PX",
phone="07999999999",
)
db.session.add(new_user)
new_order = Orders(customer_id=1)
db.session.add(new_order)
new_order = Orders(customer_id=1, order_status="out for delivery")
db.session.add(new_order)
new_order = Orders(customer_id=1, order_status="delivered")
db.session.add(new_order)
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()
class TestPadNum(TestCase):
def test_pad_num(self):
self.assertEqual(len(pad_num(3)), 4)
class TestTrackingGen(TestCase):
def test_tracking_gen(self):
self.assertEqual(len(tracking_gen()), 8)
class TestViews(TestCase):
def test_home_get(self):
response = self.client.get(url_for("home"))
self.assertEqual(response.status_code, 200)
def test_add_order_get(self):
response = self.client.get(url_for("add_order"))
self.assertEqual(response.status_code, 200)
def test_view_order_get(self):
response = self.client.get(url_for("view_order", id=1))
self.assertEqual(response.status_code, 200)
def test_register_get(self):
response = self.client.get(url_for("register"))
self.assertEqual(response.status_code, 200)
def test_update_order_get(self):
response = self.client.get(url_for("update_order", id=1))
self.assertEqual(response.status_code, 200)
def test_delete_get(self):
response = self.client.get(url_for("delete", id=1))
self.assertEqual(response.status_code, 405)
def test_delivered_get(self):
response = self.client.get(url_for("delivered", id=1))
self.assertEqual(response.status_code, 405)
class TestCreateUser(TestCase):
def test_create_user(self):
response = self.client.post(
url_for("register"),
data=dict(
email="[email protected]",
name="Test2",
house_number="82",
postcode="G2 8PX",
phone="0788888888",
),
follow_redirects=True,
)
user = Users.query.filter_by(id=2).first()
self.assertEqual("[email protected]", user.email)
self.assertEqual("Test2", user.name)
self.assertEqual("82", user.house_number)
self.assertEqual("G2 8PX", user.postcode)
self.assertEqual("0788888888", user.phone)
class TestDuplicateEmail(TestCase):
def test_duplicate_email(self):
response = self.client.post(
url_for("register"),
data=dict(
email="[email protected]",
name="Test",
house_number="82",
postcode="G2 8PX",
phone="0788888888",
),
follow_redirects=True,
)
class TestAddOrder(TestCase):
def test_add_order(self):
response = self.client.post(
url_for("add_order", id=1),
data=dict(email="[email protected]"),
follow_redirects=True,
)
order = Orders.query.filter_by(id=1).first()
user = Users.query.filter_by(id=1).first()
self.assertEqual(1, order.customer_id)
self.assertEqual("order placed", order.order_status)
self.assertEqual(None, order.tracking_num)
self.assertIn(order, user.orders)
class TestAddOrderNoUser(TestCase):
def test_add_order_no_user(self):
response = self.client.post(
url_for("add_order"), data=dict(email="[email protected]")
)
class TestViewOrder(TestCase):
def test_view_order(self):
response = self.client.get(
url_for("view_order", id=1),
data=dict(
id="0006",
name="Test",
house_number="8",
postode="G3 8PX",
phone="07999999999",
),
)
self.assertIn(b"0001", response.data)
self.assertIn(b"Test", response.data)
self.assertIn(b"8", response.data)
self.assertIn(b"G3 8PX", response.data)
self.assertIn(b"07999999999", response.data)
class TestUpdateOrder(TestCase):
def test_update_order(self):
response = self.client.post(
url_for("update_order", id=1),
data=dict(
status="out for delivery",
tracking_num_len=8,
),
)
order = Orders.query.filter_by(id=1).first()
self.assertEqual("out for delivery", order.order_status)
self.assertEqual(len(order.tracking_num), 8)
class TestDelivered(TestCase):
def test_delivered(self):
response = self.client.post(url_for("delivered", id=1))
order = Orders.query.filter_by(id=1).first()
self.assertEqual("delivered", order.order_status)
class TestDelete(TestCase):
def test_delete(self):
response = self.client.post(url_for("delete", id=1))
order = Orders.query.filter_by(id=1).first()
self.assertEqual(order, None)
|
normal
|
{
"blob_id": "eeece3bf423f85f05ef11db47909215578e64aec",
"index": 4912,
"step-1": "<mask token>\n\n\nclass TestViews(TestCase):\n <mask token>\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n",
"step-2": "<mask token>\n\n\nclass TestPadNum(TestCase):\n <mask token>\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n",
"step-3": "<mask token>\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n",
"step-4": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n\n def create_app(self):\n app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///test.db',\n SECRET_KEY='TEST_SECRET_KEY', DEBUG=True, WTF_CSRF_ENABLED=False)\n return app\n\n def setUp(self):\n db.create_all()\n new_user = Users(email='[email protected]', name='Test', house_number=\n '8', postcode='G3 8PX', phone='07999999999')\n db.session.add(new_user)\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='out for delivery')\n db.session.add(new_order)\n new_order = Orders(customer_id=1, order_status='delivered')\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n\n def test_home_get(self):\n response = self.client.get(url_for('home'))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for('add_order'))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for('view_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for('register'))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for('update_order', id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for('delete', id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for('delivered', id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n\n def test_create_user(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test2', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n user = Users.query.filter_by(id=2).first()\n self.assertEqual('[email protected]', user.email)\n self.assertEqual('Test2', user.name)\n self.assertEqual('82', user.house_number)\n self.assertEqual('G2 8PX', user.postcode)\n self.assertEqual('0788888888', user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n\n def test_duplicate_email(self):\n response = self.client.post(url_for('register'), data=dict(email=\n '[email protected]', name='Test', house_number='82', postcode=\n 'G2 8PX', phone='0788888888'), follow_redirects=True)\n\n\nclass TestAddOrder(TestCase):\n\n def test_add_order(self):\n response = self.client.post(url_for('add_order', id=1), data=dict(\n email='[email protected]'), follow_redirects=True)\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual('order placed', order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n\n def test_add_order_no_user(self):\n response = self.client.post(url_for('add_order'), data=dict(email=\n '[email protected]'))\n\n\nclass TestViewOrder(TestCase):\n\n def test_view_order(self):\n response = self.client.get(url_for('view_order', id=1), data=dict(\n id='0006', name='Test', house_number='8', postode='G3 8PX',\n phone='07999999999'))\n self.assertIn(b'0001', response.data)\n self.assertIn(b'Test', response.data)\n self.assertIn(b'8', response.data)\n self.assertIn(b'G3 8PX', response.data)\n self.assertIn(b'07999999999', response.data)\n\n\nclass TestUpdateOrder(TestCase):\n\n def test_update_order(self):\n response = self.client.post(url_for('update_order', id=1), data=\n dict(status='out for delivery', tracking_num_len=8))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('out for delivery', order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n\n def test_delivered(self):\n response = self.client.post(url_for('delivered', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual('delivered', order.order_status)\n\n\nclass TestDelete(TestCase):\n\n def test_delete(self):\n response = self.client.post(url_for('delete', id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n",
"step-5": "from application.routes import pad_num, tracking_gen\nfrom flask import url_for\nfrom flask_testing import TestCase\n\nfrom application import app, db\nfrom application.models import Users, Orders\nfrom os import getenv\n\n\nclass TestCase(TestCase):\n def create_app(self):\n app.config.update(\n SQLALCHEMY_DATABASE_URI=\"sqlite:///test.db\",\n SECRET_KEY=\"TEST_SECRET_KEY\",\n DEBUG=True,\n WTF_CSRF_ENABLED=False,\n )\n return app\n\n def setUp(self):\n db.create_all()\n\n new_user = Users(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"8\",\n postcode=\"G3 8PX\",\n phone=\"07999999999\",\n )\n db.session.add(new_user)\n\n new_order = Orders(customer_id=1)\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"out for delivery\")\n db.session.add(new_order)\n\n new_order = Orders(customer_id=1, order_status=\"delivered\")\n db.session.add(new_order)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass TestPadNum(TestCase):\n def test_pad_num(self):\n self.assertEqual(len(pad_num(3)), 4)\n\n\nclass TestTrackingGen(TestCase):\n def test_tracking_gen(self):\n self.assertEqual(len(tracking_gen()), 8)\n\n\nclass TestViews(TestCase):\n def test_home_get(self):\n response = self.client.get(url_for(\"home\"))\n self.assertEqual(response.status_code, 200)\n\n def test_add_order_get(self):\n response = self.client.get(url_for(\"add_order\"))\n self.assertEqual(response.status_code, 200)\n\n def test_view_order_get(self):\n response = self.client.get(url_for(\"view_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_register_get(self):\n response = self.client.get(url_for(\"register\"))\n self.assertEqual(response.status_code, 200)\n\n def test_update_order_get(self):\n response = self.client.get(url_for(\"update_order\", id=1))\n self.assertEqual(response.status_code, 200)\n\n def test_delete_get(self):\n response = self.client.get(url_for(\"delete\", id=1))\n self.assertEqual(response.status_code, 405)\n\n def test_delivered_get(self):\n response = self.client.get(url_for(\"delivered\", id=1))\n self.assertEqual(response.status_code, 405)\n\n\nclass TestCreateUser(TestCase):\n def test_create_user(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test2\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n user = Users.query.filter_by(id=2).first()\n self.assertEqual(\"[email protected]\", user.email)\n self.assertEqual(\"Test2\", user.name)\n self.assertEqual(\"82\", user.house_number)\n self.assertEqual(\"G2 8PX\", user.postcode)\n self.assertEqual(\"0788888888\", user.phone)\n\n\nclass TestDuplicateEmail(TestCase):\n def test_duplicate_email(self):\n response = self.client.post(\n url_for(\"register\"),\n data=dict(\n email=\"[email protected]\",\n name=\"Test\",\n house_number=\"82\",\n postcode=\"G2 8PX\",\n phone=\"0788888888\",\n ),\n follow_redirects=True,\n )\n\n\nclass TestAddOrder(TestCase):\n def test_add_order(self):\n response = self.client.post(\n url_for(\"add_order\", id=1),\n data=dict(email=\"[email protected]\"),\n follow_redirects=True,\n )\n order = Orders.query.filter_by(id=1).first()\n user = Users.query.filter_by(id=1).first()\n self.assertEqual(1, order.customer_id)\n self.assertEqual(\"order placed\", order.order_status)\n self.assertEqual(None, order.tracking_num)\n self.assertIn(order, user.orders)\n\n\nclass TestAddOrderNoUser(TestCase):\n def test_add_order_no_user(self):\n response = self.client.post(\n url_for(\"add_order\"), data=dict(email=\"[email protected]\")\n )\n\n\nclass TestViewOrder(TestCase):\n def test_view_order(self):\n response = self.client.get(\n url_for(\"view_order\", id=1),\n data=dict(\n id=\"0006\",\n name=\"Test\",\n house_number=\"8\",\n postode=\"G3 8PX\",\n phone=\"07999999999\",\n ),\n )\n self.assertIn(b\"0001\", response.data)\n self.assertIn(b\"Test\", response.data)\n self.assertIn(b\"8\", response.data)\n self.assertIn(b\"G3 8PX\", response.data)\n self.assertIn(b\"07999999999\", response.data)\n\n\nclass TestUpdateOrder(TestCase):\n def test_update_order(self):\n response = self.client.post(\n url_for(\"update_order\", id=1),\n data=dict(\n status=\"out for delivery\",\n tracking_num_len=8,\n ),\n )\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"out for delivery\", order.order_status)\n self.assertEqual(len(order.tracking_num), 8)\n\n\nclass TestDelivered(TestCase):\n def test_delivered(self):\n response = self.client.post(url_for(\"delivered\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(\"delivered\", order.order_status)\n\n\nclass TestDelete(TestCase):\n def test_delete(self):\n response = self.client.post(url_for(\"delete\", id=1))\n order = Orders.query.filter_by(id=1).first()\n self.assertEqual(order, None)\n",
"step-ids": [
20,
27,
32,
33,
34
]
}
|
[
20,
27,
32,
33,
34
] |
'''Finding Perfect Numbers
3/2/17
@author: Annalane Miller (asm9) and Ivanna Rodriguez (imr6)'''
num_perfect = 0
for value in range(2, 10000):
#set initial values
high= value
low = 1
divisors = []
#finding divisors
while low < high:
if value % low ==0:
high = value// low
divisors.append(low)
if high != low:
divisors.append(high)
low += 1
#find if number is perfect
divisors.remove(value)
total= sum(divisors)
#print 4 perfect numbers in range
if total==value:
print(value)
num_perfect +=1
if num_perfect > 4:
break
|
normal
|
{
"blob_id": "1f0349edd9220b663f7469b287f796e4a54df88d",
"index": 6502,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor value in range(2, 10000):\n high = value\n low = 1\n divisors = []\n while low < high:\n if value % low == 0:\n high = value // low\n divisors.append(low)\n if high != low:\n divisors.append(high)\n low += 1\n divisors.remove(value)\n total = sum(divisors)\n if total == value:\n print(value)\n num_perfect += 1\n if num_perfect > 4:\n break\n",
"step-3": "<mask token>\nnum_perfect = 0\nfor value in range(2, 10000):\n high = value\n low = 1\n divisors = []\n while low < high:\n if value % low == 0:\n high = value // low\n divisors.append(low)\n if high != low:\n divisors.append(high)\n low += 1\n divisors.remove(value)\n total = sum(divisors)\n if total == value:\n print(value)\n num_perfect += 1\n if num_perfect > 4:\n break\n",
"step-4": "'''Finding Perfect Numbers\n3/2/17\n@author: Annalane Miller (asm9) and Ivanna Rodriguez (imr6)'''\n\n\nnum_perfect = 0\n\nfor value in range(2, 10000):\n#set initial values\n high= value\n low = 1\n divisors = []\n\n#finding divisors\n while low < high:\n if value % low ==0:\n high = value// low\n divisors.append(low)\n if high != low:\n divisors.append(high)\n low += 1 \n \n \n #find if number is perfect \n divisors.remove(value)\n\n total= sum(divisors)\n \n#print 4 perfect numbers in range\n if total==value:\n print(value)\n num_perfect +=1\n if num_perfect > 4:\n break\n \n \n \n \n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
"""
Package:
pgnumpy
Description
A class and a set of functions for interacting with a PostgreSql database.
A C++ extension module allows returning results as a NumPy array. Numpy
arrays can also be written to tables.
The workhorse class is called PgNumpy
This class has limited functionality compared to the full Python database
api specification. It can execute arbitrary queries and extract results
into numpy arrays. However, cursors are not yet supported. For getting
results, only the fetchall() command is available, as the goal is always to
extract all rows into a single numpy structure rather than work row by row.
More generic DB-API compliant packges like psycopg are more suitable when
more flexible operations are needed.
Classes:
PgNumpy:
The class used in all database interactions. This class represents a
database connection and facilitates executing queries and extracting
results. See docs for pgnumpy.PgNumpy for more details.
PgInput:
A class for writing input files for use in a COPY into the database.
ArrayWriter:
Write arrays to a file for input to postgres. This slower version can
be used if recfile is not available.
ArrayStringifier:
Make a string from an array, possibly with brackets indicating
dimensions.
Convenience Functions:
connect:
Create a database connection, returning a PgNumpy object. If conninfo
is None or "" then the "default" connection based on the PGUSER and
PGDATABASE environment variables is used.
array2table:
Write array with fields (a structure) to a postgres table. If the
table does not yet exist it is created with column definitions based on
the input array. If it does exist the data are appended as new rows in
the table.
"""
import pgnumpy
import cpgnumpy
from pgnumpy import connect
from pgnumpy import PgNumpy
from pgnumpy import PgInput
from pgnumpy import ArrayWriter
from pgnumpy import ArrayStringifier
from pgnumpy import array2table
#from pgnumpy import tables
#from pgnumpy import table_exists
#from pgnumpy import describe
from pgnumpy import test
from pgnumpy import test_simple
#from pgnumpy import obliterate
#from pgnumpy import compare_arrays
# attempt to import the connect method from psycopg2
try:
from psycopg2 import connect
except:
pass
|
normal
|
{
"blob_id": "7e5cf782692d9cfb2718b2efcc83efa2ecb815cd",
"index": 1371,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n from psycopg2 import connect\nexcept:\n pass\n",
"step-3": "<mask token>\nimport pgnumpy\nimport cpgnumpy\nfrom pgnumpy import connect\nfrom pgnumpy import PgNumpy\nfrom pgnumpy import PgInput\nfrom pgnumpy import ArrayWriter\nfrom pgnumpy import ArrayStringifier\nfrom pgnumpy import array2table\nfrom pgnumpy import test\nfrom pgnumpy import test_simple\ntry:\n from psycopg2 import connect\nexcept:\n pass\n",
"step-4": "\"\"\"\nPackage:\n pgnumpy\nDescription\n\n A class and a set of functions for interacting with a PostgreSql database.\n A C++ extension module allows returning results as a NumPy array. Numpy\n arrays can also be written to tables. \n \n The workhorse class is called PgNumpy\n\n This class has limited functionality compared to the full Python database\n api specification. It can execute arbitrary queries and extract results\n into numpy arrays. However, cursors are not yet supported. For getting\n results, only the fetchall() command is available, as the goal is always to\n extract all rows into a single numpy structure rather than work row by row.\n \n More generic DB-API compliant packges like psycopg are more suitable when\n more flexible operations are needed.\n\nClasses:\n PgNumpy: \n The class used in all database interactions. This class represents a\n database connection and facilitates executing queries and extracting\n results. See docs for pgnumpy.PgNumpy for more details.\n PgInput: \n A class for writing input files for use in a COPY into the database.\n ArrayWriter: \n Write arrays to a file for input to postgres. This slower version can\n be used if recfile is not available.\n ArrayStringifier: \n Make a string from an array, possibly with brackets indicating\n dimensions.\n\n\nConvenience Functions:\n\n connect:\n Create a database connection, returning a PgNumpy object. If conninfo\n is None or \"\" then the \"default\" connection based on the PGUSER and\n PGDATABASE environment variables is used.\n\n array2table:\n Write array with fields (a structure) to a postgres table. If the\n table does not yet exist it is created with column definitions based on\n the input array. If it does exist the data are appended as new rows in\n the table. \n\n\"\"\"\n\nimport pgnumpy\nimport cpgnumpy\n\nfrom pgnumpy import connect\nfrom pgnumpy import PgNumpy\nfrom pgnumpy import PgInput\nfrom pgnumpy import ArrayWriter\nfrom pgnumpy import ArrayStringifier\nfrom pgnumpy import array2table\n\n#from pgnumpy import tables\n#from pgnumpy import table_exists\n#from pgnumpy import describe\nfrom pgnumpy import test\nfrom pgnumpy import test_simple\n#from pgnumpy import obliterate\n#from pgnumpy import compare_arrays\n\n# attempt to import the connect method from psycopg2\ntry:\n from psycopg2 import connect\nexcept:\n pass\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, pickle, json, ast
import pandas as pd
from scipy import spatial
import numpy as np
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.svm import LinearSVC
from sklearn.metrics import precision_score, recall_score, f1_score
from datetime import date
from sklearn.neural_network import MLPClassifier
class TaskSolver:
W2V_DICT = dict()
def __init__(self):
pass
def solve(self, task_name, **kwargs):
self.gen_w2v_dict()
if task_name == 'k-nearest-words':
self.task_k_nearest_words(kwargs.get('k'), kwargs.get('word'))
elif task_name == 'synonym-antonym-classification':
self.task_synonym_antonym_classification()
elif task_name == 'test-cosin-similarity-with-visim-400-dataset':
self.test_with_visim_400_data_set()
def task_calculate_cosin_similarity(self, word1, word2, print_to_screen=True):
sim = 0
if word1 in self.W2V_DICT and word2 in self.W2V_DICT:
sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.W2V_DICT[word2])) / 2
if (print_to_screen): print("Độ tương đồng giữa '{}' và '{}' là: {}".format(word1, word2, sim))
return sim
def test_with_visim_400_data_set(self):
visim_400_df = pd.read_csv(
os.path.abspath('./Word-Similarity/datasets/ViSim-400/Visim-400.txt'),
sep="\t")
rs, sim1_arr, sim2_arr = [], [], []
for index, row in visim_400_df.iterrows():
word_1, word_2 = row['Word1'], row['Word2']
sim_1, sim_2 = row['Sim1'], row['Sim2']
if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:
sim = self.task_calculate_cosin_similarity(word_1, word_2, True)
rs.append(sim)
sim1_arr.append(sim_1)
sim2_arr.append(sim_2)
print("Hệ số tương đồng Pearson là: ", stats.pearsonr(rs, sim1_arr))
print("Hệ số tương đồng Spearman là: ", stats.spearmanr(rs, sim1_arr))
def task_k_nearest_words(self, k, word):
k = int(k)
if word not in self.W2V_DICT:
print("Word '{}' not in vocab".format(word))
return
sims = []
for key in self.W2V_DICT:
if key != word:
sims.append({
'key': key,
'sim': self.task_calculate_cosin_similarity(key, word, False)
})
k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0: (k - 1)]
print("{} từ tương đồng nhất với từ '{}' là:".format(k, word))
for w in k_list:
print("Từ {} có độ tương đồng là {}".format(w.get('key'), w.get('sim')))
return k_list
def task_synonym_antonym_classification(self):
self.prepare_data()
self.train_synonym_antonym_classification()
self.test_synonym_antonym_classification()
def test_synonym_antonym_classification(self):
clf = pickle.load(open('./main/model/svm.model', 'rb'))
X_test, Y_test = [], []
for file in [
'./Word-Similarity/datasets/ViCon-400/400_noun_pairs.txt',
'./Word-Similarity/datasets/ViCon-400/400_verb_pairs.txt',
'./Word-Similarity/datasets/ViCon-400/600_adj_pairs.txt'
]:
f = open(file, 'r', encoding="utf8")
for index, line in enumerate(f):
line_arr = line.split()
if index == 0: continue
word1, word2, relation = line_arr[0], line_arr[1], line_arr[2]
if word1 in self.W2V_DICT and word2 in self.W2V_DICT:
vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)
X_test.append(vec)
if relation == 'SYN': Y_test.append(1)
elif relation == 'ANT': Y_test.append(-1)
X_test = X_test
pred = clf.predict(X_test)
print("Test date: {}".format(date.today()))
print("Precision: {}".format(precision_score(Y_test, pred)))
print("Recall: {}".format(recall_score(Y_test, pred)))
print("F1: {}".format(f1_score(Y_test, pred)))
log = """
Test date: {}
Precision: {}
Recall: {}
F1: {}
\n
----------------------------------------
""".format(
date.today(),
precision_score(Y_test, pred),
recall_score(Y_test, pred),
f1_score(Y_test, pred))
log_f = open('./main/log', 'a+')
log_f.write(log)
log_f.close()
def gen_vec_for_synonym_antonym_pair(self, word1, word2):
np_vec1, np_vec2 = np.array(self.W2V_DICT[word1]), np.array(self.W2V_DICT[word2])
return np.concatenate((
np_vec1,
np_vec2,
np_vec1 + np_vec2,
np_vec1 * np_vec2,
np.absolute(np_vec1 - np_vec2),
# np.array([self.task_calculate_cosin_similarity(word1, word2, False)])
), axis=0)
def train_synonym_antonym_classification(self):
X_train, Y_train = pickle.load(open('./main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))
unique, counts = np.unique(Y_train, return_counts=True)
label_count = dict(zip(unique, counts))
clf = MLPClassifier()
clf.fit(X_train, Y_train)
pickle.dump(clf, open('./main/model/svm.model', 'wb+'))
return clf
def prepare_data(self):
X, Y = [], []
for file in [
'./Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt',
'./Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt'
]:
f = open(file, 'r', encoding="utf8")
for index, line in enumerate(f):
line_arr = line.split()
if len(line_arr) < 2: continue
word1, word2 = line_arr[0], line_arr[1]
if word1 in self.W2V_DICT and word2 in self.W2V_DICT:
vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)
X.append(vec)
if os.path.basename(f.name) == 'Antonym_vietnamese.txt': Y.append(-1)
else: Y.append(1)
X, Y = np.array(X), np.array(Y)
pickle.dump(
( X.astype(np.float64), Y ),
open('./main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+')
)
def gen_w2v_dict(self):
with open('./main/dataset/w2v/w2v-dict.json', 'w+') as f:
if f.read(1):
f.seek(0)
self.W2V_DICT = json.load(f)
if not self.W2V_DICT:
with open('./Word-Similarity/word2vec/W2V_150.txt', 'r', encoding="utf8") as f:
for index, line in enumerate(f):
line_arr = line.split()
if index > 1:
self.W2V_DICT.update({line_arr[0]: np.array(line_arr[1:]).astype(float).tolist()})
f = open("./main/dataset/w2v/w2v-dict.json","w+")
f.write(json.dumps(self.W2V_DICT))
f.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Helper")
parser.add_argument(
"--task",
required=True,
metavar="path",
help="""
Task name:
0 => Cosin Similarity
1 => Test Cosine Similarity with Visim-400 dataset
2 => K Nearest Words
3 => Synonym Antonym Classification
""",
)
parser.add_argument(
"--word",
metavar="path",
help="Target word used in 'K Nearest Words' task",
)
parser.add_argument(
"--k",
metavar="path",
help="Number of 'Nearest Words' used in 'K Nearest Words' task",
)
parser.add_argument(
"--word1",
metavar="path",
help="Source word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task",
)
parser.add_argument(
"--word2",
metavar="path",
help="Target word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task",
)
args = parser.parse_args()
task = args.task
k = args.k
word = args.word
word1 = args.word1
word2 = args.word2
switcher = {
'0': 'calculate-cosin-similarity',
'1': 'test-cosin-similarity-with-visim-400-dataset',
'2': 'k-nearest-words',
'3': 'synonym-antonym-classification',
'4': 'predict-synonym-antonym'
}
task_name = switcher.get(task, "Invalid task")
task_solver = TaskSolver()
task_solver.solve(
task_name,
k=k,
word=word,
word1=word1,
word2=word2
)
|
normal
|
{
"blob_id": "c23bd136991bfb41f153321420c2fcfba0c843f4",
"index": 1513,
"step-1": "<mask token>\n\n\nclass TaskSolver:\n <mask token>\n <mask token>\n <mask token>\n\n def task_calculate_cosin_similarity(self, word1, word2, print_to_screen\n =True):\n sim = 0\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.\n W2V_DICT[word2])) / 2\n if print_to_screen:\n print(\"Độ tương đồng giữa '{}' và '{}' là: {}\".format(word1,\n word2, sim))\n return sim\n\n def test_with_visim_400_data_set(self):\n visim_400_df = pd.read_csv(os.path.abspath(\n './Word-Similarity/datasets/ViSim-400/Visim-400.txt'), sep='\\t')\n rs, sim1_arr, sim2_arr = [], [], []\n for index, row in visim_400_df.iterrows():\n word_1, word_2 = row['Word1'], row['Word2']\n sim_1, sim_2 = row['Sim1'], row['Sim2']\n if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:\n sim = self.task_calculate_cosin_similarity(word_1, word_2, True\n )\n rs.append(sim)\n sim1_arr.append(sim_1)\n sim2_arr.append(sim_2)\n print('Hệ số tương đồng Pearson là: ', stats.pearsonr(rs, sim1_arr))\n print('Hệ số tương đồng Spearman là: ', stats.spearmanr(rs, sim1_arr))\n\n def task_k_nearest_words(self, k, word):\n k = int(k)\n if word not in self.W2V_DICT:\n print(\"Word '{}' not in vocab\".format(word))\n return\n sims = []\n for key in self.W2V_DICT:\n if key != word:\n sims.append({'key': key, 'sim': self.\n task_calculate_cosin_similarity(key, word, False)})\n k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0:k - 1]\n print(\"{} từ tương đồng nhất với từ '{}' là:\".format(k, word))\n for w in k_list:\n print('Từ {} có độ tương đồng là {}'.format(w.get('key'), w.get\n ('sim')))\n return k_list\n\n def task_synonym_antonym_classification(self):\n self.prepare_data()\n self.train_synonym_antonym_classification()\n self.test_synonym_antonym_classification()\n <mask token>\n <mask token>\n\n def train_synonym_antonym_classification(self):\n X_train, Y_train = pickle.load(open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))\n unique, counts = np.unique(Y_train, return_counts=True)\n label_count = dict(zip(unique, counts))\n clf = MLPClassifier()\n clf.fit(X_train, Y_train)\n pickle.dump(clf, open('./main/model/svm.model', 'wb+'))\n return clf\n\n def prepare_data(self):\n X, Y = [], []\n for file in [\n './Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt',\n './Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if len(line_arr) < 2:\n continue\n word1, word2 = line_arr[0], line_arr[1]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X.append(vec)\n if os.path.basename(f.name) == 'Antonym_vietnamese.txt':\n Y.append(-1)\n else:\n Y.append(1)\n X, Y = np.array(X), np.array(Y)\n pickle.dump((X.astype(np.float64), Y), open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+'))\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass TaskSolver:\n <mask token>\n\n def __init__(self):\n pass\n <mask token>\n\n def task_calculate_cosin_similarity(self, word1, word2, print_to_screen\n =True):\n sim = 0\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.\n W2V_DICT[word2])) / 2\n if print_to_screen:\n print(\"Độ tương đồng giữa '{}' và '{}' là: {}\".format(word1,\n word2, sim))\n return sim\n\n def test_with_visim_400_data_set(self):\n visim_400_df = pd.read_csv(os.path.abspath(\n './Word-Similarity/datasets/ViSim-400/Visim-400.txt'), sep='\\t')\n rs, sim1_arr, sim2_arr = [], [], []\n for index, row in visim_400_df.iterrows():\n word_1, word_2 = row['Word1'], row['Word2']\n sim_1, sim_2 = row['Sim1'], row['Sim2']\n if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:\n sim = self.task_calculate_cosin_similarity(word_1, word_2, True\n )\n rs.append(sim)\n sim1_arr.append(sim_1)\n sim2_arr.append(sim_2)\n print('Hệ số tương đồng Pearson là: ', stats.pearsonr(rs, sim1_arr))\n print('Hệ số tương đồng Spearman là: ', stats.spearmanr(rs, sim1_arr))\n\n def task_k_nearest_words(self, k, word):\n k = int(k)\n if word not in self.W2V_DICT:\n print(\"Word '{}' not in vocab\".format(word))\n return\n sims = []\n for key in self.W2V_DICT:\n if key != word:\n sims.append({'key': key, 'sim': self.\n task_calculate_cosin_similarity(key, word, False)})\n k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0:k - 1]\n print(\"{} từ tương đồng nhất với từ '{}' là:\".format(k, word))\n for w in k_list:\n print('Từ {} có độ tương đồng là {}'.format(w.get('key'), w.get\n ('sim')))\n return k_list\n\n def task_synonym_antonym_classification(self):\n self.prepare_data()\n self.train_synonym_antonym_classification()\n self.test_synonym_antonym_classification()\n\n def test_synonym_antonym_classification(self):\n clf = pickle.load(open('./main/model/svm.model', 'rb'))\n X_test, Y_test = [], []\n for file in ['./Word-Similarity/datasets/ViCon-400/400_noun_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/400_verb_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/600_adj_pairs.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if index == 0:\n continue\n word1, word2, relation = line_arr[0], line_arr[1], line_arr[2]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X_test.append(vec)\n if relation == 'SYN':\n Y_test.append(1)\n elif relation == 'ANT':\n Y_test.append(-1)\n X_test = X_test\n pred = clf.predict(X_test)\n print('Test date: {}'.format(date.today()))\n print('Precision: {}'.format(precision_score(Y_test, pred)))\n print('Recall: {}'.format(recall_score(Y_test, pred)))\n print('F1: {}'.format(f1_score(Y_test, pred)))\n log = (\n \"\"\"\n Test date: {}\n Precision: {}\n Recall: {}\n F1: {}\n \n\n ----------------------------------------\n \"\"\"\n .format(date.today(), precision_score(Y_test, pred),\n recall_score(Y_test, pred), f1_score(Y_test, pred)))\n log_f = open('./main/log', 'a+')\n log_f.write(log)\n log_f.close()\n\n def gen_vec_for_synonym_antonym_pair(self, word1, word2):\n np_vec1, np_vec2 = np.array(self.W2V_DICT[word1]), np.array(self.\n W2V_DICT[word2])\n return np.concatenate((np_vec1, np_vec2, np_vec1 + np_vec2, np_vec1 *\n np_vec2, np.absolute(np_vec1 - np_vec2)), axis=0)\n\n def train_synonym_antonym_classification(self):\n X_train, Y_train = pickle.load(open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))\n unique, counts = np.unique(Y_train, return_counts=True)\n label_count = dict(zip(unique, counts))\n clf = MLPClassifier()\n clf.fit(X_train, Y_train)\n pickle.dump(clf, open('./main/model/svm.model', 'wb+'))\n return clf\n\n def prepare_data(self):\n X, Y = [], []\n for file in [\n './Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt',\n './Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if len(line_arr) < 2:\n continue\n word1, word2 = line_arr[0], line_arr[1]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X.append(vec)\n if os.path.basename(f.name) == 'Antonym_vietnamese.txt':\n Y.append(-1)\n else:\n Y.append(1)\n X, Y = np.array(X), np.array(Y)\n pickle.dump((X.astype(np.float64), Y), open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+'))\n\n def gen_w2v_dict(self):\n with open('./main/dataset/w2v/w2v-dict.json', 'w+') as f:\n if f.read(1):\n f.seek(0)\n self.W2V_DICT = json.load(f)\n if not self.W2V_DICT:\n with open('./Word-Similarity/word2vec/W2V_150.txt', 'r',\n encoding='utf8') as f:\n for index, line in enumerate(f):\n line_arr = line.split()\n if index > 1:\n self.W2V_DICT.update({line_arr[0]: np.array(\n line_arr[1:]).astype(float).tolist()})\n f = open('./main/dataset/w2v/w2v-dict.json', 'w+')\n f.write(json.dumps(self.W2V_DICT))\n f.close()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass TaskSolver:\n <mask token>\n\n def __init__(self):\n pass\n\n def solve(self, task_name, **kwargs):\n self.gen_w2v_dict()\n if task_name == 'k-nearest-words':\n self.task_k_nearest_words(kwargs.get('k'), kwargs.get('word'))\n elif task_name == 'synonym-antonym-classification':\n self.task_synonym_antonym_classification()\n elif task_name == 'test-cosin-similarity-with-visim-400-dataset':\n self.test_with_visim_400_data_set()\n\n def task_calculate_cosin_similarity(self, word1, word2, print_to_screen\n =True):\n sim = 0\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.\n W2V_DICT[word2])) / 2\n if print_to_screen:\n print(\"Độ tương đồng giữa '{}' và '{}' là: {}\".format(word1,\n word2, sim))\n return sim\n\n def test_with_visim_400_data_set(self):\n visim_400_df = pd.read_csv(os.path.abspath(\n './Word-Similarity/datasets/ViSim-400/Visim-400.txt'), sep='\\t')\n rs, sim1_arr, sim2_arr = [], [], []\n for index, row in visim_400_df.iterrows():\n word_1, word_2 = row['Word1'], row['Word2']\n sim_1, sim_2 = row['Sim1'], row['Sim2']\n if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:\n sim = self.task_calculate_cosin_similarity(word_1, word_2, True\n )\n rs.append(sim)\n sim1_arr.append(sim_1)\n sim2_arr.append(sim_2)\n print('Hệ số tương đồng Pearson là: ', stats.pearsonr(rs, sim1_arr))\n print('Hệ số tương đồng Spearman là: ', stats.spearmanr(rs, sim1_arr))\n\n def task_k_nearest_words(self, k, word):\n k = int(k)\n if word not in self.W2V_DICT:\n print(\"Word '{}' not in vocab\".format(word))\n return\n sims = []\n for key in self.W2V_DICT:\n if key != word:\n sims.append({'key': key, 'sim': self.\n task_calculate_cosin_similarity(key, word, False)})\n k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0:k - 1]\n print(\"{} từ tương đồng nhất với từ '{}' là:\".format(k, word))\n for w in k_list:\n print('Từ {} có độ tương đồng là {}'.format(w.get('key'), w.get\n ('sim')))\n return k_list\n\n def task_synonym_antonym_classification(self):\n self.prepare_data()\n self.train_synonym_antonym_classification()\n self.test_synonym_antonym_classification()\n\n def test_synonym_antonym_classification(self):\n clf = pickle.load(open('./main/model/svm.model', 'rb'))\n X_test, Y_test = [], []\n for file in ['./Word-Similarity/datasets/ViCon-400/400_noun_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/400_verb_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/600_adj_pairs.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if index == 0:\n continue\n word1, word2, relation = line_arr[0], line_arr[1], line_arr[2]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X_test.append(vec)\n if relation == 'SYN':\n Y_test.append(1)\n elif relation == 'ANT':\n Y_test.append(-1)\n X_test = X_test\n pred = clf.predict(X_test)\n print('Test date: {}'.format(date.today()))\n print('Precision: {}'.format(precision_score(Y_test, pred)))\n print('Recall: {}'.format(recall_score(Y_test, pred)))\n print('F1: {}'.format(f1_score(Y_test, pred)))\n log = (\n \"\"\"\n Test date: {}\n Precision: {}\n Recall: {}\n F1: {}\n \n\n ----------------------------------------\n \"\"\"\n .format(date.today(), precision_score(Y_test, pred),\n recall_score(Y_test, pred), f1_score(Y_test, pred)))\n log_f = open('./main/log', 'a+')\n log_f.write(log)\n log_f.close()\n\n def gen_vec_for_synonym_antonym_pair(self, word1, word2):\n np_vec1, np_vec2 = np.array(self.W2V_DICT[word1]), np.array(self.\n W2V_DICT[word2])\n return np.concatenate((np_vec1, np_vec2, np_vec1 + np_vec2, np_vec1 *\n np_vec2, np.absolute(np_vec1 - np_vec2)), axis=0)\n\n def train_synonym_antonym_classification(self):\n X_train, Y_train = pickle.load(open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))\n unique, counts = np.unique(Y_train, return_counts=True)\n label_count = dict(zip(unique, counts))\n clf = MLPClassifier()\n clf.fit(X_train, Y_train)\n pickle.dump(clf, open('./main/model/svm.model', 'wb+'))\n return clf\n\n def prepare_data(self):\n X, Y = [], []\n for file in [\n './Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt',\n './Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if len(line_arr) < 2:\n continue\n word1, word2 = line_arr[0], line_arr[1]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X.append(vec)\n if os.path.basename(f.name) == 'Antonym_vietnamese.txt':\n Y.append(-1)\n else:\n Y.append(1)\n X, Y = np.array(X), np.array(Y)\n pickle.dump((X.astype(np.float64), Y), open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+'))\n\n def gen_w2v_dict(self):\n with open('./main/dataset/w2v/w2v-dict.json', 'w+') as f:\n if f.read(1):\n f.seek(0)\n self.W2V_DICT = json.load(f)\n if not self.W2V_DICT:\n with open('./Word-Similarity/word2vec/W2V_150.txt', 'r',\n encoding='utf8') as f:\n for index, line in enumerate(f):\n line_arr = line.split()\n if index > 1:\n self.W2V_DICT.update({line_arr[0]: np.array(\n line_arr[1:]).astype(float).tolist()})\n f = open('./main/dataset/w2v/w2v-dict.json', 'w+')\n f.write(json.dumps(self.W2V_DICT))\n f.close()\n\n\n<mask token>\n",
"step-4": "import os, pickle, json, ast\nimport pandas as pd\nfrom scipy import spatial\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom datetime import date\nfrom sklearn.neural_network import MLPClassifier\n\n\nclass TaskSolver:\n W2V_DICT = dict()\n\n def __init__(self):\n pass\n\n def solve(self, task_name, **kwargs):\n self.gen_w2v_dict()\n if task_name == 'k-nearest-words':\n self.task_k_nearest_words(kwargs.get('k'), kwargs.get('word'))\n elif task_name == 'synonym-antonym-classification':\n self.task_synonym_antonym_classification()\n elif task_name == 'test-cosin-similarity-with-visim-400-dataset':\n self.test_with_visim_400_data_set()\n\n def task_calculate_cosin_similarity(self, word1, word2, print_to_screen\n =True):\n sim = 0\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.\n W2V_DICT[word2])) / 2\n if print_to_screen:\n print(\"Độ tương đồng giữa '{}' và '{}' là: {}\".format(word1,\n word2, sim))\n return sim\n\n def test_with_visim_400_data_set(self):\n visim_400_df = pd.read_csv(os.path.abspath(\n './Word-Similarity/datasets/ViSim-400/Visim-400.txt'), sep='\\t')\n rs, sim1_arr, sim2_arr = [], [], []\n for index, row in visim_400_df.iterrows():\n word_1, word_2 = row['Word1'], row['Word2']\n sim_1, sim_2 = row['Sim1'], row['Sim2']\n if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:\n sim = self.task_calculate_cosin_similarity(word_1, word_2, True\n )\n rs.append(sim)\n sim1_arr.append(sim_1)\n sim2_arr.append(sim_2)\n print('Hệ số tương đồng Pearson là: ', stats.pearsonr(rs, sim1_arr))\n print('Hệ số tương đồng Spearman là: ', stats.spearmanr(rs, sim1_arr))\n\n def task_k_nearest_words(self, k, word):\n k = int(k)\n if word not in self.W2V_DICT:\n print(\"Word '{}' not in vocab\".format(word))\n return\n sims = []\n for key in self.W2V_DICT:\n if key != word:\n sims.append({'key': key, 'sim': self.\n task_calculate_cosin_similarity(key, word, False)})\n k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0:k - 1]\n print(\"{} từ tương đồng nhất với từ '{}' là:\".format(k, word))\n for w in k_list:\n print('Từ {} có độ tương đồng là {}'.format(w.get('key'), w.get\n ('sim')))\n return k_list\n\n def task_synonym_antonym_classification(self):\n self.prepare_data()\n self.train_synonym_antonym_classification()\n self.test_synonym_antonym_classification()\n\n def test_synonym_antonym_classification(self):\n clf = pickle.load(open('./main/model/svm.model', 'rb'))\n X_test, Y_test = [], []\n for file in ['./Word-Similarity/datasets/ViCon-400/400_noun_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/400_verb_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/600_adj_pairs.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if index == 0:\n continue\n word1, word2, relation = line_arr[0], line_arr[1], line_arr[2]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X_test.append(vec)\n if relation == 'SYN':\n Y_test.append(1)\n elif relation == 'ANT':\n Y_test.append(-1)\n X_test = X_test\n pred = clf.predict(X_test)\n print('Test date: {}'.format(date.today()))\n print('Precision: {}'.format(precision_score(Y_test, pred)))\n print('Recall: {}'.format(recall_score(Y_test, pred)))\n print('F1: {}'.format(f1_score(Y_test, pred)))\n log = (\n \"\"\"\n Test date: {}\n Precision: {}\n Recall: {}\n F1: {}\n \n\n ----------------------------------------\n \"\"\"\n .format(date.today(), precision_score(Y_test, pred),\n recall_score(Y_test, pred), f1_score(Y_test, pred)))\n log_f = open('./main/log', 'a+')\n log_f.write(log)\n log_f.close()\n\n def gen_vec_for_synonym_antonym_pair(self, word1, word2):\n np_vec1, np_vec2 = np.array(self.W2V_DICT[word1]), np.array(self.\n W2V_DICT[word2])\n return np.concatenate((np_vec1, np_vec2, np_vec1 + np_vec2, np_vec1 *\n np_vec2, np.absolute(np_vec1 - np_vec2)), axis=0)\n\n def train_synonym_antonym_classification(self):\n X_train, Y_train = pickle.load(open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))\n unique, counts = np.unique(Y_train, return_counts=True)\n label_count = dict(zip(unique, counts))\n clf = MLPClassifier()\n clf.fit(X_train, Y_train)\n pickle.dump(clf, open('./main/model/svm.model', 'wb+'))\n return clf\n\n def prepare_data(self):\n X, Y = [], []\n for file in [\n './Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt',\n './Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt']:\n f = open(file, 'r', encoding='utf8')\n for index, line in enumerate(f):\n line_arr = line.split()\n if len(line_arr) < 2:\n continue\n word1, word2 = line_arr[0], line_arr[1]\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n X.append(vec)\n if os.path.basename(f.name) == 'Antonym_vietnamese.txt':\n Y.append(-1)\n else:\n Y.append(1)\n X, Y = np.array(X), np.array(Y)\n pickle.dump((X.astype(np.float64), Y), open(\n './main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+'))\n\n def gen_w2v_dict(self):\n with open('./main/dataset/w2v/w2v-dict.json', 'w+') as f:\n if f.read(1):\n f.seek(0)\n self.W2V_DICT = json.load(f)\n if not self.W2V_DICT:\n with open('./Word-Similarity/word2vec/W2V_150.txt', 'r',\n encoding='utf8') as f:\n for index, line in enumerate(f):\n line_arr = line.split()\n if index > 1:\n self.W2V_DICT.update({line_arr[0]: np.array(\n line_arr[1:]).astype(float).tolist()})\n f = open('./main/dataset/w2v/w2v-dict.json', 'w+')\n f.write(json.dumps(self.W2V_DICT))\n f.close()\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Helper')\n parser.add_argument('--task', required=True, metavar='path', help=\n \"\"\"\n Task name: \n 0 => Cosin Similarity\n 1 => Test Cosine Similarity with Visim-400 dataset\n 2 => K Nearest Words\n 3 => Synonym Antonym Classification\n \"\"\"\n )\n parser.add_argument('--word', metavar='path', help=\n \"Target word used in 'K Nearest Words' task\")\n parser.add_argument('--k', metavar='path', help=\n \"Number of 'Nearest Words' used in 'K Nearest Words' task\")\n parser.add_argument('--word1', metavar='path', help=\n \"Source word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task\"\n )\n parser.add_argument('--word2', metavar='path', help=\n \"Target word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task\"\n )\n args = parser.parse_args()\n task = args.task\n k = args.k\n word = args.word\n word1 = args.word1\n word2 = args.word2\n switcher = {'0': 'calculate-cosin-similarity', '1':\n 'test-cosin-similarity-with-visim-400-dataset', '2':\n 'k-nearest-words', '3': 'synonym-antonym-classification', '4':\n 'predict-synonym-antonym'}\n task_name = switcher.get(task, 'Invalid task')\n task_solver = TaskSolver()\n task_solver.solve(task_name, k=k, word=word, word1=word1, word2=word2)\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\nimport os, pickle, json, ast\nimport pandas as pd\nfrom scipy import spatial\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom datetime import date\nfrom sklearn.neural_network import MLPClassifier\n\nclass TaskSolver:\n\n W2V_DICT = dict()\n\n def __init__(self):\n pass\n\n def solve(self, task_name, **kwargs):\n\n self.gen_w2v_dict()\n\n if task_name == 'k-nearest-words':\n self.task_k_nearest_words(kwargs.get('k'), kwargs.get('word'))\n elif task_name == 'synonym-antonym-classification':\n self.task_synonym_antonym_classification()\n elif task_name == 'test-cosin-similarity-with-visim-400-dataset':\n self.test_with_visim_400_data_set()\n\n def task_calculate_cosin_similarity(self, word1, word2, print_to_screen=True):\n\n sim = 0\n\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n\n sim = (2 - spatial.distance.cosine(self.W2V_DICT[word1], self.W2V_DICT[word2])) / 2\n\n if (print_to_screen): print(\"Độ tương đồng giữa '{}' và '{}' là: {}\".format(word1, word2, sim))\n\n return sim\n\n def test_with_visim_400_data_set(self):\n\n visim_400_df = pd.read_csv(\n os.path.abspath('./Word-Similarity/datasets/ViSim-400/Visim-400.txt'), \n sep=\"\\t\")\n\n rs, sim1_arr, sim2_arr = [], [], []\n\n for index, row in visim_400_df.iterrows():\n\n word_1, word_2 = row['Word1'], row['Word2']\n sim_1, sim_2 = row['Sim1'], row['Sim2']\n\n if word_1 in self.W2V_DICT and word_2 in self.W2V_DICT:\n\n sim = self.task_calculate_cosin_similarity(word_1, word_2, True)\n\n rs.append(sim)\n \n sim1_arr.append(sim_1)\n sim2_arr.append(sim_2)\n\n print(\"Hệ số tương đồng Pearson là: \", stats.pearsonr(rs, sim1_arr))\n print(\"Hệ số tương đồng Spearman là: \", stats.spearmanr(rs, sim1_arr))\n\n def task_k_nearest_words(self, k, word):\n\n k = int(k)\n\n if word not in self.W2V_DICT: \n print(\"Word '{}' not in vocab\".format(word))\n return\n\n sims = []\n\n for key in self.W2V_DICT:\n\n if key != word:\n\n sims.append({\n 'key': key,\n 'sim': self.task_calculate_cosin_similarity(key, word, False)\n })\n \n k_list = sorted(sims, key=lambda k: k['sim'], reverse=True)[0: (k - 1)]\n\n print(\"{} từ tương đồng nhất với từ '{}' là:\".format(k, word))\n\n for w in k_list:\n\n print(\"Từ {} có độ tương đồng là {}\".format(w.get('key'), w.get('sim')))\n\n return k_list\n\n def task_synonym_antonym_classification(self):\n\n self.prepare_data()\n\n self.train_synonym_antonym_classification()\n\n self.test_synonym_antonym_classification()\n\n def test_synonym_antonym_classification(self):\n\n clf = pickle.load(open('./main/model/svm.model', 'rb'))\n\n X_test, Y_test = [], []\n\n for file in [\n './Word-Similarity/datasets/ViCon-400/400_noun_pairs.txt', \n './Word-Similarity/datasets/ViCon-400/400_verb_pairs.txt',\n './Word-Similarity/datasets/ViCon-400/600_adj_pairs.txt'\n ]:\n\n f = open(file, 'r', encoding=\"utf8\")\n\n for index, line in enumerate(f):\n\n line_arr = line.split()\n\n if index == 0: continue\n\n word1, word2, relation = line_arr[0], line_arr[1], line_arr[2]\n\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n\n X_test.append(vec)\n\n if relation == 'SYN': Y_test.append(1)\n elif relation == 'ANT': Y_test.append(-1)\n\n X_test = X_test\n pred = clf.predict(X_test)\n\n print(\"Test date: {}\".format(date.today()))\n print(\"Precision: {}\".format(precision_score(Y_test, pred)))\n print(\"Recall: {}\".format(recall_score(Y_test, pred)))\n print(\"F1: {}\".format(f1_score(Y_test, pred)))\n\n log = \"\"\"\n Test date: {}\n Precision: {}\n Recall: {}\n F1: {}\n \\n\n ----------------------------------------\n \"\"\".format(\n date.today(), \n precision_score(Y_test, pred), \n recall_score(Y_test, pred), \n f1_score(Y_test, pred))\n\n log_f = open('./main/log', 'a+')\n\n log_f.write(log)\n\n log_f.close()\n\n def gen_vec_for_synonym_antonym_pair(self, word1, word2):\n\n np_vec1, np_vec2 = np.array(self.W2V_DICT[word1]), np.array(self.W2V_DICT[word2])\n\n return np.concatenate((\n np_vec1,\n np_vec2,\n np_vec1 + np_vec2, \n np_vec1 * np_vec2,\n np.absolute(np_vec1 - np_vec2),\n # np.array([self.task_calculate_cosin_similarity(word1, word2, False)])\n ), axis=0)\n\n def train_synonym_antonym_classification(self):\n\n X_train, Y_train = pickle.load(open('./main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'rb+'))\n\n unique, counts = np.unique(Y_train, return_counts=True)\n\n label_count = dict(zip(unique, counts))\n \n clf = MLPClassifier()\n \n clf.fit(X_train, Y_train)\n\n pickle.dump(clf, open('./main/model/svm.model', 'wb+'))\n\n return clf\n\n def prepare_data(self):\n\n X, Y = [], []\n\n for file in [\n './Word-Similarity/antonym-synonym set/Antonym_vietnamese.txt', \n './Word-Similarity/antonym-synonym set/Synonym_vietnamese.txt'\n ]:\n \n f = open(file, 'r', encoding=\"utf8\")\n\n for index, line in enumerate(f):\n\n line_arr = line.split()\n \n if len(line_arr) < 2: continue\n\n word1, word2 = line_arr[0], line_arr[1]\n\n if word1 in self.W2V_DICT and word2 in self.W2V_DICT:\n\n vec = self.gen_vec_for_synonym_antonym_pair(word1, word2)\n\n X.append(vec)\n\n if os.path.basename(f.name) == 'Antonym_vietnamese.txt': Y.append(-1)\n else: Y.append(1)\n\n\n X, Y = np.array(X), np.array(Y)\n\n pickle.dump(\n ( X.astype(np.float64), Y ),\n open('./main/dataset/antonym-synonym/antonym-synonym-pairs.bin', 'wb+')\n )\n\n def gen_w2v_dict(self):\n with open('./main/dataset/w2v/w2v-dict.json', 'w+') as f:\n if f.read(1):\n\n f.seek(0)\n\n self.W2V_DICT = json.load(f)\n\n if not self.W2V_DICT:\n with open('./Word-Similarity/word2vec/W2V_150.txt', 'r', encoding=\"utf8\") as f:\n\n for index, line in enumerate(f):\n\n line_arr = line.split()\n \n if index > 1:\n\n self.W2V_DICT.update({line_arr[0]: np.array(line_arr[1:]).astype(float).tolist()})\n\n f = open(\"./main/dataset/w2v/w2v-dict.json\",\"w+\")\n\n f.write(json.dumps(self.W2V_DICT))\n\n f.close()\n\nif __name__ == \"__main__\":\n\n import argparse\n\n parser = argparse.ArgumentParser(description=\"Helper\")\n\n parser.add_argument(\n \"--task\",\n required=True,\n metavar=\"path\",\n help=\"\"\"\n Task name: \n 0 => Cosin Similarity\n 1 => Test Cosine Similarity with Visim-400 dataset\n 2 => K Nearest Words\n 3 => Synonym Antonym Classification\n \"\"\",\n )\n\n parser.add_argument(\n \"--word\",\n metavar=\"path\",\n help=\"Target word used in 'K Nearest Words' task\",\n )\n\n parser.add_argument(\n \"--k\",\n metavar=\"path\",\n help=\"Number of 'Nearest Words' used in 'K Nearest Words' task\",\n )\n\n parser.add_argument(\n \"--word1\",\n metavar=\"path\",\n help=\"Source word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task\",\n )\n\n parser.add_argument(\n \"--word2\",\n metavar=\"path\",\n help=\"Target word used in 'Cosin Similarity' and 'Predict Synonym Antonym' task\",\n )\n\n args = parser.parse_args()\n\n task = args.task \n k = args.k \n word = args.word \n word1 = args.word1\n word2 = args.word2\n\n switcher = {\n '0': 'calculate-cosin-similarity',\n '1': 'test-cosin-similarity-with-visim-400-dataset',\n '2': 'k-nearest-words',\n '3': 'synonym-antonym-classification',\n '4': 'predict-synonym-antonym'\n }\n\n task_name = switcher.get(task, \"Invalid task\")\n\n task_solver = TaskSolver()\n\n task_solver.solve(\n task_name, \n k=k,\n word=word,\n word1=word1,\n word2=word2\n )\n",
"step-ids": [
7,
11,
12,
15,
16
]
}
|
[
7,
11,
12,
15,
16
] |
from django.shortcuts import render, redirect
from .models import *
from django.contrib.auth import authenticate ,login,logout
from django.contrib.auth.models import User
from datetime import date
# Create your views here.
def home(request):
if request.method=='GET':
daily_users = User.objects.filter(date_joined__contains=date.today()).count()
return render(request,'home/home.html',{'users':daily_users})
def register(request):
if request.method=='GET':
return render(request,'home/home.html')
else:
name = request.POST['name']
username = request.POST['uname']
email = request.POST['email']
password = request.POST['password']
if name and username and email and password:
if not User.objects.filter(username=username).exists():
user = User.objects.create_user(first_name=name,
username=username,
email=email,
password=password)
u = authenticate(username=username, password=password)
if u is not None:
print("authenticated")
login(request, u)
request.session['id'] = user.id
return redirect('user')
else:
redirect('/')
def login_view(request):
if request.method=='GET':
if 'id' in request.session:
return redirect('user')
return render(request,'home/login.html')
else:
username = request.POST['uname']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
print("user active")
login(request, user)
request.session['id'] = User.objects.filter(username=username).values('id')[0]['id']
return redirect('user')
else:
return render(request, 'home/home.html')
else:
return redirect('/')
def user(request):
if request.method=='GET':
try:
uid = request.GET['id']
except:
uid = request.session['id']
#print(uid)
user = User.objects.get(pk=int(uid))
#print(user.username)
genre = Genres.objects.all()
fbook = UserBook.objects.filter(user=user)
genre_list = []
for i in fbook:
if i.book.genre.id in genre_list:
pass
else:
genre_list.append(i.book.genre.id)
if len(genre_list)!=0:
number = 5//len(genre_list)
isselected = 1
recbook = set()
for i in genre_list:
book = Books.objects.filter(genre=int(i)).order_by('-rating')
while len(recbook)<5:
if len(book)>=number:
for k in range(0,number):
recbook.add(book[k])
else:
for k in range(0,len(book)):
recbook.add(book[k])
break
else:
isselected = 0
recbook =""
return render(request,'home/user.html',{'user':user,'genre':genre,"fbook":fbook,'recbook':recbook,'isset':isselected})
else:
user = User.objects.get(pk=int(request.session['id']))
book = request.POST['book']
userbook = UserBook(
user = user,
book=Books.objects.get(pk=int(book))
)
userbook.save()
return redirect('user')
def genre(request):
if request.method=='GET':
id = request.GET['id']
books = Books.objects.filter(genre=id)
return render(request,'home/genre.html',{'books':books,})
def book(request):
if request.method=='GET':
id = request.GET['id']
book = Books.objects.get(pk=(int(id)))
if UserBook.objects.filter(user=User.objects.get(pk=int(request.session['id'])),book=book).exists():
follow = 1
else:
follow = 0
comment = UserCommentBook.objects.filter(book=book)
return render(request, 'home/book.html',{'book':book,'comment':comment,'follow':follow})
else:
comment = request.POST['comment']
book = request.POST['id']
comment = UserCommentBook(
user = User.objects.get(pk=int(request.session['id'])),
book = Books.objects.get(pk=int(book)),
comment=comment,
)
comment.save()
return redirect('book/?id='+str(book))
def logout_view(request):
logout(request)
return redirect('/')
|
normal
|
{
"blob_id": "4cb601d7fc4023e145c6d510d27507214ddbd2d3",
"index": 809,
"step-1": "<mask token>\n\n\ndef register(request):\n if request.method == 'GET':\n return render(request, 'home/home.html')\n else:\n name = request.POST['name']\n username = request.POST['uname']\n email = request.POST['email']\n password = request.POST['password']\n if name and username and email and password:\n if not User.objects.filter(username=username).exists():\n user = User.objects.create_user(first_name=name, username=\n username, email=email, password=password)\n u = authenticate(username=username, password=password)\n if u is not None:\n print('authenticated')\n login(request, u)\n request.session['id'] = user.id\n return redirect('user')\n else:\n redirect('/')\n\n\ndef login_view(request):\n if request.method == 'GET':\n if 'id' in request.session:\n return redirect('user')\n return render(request, 'home/login.html')\n else:\n username = request.POST['uname']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n print('user active')\n login(request, user)\n request.session['id'] = User.objects.filter(username=username\n ).values('id')[0]['id']\n return redirect('user')\n else:\n return render(request, 'home/home.html')\n else:\n return redirect('/')\n\n\ndef user(request):\n if request.method == 'GET':\n try:\n uid = request.GET['id']\n except:\n uid = request.session['id']\n user = User.objects.get(pk=int(uid))\n genre = Genres.objects.all()\n fbook = UserBook.objects.filter(user=user)\n genre_list = []\n for i in fbook:\n if i.book.genre.id in genre_list:\n pass\n else:\n genre_list.append(i.book.genre.id)\n if len(genre_list) != 0:\n number = 5 // len(genre_list)\n isselected = 1\n recbook = set()\n for i in genre_list:\n book = Books.objects.filter(genre=int(i)).order_by('-rating')\n while len(recbook) < 5:\n if len(book) >= number:\n for k in range(0, number):\n recbook.add(book[k])\n else:\n for k in range(0, len(book)):\n recbook.add(book[k])\n break\n else:\n isselected = 0\n recbook = ''\n return render(request, 'home/user.html', {'user': user, 'genre':\n genre, 'fbook': fbook, 'recbook': recbook, 'isset': isselected})\n else:\n user = User.objects.get(pk=int(request.session['id']))\n book = request.POST['book']\n userbook = UserBook(user=user, book=Books.objects.get(pk=int(book)))\n userbook.save()\n return redirect('user')\n\n\ndef genre(request):\n if request.method == 'GET':\n id = request.GET['id']\n books = Books.objects.filter(genre=id)\n return render(request, 'home/genre.html', {'books': books})\n\n\ndef book(request):\n if request.method == 'GET':\n id = request.GET['id']\n book = Books.objects.get(pk=int(id))\n if UserBook.objects.filter(user=User.objects.get(pk=int(request.\n session['id'])), book=book).exists():\n follow = 1\n else:\n follow = 0\n comment = UserCommentBook.objects.filter(book=book)\n return render(request, 'home/book.html', {'book': book, 'comment':\n comment, 'follow': follow})\n else:\n comment = request.POST['comment']\n book = request.POST['id']\n comment = UserCommentBook(user=User.objects.get(pk=int(request.\n session['id'])), book=Books.objects.get(pk=int(book)), comment=\n comment)\n comment.save()\n return redirect('book/?id=' + str(book))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef register(request):\n if request.method == 'GET':\n return render(request, 'home/home.html')\n else:\n name = request.POST['name']\n username = request.POST['uname']\n email = request.POST['email']\n password = request.POST['password']\n if name and username and email and password:\n if not User.objects.filter(username=username).exists():\n user = User.objects.create_user(first_name=name, username=\n username, email=email, password=password)\n u = authenticate(username=username, password=password)\n if u is not None:\n print('authenticated')\n login(request, u)\n request.session['id'] = user.id\n return redirect('user')\n else:\n redirect('/')\n\n\ndef login_view(request):\n if request.method == 'GET':\n if 'id' in request.session:\n return redirect('user')\n return render(request, 'home/login.html')\n else:\n username = request.POST['uname']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n print('user active')\n login(request, user)\n request.session['id'] = User.objects.filter(username=username\n ).values('id')[0]['id']\n return redirect('user')\n else:\n return render(request, 'home/home.html')\n else:\n return redirect('/')\n\n\ndef user(request):\n if request.method == 'GET':\n try:\n uid = request.GET['id']\n except:\n uid = request.session['id']\n user = User.objects.get(pk=int(uid))\n genre = Genres.objects.all()\n fbook = UserBook.objects.filter(user=user)\n genre_list = []\n for i in fbook:\n if i.book.genre.id in genre_list:\n pass\n else:\n genre_list.append(i.book.genre.id)\n if len(genre_list) != 0:\n number = 5 // len(genre_list)\n isselected = 1\n recbook = set()\n for i in genre_list:\n book = Books.objects.filter(genre=int(i)).order_by('-rating')\n while len(recbook) < 5:\n if len(book) >= number:\n for k in range(0, number):\n recbook.add(book[k])\n else:\n for k in range(0, len(book)):\n recbook.add(book[k])\n break\n else:\n isselected = 0\n recbook = ''\n return render(request, 'home/user.html', {'user': user, 'genre':\n genre, 'fbook': fbook, 'recbook': recbook, 'isset': isselected})\n else:\n user = User.objects.get(pk=int(request.session['id']))\n book = request.POST['book']\n userbook = UserBook(user=user, book=Books.objects.get(pk=int(book)))\n userbook.save()\n return redirect('user')\n\n\ndef genre(request):\n if request.method == 'GET':\n id = request.GET['id']\n books = Books.objects.filter(genre=id)\n return render(request, 'home/genre.html', {'books': books})\n\n\ndef book(request):\n if request.method == 'GET':\n id = request.GET['id']\n book = Books.objects.get(pk=int(id))\n if UserBook.objects.filter(user=User.objects.get(pk=int(request.\n session['id'])), book=book).exists():\n follow = 1\n else:\n follow = 0\n comment = UserCommentBook.objects.filter(book=book)\n return render(request, 'home/book.html', {'book': book, 'comment':\n comment, 'follow': follow})\n else:\n comment = request.POST['comment']\n book = request.POST['id']\n comment = UserCommentBook(user=User.objects.get(pk=int(request.\n session['id'])), book=Books.objects.get(pk=int(book)), comment=\n comment)\n comment.save()\n return redirect('book/?id=' + str(book))\n\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n",
"step-3": "<mask token>\n\n\ndef home(request):\n if request.method == 'GET':\n daily_users = User.objects.filter(date_joined__contains=date.today()\n ).count()\n return render(request, 'home/home.html', {'users': daily_users})\n\n\ndef register(request):\n if request.method == 'GET':\n return render(request, 'home/home.html')\n else:\n name = request.POST['name']\n username = request.POST['uname']\n email = request.POST['email']\n password = request.POST['password']\n if name and username and email and password:\n if not User.objects.filter(username=username).exists():\n user = User.objects.create_user(first_name=name, username=\n username, email=email, password=password)\n u = authenticate(username=username, password=password)\n if u is not None:\n print('authenticated')\n login(request, u)\n request.session['id'] = user.id\n return redirect('user')\n else:\n redirect('/')\n\n\ndef login_view(request):\n if request.method == 'GET':\n if 'id' in request.session:\n return redirect('user')\n return render(request, 'home/login.html')\n else:\n username = request.POST['uname']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n print('user active')\n login(request, user)\n request.session['id'] = User.objects.filter(username=username\n ).values('id')[0]['id']\n return redirect('user')\n else:\n return render(request, 'home/home.html')\n else:\n return redirect('/')\n\n\ndef user(request):\n if request.method == 'GET':\n try:\n uid = request.GET['id']\n except:\n uid = request.session['id']\n user = User.objects.get(pk=int(uid))\n genre = Genres.objects.all()\n fbook = UserBook.objects.filter(user=user)\n genre_list = []\n for i in fbook:\n if i.book.genre.id in genre_list:\n pass\n else:\n genre_list.append(i.book.genre.id)\n if len(genre_list) != 0:\n number = 5 // len(genre_list)\n isselected = 1\n recbook = set()\n for i in genre_list:\n book = Books.objects.filter(genre=int(i)).order_by('-rating')\n while len(recbook) < 5:\n if len(book) >= number:\n for k in range(0, number):\n recbook.add(book[k])\n else:\n for k in range(0, len(book)):\n recbook.add(book[k])\n break\n else:\n isselected = 0\n recbook = ''\n return render(request, 'home/user.html', {'user': user, 'genre':\n genre, 'fbook': fbook, 'recbook': recbook, 'isset': isselected})\n else:\n user = User.objects.get(pk=int(request.session['id']))\n book = request.POST['book']\n userbook = UserBook(user=user, book=Books.objects.get(pk=int(book)))\n userbook.save()\n return redirect('user')\n\n\ndef genre(request):\n if request.method == 'GET':\n id = request.GET['id']\n books = Books.objects.filter(genre=id)\n return render(request, 'home/genre.html', {'books': books})\n\n\ndef book(request):\n if request.method == 'GET':\n id = request.GET['id']\n book = Books.objects.get(pk=int(id))\n if UserBook.objects.filter(user=User.objects.get(pk=int(request.\n session['id'])), book=book).exists():\n follow = 1\n else:\n follow = 0\n comment = UserCommentBook.objects.filter(book=book)\n return render(request, 'home/book.html', {'book': book, 'comment':\n comment, 'follow': follow})\n else:\n comment = request.POST['comment']\n book = request.POST['id']\n comment = UserCommentBook(user=User.objects.get(pk=int(request.\n session['id'])), book=Books.objects.get(pk=int(book)), comment=\n comment)\n comment.save()\n return redirect('book/?id=' + str(book))\n\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n",
"step-4": "from django.shortcuts import render, redirect\nfrom .models import *\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom datetime import date\n\n\ndef home(request):\n if request.method == 'GET':\n daily_users = User.objects.filter(date_joined__contains=date.today()\n ).count()\n return render(request, 'home/home.html', {'users': daily_users})\n\n\ndef register(request):\n if request.method == 'GET':\n return render(request, 'home/home.html')\n else:\n name = request.POST['name']\n username = request.POST['uname']\n email = request.POST['email']\n password = request.POST['password']\n if name and username and email and password:\n if not User.objects.filter(username=username).exists():\n user = User.objects.create_user(first_name=name, username=\n username, email=email, password=password)\n u = authenticate(username=username, password=password)\n if u is not None:\n print('authenticated')\n login(request, u)\n request.session['id'] = user.id\n return redirect('user')\n else:\n redirect('/')\n\n\ndef login_view(request):\n if request.method == 'GET':\n if 'id' in request.session:\n return redirect('user')\n return render(request, 'home/login.html')\n else:\n username = request.POST['uname']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n print('user active')\n login(request, user)\n request.session['id'] = User.objects.filter(username=username\n ).values('id')[0]['id']\n return redirect('user')\n else:\n return render(request, 'home/home.html')\n else:\n return redirect('/')\n\n\ndef user(request):\n if request.method == 'GET':\n try:\n uid = request.GET['id']\n except:\n uid = request.session['id']\n user = User.objects.get(pk=int(uid))\n genre = Genres.objects.all()\n fbook = UserBook.objects.filter(user=user)\n genre_list = []\n for i in fbook:\n if i.book.genre.id in genre_list:\n pass\n else:\n genre_list.append(i.book.genre.id)\n if len(genre_list) != 0:\n number = 5 // len(genre_list)\n isselected = 1\n recbook = set()\n for i in genre_list:\n book = Books.objects.filter(genre=int(i)).order_by('-rating')\n while len(recbook) < 5:\n if len(book) >= number:\n for k in range(0, number):\n recbook.add(book[k])\n else:\n for k in range(0, len(book)):\n recbook.add(book[k])\n break\n else:\n isselected = 0\n recbook = ''\n return render(request, 'home/user.html', {'user': user, 'genre':\n genre, 'fbook': fbook, 'recbook': recbook, 'isset': isselected})\n else:\n user = User.objects.get(pk=int(request.session['id']))\n book = request.POST['book']\n userbook = UserBook(user=user, book=Books.objects.get(pk=int(book)))\n userbook.save()\n return redirect('user')\n\n\ndef genre(request):\n if request.method == 'GET':\n id = request.GET['id']\n books = Books.objects.filter(genre=id)\n return render(request, 'home/genre.html', {'books': books})\n\n\ndef book(request):\n if request.method == 'GET':\n id = request.GET['id']\n book = Books.objects.get(pk=int(id))\n if UserBook.objects.filter(user=User.objects.get(pk=int(request.\n session['id'])), book=book).exists():\n follow = 1\n else:\n follow = 0\n comment = UserCommentBook.objects.filter(book=book)\n return render(request, 'home/book.html', {'book': book, 'comment':\n comment, 'follow': follow})\n else:\n comment = request.POST['comment']\n book = request.POST['id']\n comment = UserCommentBook(user=User.objects.get(pk=int(request.\n session['id'])), book=Books.objects.get(pk=int(book)), comment=\n comment)\n comment.save()\n return redirect('book/?id=' + str(book))\n\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n",
"step-5": "from django.shortcuts import render, redirect\r\nfrom .models import *\r\nfrom django.contrib.auth import authenticate ,login,logout\r\nfrom django.contrib.auth.models import User\r\nfrom datetime import date\r\n# Create your views here.\r\n\r\n\r\ndef home(request):\r\n if request.method=='GET':\r\n daily_users = User.objects.filter(date_joined__contains=date.today()).count()\r\n return render(request,'home/home.html',{'users':daily_users})\r\n\r\n\r\n\r\n\r\n\r\ndef register(request):\r\n if request.method=='GET':\r\n return render(request,'home/home.html')\r\n else:\r\n name = request.POST['name']\r\n username = request.POST['uname']\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n if name and username and email and password:\r\n if not User.objects.filter(username=username).exists():\r\n user = User.objects.create_user(first_name=name,\r\n username=username,\r\n email=email,\r\n password=password)\r\n u = authenticate(username=username, password=password)\r\n if u is not None:\r\n print(\"authenticated\")\r\n login(request, u)\r\n\r\n request.session['id'] = user.id\r\n return redirect('user')\r\n else:\r\n redirect('/')\r\n\r\ndef login_view(request):\r\n if request.method=='GET':\r\n if 'id' in request.session:\r\n return redirect('user')\r\n return render(request,'home/login.html')\r\n\r\n else:\r\n username = request.POST['uname']\r\n password = request.POST['password']\r\n user = authenticate(username=username, password=password)\r\n if user is not None:\r\n if user.is_active:\r\n print(\"user active\")\r\n login(request, user)\r\n request.session['id'] = User.objects.filter(username=username).values('id')[0]['id']\r\n return redirect('user')\r\n else:\r\n return render(request, 'home/home.html')\r\n else:\r\n return redirect('/')\r\n\r\ndef user(request):\r\n if request.method=='GET':\r\n try:\r\n uid = request.GET['id']\r\n except:\r\n uid = request.session['id']\r\n #print(uid)\r\n user = User.objects.get(pk=int(uid))\r\n #print(user.username)\r\n genre = Genres.objects.all()\r\n fbook = UserBook.objects.filter(user=user)\r\n genre_list = []\r\n for i in fbook:\r\n if i.book.genre.id in genre_list:\r\n pass\r\n else:\r\n genre_list.append(i.book.genre.id)\r\n if len(genre_list)!=0:\r\n number = 5//len(genre_list)\r\n isselected = 1\r\n recbook = set()\r\n for i in genre_list:\r\n book = Books.objects.filter(genre=int(i)).order_by('-rating')\r\n while len(recbook)<5:\r\n if len(book)>=number:\r\n for k in range(0,number):\r\n recbook.add(book[k])\r\n else:\r\n for k in range(0,len(book)):\r\n recbook.add(book[k])\r\n break\r\n else:\r\n isselected = 0\r\n recbook =\"\"\r\n return render(request,'home/user.html',{'user':user,'genre':genre,\"fbook\":fbook,'recbook':recbook,'isset':isselected})\r\n else:\r\n user = User.objects.get(pk=int(request.session['id']))\r\n book = request.POST['book']\r\n userbook = UserBook(\r\n user = user,\r\n book=Books.objects.get(pk=int(book))\r\n )\r\n userbook.save()\r\n return redirect('user')\r\n\r\ndef genre(request):\r\n if request.method=='GET':\r\n id = request.GET['id']\r\n books = Books.objects.filter(genre=id)\r\n return render(request,'home/genre.html',{'books':books,})\r\n\r\ndef book(request):\r\n if request.method=='GET':\r\n id = request.GET['id']\r\n book = Books.objects.get(pk=(int(id)))\r\n if UserBook.objects.filter(user=User.objects.get(pk=int(request.session['id'])),book=book).exists():\r\n follow = 1\r\n else:\r\n follow = 0\r\n comment = UserCommentBook.objects.filter(book=book)\r\n return render(request, 'home/book.html',{'book':book,'comment':comment,'follow':follow})\r\n else:\r\n comment = request.POST['comment']\r\n book = request.POST['id']\r\n comment = UserCommentBook(\r\n user = User.objects.get(pk=int(request.session['id'])),\r\n book = Books.objects.get(pk=int(book)),\r\n comment=comment,\r\n )\r\n comment.save()\r\n return redirect('book/?id='+str(book))\r\n\r\ndef logout_view(request):\r\n logout(request)\r\n return redirect('/')",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
#!/usr/bin/env python
import utils
def revcomp(s):
comp = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
return ''.join([comp[c] for c in reversed(s)])
def reverse_palindromes(s):
results = []
l = len(s)
for i in range(l):
for j in range(4, 13):
if i + j > l:
continue
s1 = s[i:i+j]
s2 = revcomp(s1)
if s1 == s2:
results.append((i + 1, j))
return results
if __name__ == "__main__":
seq = utils.load_multifasta('files/rosalind_revp.txt').values()[0]
results = reverse_palindromes(seq)
print "\n".join([' '.join(map(str, r)) for r in results])
|
normal
|
{
"blob_id": "1f40c0ed8e449354a5a87ef18bb07978a9fb8a1c",
"index": 3368,
"step-1": "#!/usr/bin/env python\n\nimport utils\n\ndef revcomp(s):\n comp = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}\n return ''.join([comp[c] for c in reversed(s)])\n\ndef reverse_palindromes(s):\n results = []\n l = len(s)\n for i in range(l):\n for j in range(4, 13):\n if i + j > l:\n continue\n s1 = s[i:i+j]\n s2 = revcomp(s1)\n if s1 == s2:\n results.append((i + 1, j))\n return results\n\nif __name__ == \"__main__\":\n\n seq = utils.load_multifasta('files/rosalind_revp.txt').values()[0]\n results = reverse_palindromes(seq)\nprint \"\\n\".join([' '.join(map(str, r)) for r in results])\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
incremental_factors_file = '../2019_2020_IncrementalFactorsList.csv'
tax_pickle_for_apns = 'kmes_taxes.p'
tax_history_pickle = '../cusd_1percent_tax_history.p'
distribution_pickle_out = 'kmes_distribution.p'
cabrillo_key = 50200
def read_incremental_factors():
import csv
inc_file = open(incremental_factors_file, 'r')
reader = csv.reader(inc_file)
increment_map = dict()
funding_code_map = dict()
this_trn_code = ''
for row in reader:
if row[0] != '':
this_trn_code = row[0].replace('-','')
this_trn = increment_map.get(this_trn_code,{})
this_trn[int(row[1])] = float(row[3])
funding_code_map[int(row[1])] = row[2]
increment_map[this_trn_code] = this_trn
return increment_map, funding_code_map
increment_map, funding_code_map = read_incremental_factors()
import pickle as p
tax_data_apns = p.load(open(tax_pickle_for_apns,'rb'))
apns = list(set([d[0] for d in tax_data_apns]))
apns.sort()
tax_distribution = list()
tax_history = p.load(open(tax_history_pickle,'rb'))
tax_history_apns = [d[0] for d in tax_history]
for apn in apns:
try:
tax_history_index = tax_history_apns.index(apn)
except:
tax_history_index = None
if tax_history_index is None:
print('No Matching APN: ' + apn)
else:
this_tax_history = tax_history[tax_history_index]
total_tax = this_tax_history[3]
tra = this_tax_history[1]
this_tra = increment_map.get(tra, None)
if this_tra is None:
print('TRA is Null for APN: ' + apn)
else:
fraction = this_tra.get(cabrillo_key, None)
if fraction is None:
print('APN: ' + apn + ' is not in district')
else:
tax_distribution += [[this_tax_history[0], this_tax_history[1], this_tax_history[2], fraction, this_tax_history[3], [t*fraction for t in this_tax_history[3]]]]
import numpy as np
district_data = np.array(np.array([x[5] for x in tax_distribution]))
print('District Contributions: ')
district_sum = np.sum(district_data, axis=0)
year = 2007
for ds in district_sum:
print(str(year) + ": " + str(ds))
year += 1
p.dump([tax_distribution, funding_code_map], open(distribution_pickle_out,'wb'))
|
normal
|
{
"blob_id": "18dae039f6455f944cbaa97bcb9c36ed29ac9a21",
"index": 867,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef read_incremental_factors():\n import csv\n inc_file = open(incremental_factors_file, 'r')\n reader = csv.reader(inc_file)\n increment_map = dict()\n funding_code_map = dict()\n this_trn_code = ''\n for row in reader:\n if row[0] != '':\n this_trn_code = row[0].replace('-', '')\n this_trn = increment_map.get(this_trn_code, {})\n this_trn[int(row[1])] = float(row[3])\n funding_code_map[int(row[1])] = row[2]\n increment_map[this_trn_code] = this_trn\n return increment_map, funding_code_map\n\n\n<mask token>\napns.sort()\n<mask token>\nfor apn in apns:\n try:\n tax_history_index = tax_history_apns.index(apn)\n except:\n tax_history_index = None\n if tax_history_index is None:\n print('No Matching APN: ' + apn)\n else:\n this_tax_history = tax_history[tax_history_index]\n total_tax = this_tax_history[3]\n tra = this_tax_history[1]\n this_tra = increment_map.get(tra, None)\n if this_tra is None:\n print('TRA is Null for APN: ' + apn)\n else:\n fraction = this_tra.get(cabrillo_key, None)\n if fraction is None:\n print('APN: ' + apn + ' is not in district')\n else:\n tax_distribution += [[this_tax_history[0], this_tax_history\n [1], this_tax_history[2], fraction, this_tax_history[3],\n [(t * fraction) for t in this_tax_history[3]]]]\n<mask token>\nprint('District Contributions: ')\n<mask token>\nfor ds in district_sum:\n print(str(year) + ': ' + str(ds))\n year += 1\np.dump([tax_distribution, funding_code_map], open(distribution_pickle_out,\n 'wb'))\n",
"step-3": "incremental_factors_file = '../2019_2020_IncrementalFactorsList.csv'\ntax_pickle_for_apns = 'kmes_taxes.p'\ntax_history_pickle = '../cusd_1percent_tax_history.p'\ndistribution_pickle_out = 'kmes_distribution.p'\ncabrillo_key = 50200\n\n\ndef read_incremental_factors():\n import csv\n inc_file = open(incremental_factors_file, 'r')\n reader = csv.reader(inc_file)\n increment_map = dict()\n funding_code_map = dict()\n this_trn_code = ''\n for row in reader:\n if row[0] != '':\n this_trn_code = row[0].replace('-', '')\n this_trn = increment_map.get(this_trn_code, {})\n this_trn[int(row[1])] = float(row[3])\n funding_code_map[int(row[1])] = row[2]\n increment_map[this_trn_code] = this_trn\n return increment_map, funding_code_map\n\n\nincrement_map, funding_code_map = read_incremental_factors()\n<mask token>\ntax_data_apns = p.load(open(tax_pickle_for_apns, 'rb'))\napns = list(set([d[0] for d in tax_data_apns]))\napns.sort()\ntax_distribution = list()\ntax_history = p.load(open(tax_history_pickle, 'rb'))\ntax_history_apns = [d[0] for d in tax_history]\nfor apn in apns:\n try:\n tax_history_index = tax_history_apns.index(apn)\n except:\n tax_history_index = None\n if tax_history_index is None:\n print('No Matching APN: ' + apn)\n else:\n this_tax_history = tax_history[tax_history_index]\n total_tax = this_tax_history[3]\n tra = this_tax_history[1]\n this_tra = increment_map.get(tra, None)\n if this_tra is None:\n print('TRA is Null for APN: ' + apn)\n else:\n fraction = this_tra.get(cabrillo_key, None)\n if fraction is None:\n print('APN: ' + apn + ' is not in district')\n else:\n tax_distribution += [[this_tax_history[0], this_tax_history\n [1], this_tax_history[2], fraction, this_tax_history[3],\n [(t * fraction) for t in this_tax_history[3]]]]\n<mask token>\ndistrict_data = np.array(np.array([x[5] for x in tax_distribution]))\nprint('District Contributions: ')\ndistrict_sum = np.sum(district_data, axis=0)\nyear = 2007\nfor ds in district_sum:\n print(str(year) + ': ' + str(ds))\n year += 1\np.dump([tax_distribution, funding_code_map], open(distribution_pickle_out,\n 'wb'))\n",
"step-4": "incremental_factors_file = '../2019_2020_IncrementalFactorsList.csv'\ntax_pickle_for_apns = 'kmes_taxes.p'\ntax_history_pickle = '../cusd_1percent_tax_history.p'\ndistribution_pickle_out = 'kmes_distribution.p'\ncabrillo_key = 50200\n\n\ndef read_incremental_factors():\n import csv\n inc_file = open(incremental_factors_file, 'r')\n reader = csv.reader(inc_file)\n increment_map = dict()\n funding_code_map = dict()\n this_trn_code = ''\n for row in reader:\n if row[0] != '':\n this_trn_code = row[0].replace('-', '')\n this_trn = increment_map.get(this_trn_code, {})\n this_trn[int(row[1])] = float(row[3])\n funding_code_map[int(row[1])] = row[2]\n increment_map[this_trn_code] = this_trn\n return increment_map, funding_code_map\n\n\nincrement_map, funding_code_map = read_incremental_factors()\nimport pickle as p\ntax_data_apns = p.load(open(tax_pickle_for_apns, 'rb'))\napns = list(set([d[0] for d in tax_data_apns]))\napns.sort()\ntax_distribution = list()\ntax_history = p.load(open(tax_history_pickle, 'rb'))\ntax_history_apns = [d[0] for d in tax_history]\nfor apn in apns:\n try:\n tax_history_index = tax_history_apns.index(apn)\n except:\n tax_history_index = None\n if tax_history_index is None:\n print('No Matching APN: ' + apn)\n else:\n this_tax_history = tax_history[tax_history_index]\n total_tax = this_tax_history[3]\n tra = this_tax_history[1]\n this_tra = increment_map.get(tra, None)\n if this_tra is None:\n print('TRA is Null for APN: ' + apn)\n else:\n fraction = this_tra.get(cabrillo_key, None)\n if fraction is None:\n print('APN: ' + apn + ' is not in district')\n else:\n tax_distribution += [[this_tax_history[0], this_tax_history\n [1], this_tax_history[2], fraction, this_tax_history[3],\n [(t * fraction) for t in this_tax_history[3]]]]\nimport numpy as np\ndistrict_data = np.array(np.array([x[5] for x in tax_distribution]))\nprint('District Contributions: ')\ndistrict_sum = np.sum(district_data, axis=0)\nyear = 2007\nfor ds in district_sum:\n print(str(year) + ': ' + str(ds))\n year += 1\np.dump([tax_distribution, funding_code_map], open(distribution_pickle_out,\n 'wb'))\n",
"step-5": "incremental_factors_file = '../2019_2020_IncrementalFactorsList.csv'\ntax_pickle_for_apns = 'kmes_taxes.p'\ntax_history_pickle = '../cusd_1percent_tax_history.p'\ndistribution_pickle_out = 'kmes_distribution.p'\ncabrillo_key = 50200\n\ndef read_incremental_factors():\n import csv\n inc_file = open(incremental_factors_file, 'r')\n reader = csv.reader(inc_file)\n increment_map = dict()\n funding_code_map = dict()\n this_trn_code = ''\n for row in reader:\n if row[0] != '':\n this_trn_code = row[0].replace('-','')\n this_trn = increment_map.get(this_trn_code,{})\n this_trn[int(row[1])] = float(row[3])\n funding_code_map[int(row[1])] = row[2]\n increment_map[this_trn_code] = this_trn\n return increment_map, funding_code_map\n\nincrement_map, funding_code_map = read_incremental_factors()\nimport pickle as p\ntax_data_apns = p.load(open(tax_pickle_for_apns,'rb'))\napns = list(set([d[0] for d in tax_data_apns]))\napns.sort()\ntax_distribution = list()\ntax_history = p.load(open(tax_history_pickle,'rb'))\ntax_history_apns = [d[0] for d in tax_history]\n\nfor apn in apns:\n try:\n tax_history_index = tax_history_apns.index(apn)\n except:\n tax_history_index = None\n if tax_history_index is None:\n print('No Matching APN: ' + apn)\n else:\n this_tax_history = tax_history[tax_history_index]\n total_tax = this_tax_history[3]\n tra = this_tax_history[1]\n this_tra = increment_map.get(tra, None)\n if this_tra is None:\n print('TRA is Null for APN: ' + apn)\n else:\n fraction = this_tra.get(cabrillo_key, None)\n if fraction is None:\n print('APN: ' + apn + ' is not in district')\n else:\n tax_distribution += [[this_tax_history[0], this_tax_history[1], this_tax_history[2], fraction, this_tax_history[3], [t*fraction for t in this_tax_history[3]]]]\n\nimport numpy as np\n\ndistrict_data = np.array(np.array([x[5] for x in tax_distribution]))\n\nprint('District Contributions: ')\n\ndistrict_sum = np.sum(district_data, axis=0)\nyear = 2007\nfor ds in district_sum:\n print(str(year) + \": \" + str(ds))\n year += 1\n\np.dump([tax_distribution, funding_code_map], open(distribution_pickle_out,'wb'))\n\n",
"step-ids": [
0,
2,
3,
4,
5
]
}
|
[
0,
2,
3,
4,
5
] |
#!/usr/bin/env python
"""
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
"""
import itertools
def euler_29(max_a, max_b):
gen = (a ** b for a, b in itertools.product(range(2, max_a + 1), range(2, max_b + 1)))
return len(set(gen))
if __name__ == "__main__":
print(euler_29(100, 100))
|
normal
|
{
"blob_id": "c93bd042340a6e1d0124d8f6176bdf17ab56e405",
"index": 2229,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef euler_29(max_a, max_b):\n gen = (a ** b for a, b in itertools.product(range(2, max_a + 1), range(\n 2, max_b + 1)))\n return len(set(gen))\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef euler_29(max_a, max_b):\n gen = (a ** b for a, b in itertools.product(range(2, max_a + 1), range(\n 2, max_b + 1)))\n return len(set(gen))\n\n\nif __name__ == '__main__':\n print(euler_29(100, 100))\n",
"step-4": "<mask token>\nimport itertools\n\n\ndef euler_29(max_a, max_b):\n gen = (a ** b for a, b in itertools.product(range(2, max_a + 1), range(\n 2, max_b + 1)))\n return len(set(gen))\n\n\nif __name__ == '__main__':\n print(euler_29(100, 100))\n",
"step-5": "#!/usr/bin/env python\n\"\"\"\nConsider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:\n\n 22=4, 23=8, 24=16, 25=32\n 32=9, 33=27, 34=81, 35=243\n 42=16, 43=64, 44=256, 45=1024\n 52=25, 53=125, 54=625, 55=3125\n\nIf they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:\n\n4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125\n\nHow many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?\n\"\"\"\n\nimport itertools\n\ndef euler_29(max_a, max_b):\n gen = (a ** b for a, b in itertools.product(range(2, max_a + 1), range(2, max_b + 1)))\n return len(set(gen))\n\nif __name__ == \"__main__\":\n print(euler_29(100, 100))\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import configparser
# CONFIG
config = configparser.ConfigParser()
config.read('dwh.cfg')
# DROP TABLES
drop_schema="DROP SCHEMA IF EXISTS sparkifydb;"
set_search_path="SET SEARCH_PATH to sparkifydb;"
staging_events_table_drop = "DROP TABLE IF EXISTS staging_events;"
staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs;"
songplay_table_drop = "DROP TABLE IF EXISTS songplay;"
user_table_drop = "DROP TABLE IF EXISTS sparkifydb.users;"
song_table_drop ="DROP TABLE IF EXISTS sparkifydb.songs;"
artist_table_drop = "DROP TABLE IF EXISTS sparkifydb.artists;"
time_table_drop = "DROP TABLE IF EXISTS sparkifydb.time;"
#CREATE SCHEMA
create_sparkify_schema="CREATE SCHEMA IF NOT EXISTS sparkifydb;"
# CREATE TABLES
staging_events_table_create= ("""
CREATE TABLE staging_events
(
event_id int identity(0,1) SORTKEY,
artist_name text NULL DISTKEY,
auth text NULL,
firstName text NULL,
gender varchar(5) NULL,
itemInSession bigint NULL,
lastName text NULL,
length double precision NULL,
level text NULL,
location text NULL,
method text NULL,
page text NULL,
registration text NULL,
sessionId bigint NULL,
song text NULL,
status int NULL,
ts text NULL,
userAgent text NULL,
userId bigint
);
""")
staging_songs_table_create = ("""
CREATE TABLE staging_songs
(
num_songs int,
artist_id varchar(255) DISTKEY,
artist_latitude varchar(255) NULL,
artist_longitude varchar(255) NULL,
artist_location varchar(255) NULL,
artist_name text NOT NULL,
song_id varchar(255) SORTKEY NOT NULL,
title text NOT NULL,
duration double precision NOT NULL,
year int NULL
);
""")
songplay_table_create = ("""
CREATE TABLE songplay
(
songplay_id int identity(0,1) PRIMARY KEY SORTKEY NOT NULL,
start_time timestamp NOT NULL,
user_id text NOT NULL,
level text,
song_id text NOT NULL,
artist_id text NOT NULL DISTKEY,
session_id text,
location text,
user_agent text);
""")
user_table_create = ("""
CREATE TABLE users(
user_id bigint PRIMARY KEY SORTKEY NOT NULL ,
first_name text,
last_name text,
gender varchar(10),
level text
)diststyle all;
""")
song_table_create = ("""
CREATE TABLE songs(
song_id varchar(255) SORTKEY PRIMARY KEY NOT NULL,
artist_id text NOT NULL,
year int,
duration double precision,
level text
)diststyle all;
""")
artist_table_create = ("""
CREATE TABLE artists(
artist_id text PRIMARY KEY SORTKEY,
artist_name text,
location text,
lattitude text,
longitude text
) diststyle all;
""")
time_table_create = ("""
CREATE TABLE time(
start_time timestamp PRIMARY KEY SORTKEY,
hour int,
day int,
week int,
month int,
year int,
weekday int
) diststyle all;
""")
# STAGING TABLES
staging_events_copy = ("""copy staging_events from '{}'
credentials 'aws_iam_role={}'
compupdate off
region 'us-west-2'
JSON '{}'
""").format(config['S3']['LOG_DATA'],config['IAM_ROLE']['ARN'],config['S3']['LOG_JSONPATH'])
staging_songs_copy = ("""copy staging_songs from '{}'
credentials 'aws_iam_role={}'
compupdate off
region 'us-west-2'
JSON 'auto'
""").format(config['S3']['SONG_DATA'],config['IAM_ROLE']['ARN'])
# FINAL TABLES
songplay_table_insert = ("""
INSERT INTO songplay(start_time,user_id,level,song_id,artist_id,session_id,location,user_agent)
SELECT
TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 Second ' AS start_time,
se.userId AS user_id,
se.level AS level,
ss.song_id AS song_id,
ss.artist_id AS artist_id,
se.sessionId AS session_id,
ss.artist_location AS location,
se.userAgent AS user_agent
FROM staging_songs AS ss
JOIN staging_events AS se ON (ss.title=se.song AND ss.artist_name=se.artist_name)
AND
se.page = 'NextSong';
""")
user_table_insert = ("""
INSERT INTO users(user_id,first_name,last_name,gender,level)
SELECT DISTINCT(s.userId) AS user_id,
s.firstName AS first_name,
s.lastName AS last_name,
s.gender AS gender,
s.level AS level
FROM
staging_events as s
WHERE s.page = 'NextSong'
""")
song_table_insert = ("""
INSERT INTO songs (song_id,artist_id,year, duration)
SELECT DISTINCT(ss.song_id) AS song_id,
ss.artist_id AS artist_id,
ss.year AS year,
ss.duration AS duration
FROM
staging_songs AS ss
""")
artist_table_insert = ("""
INSERT INTO artists (artist_id,artist_name,location,lattitude,longitude)
SELECT DISTINCT(s.artist_id) AS artist_id,
s.artist_name AS artist_name,
s.artist_location AS location,
s.artist_latitude AS lattitude,
s.artist_longitude AS longitude
FROM
staging_songs AS s;
""")
time_table_insert = ("""
INSERT INTO time (start_time,hour,day,week,month,year,weekday)
SELECT DISTINCT(TIMESTAMP 'epoch' + s.ts/1000 * INTERVAL '1 Second ') AS start_time,
EXTRACT(HOUR from start_time) AS hour,
EXTRACT(DAY from start_time) AS day,
EXTRACT(WEEK from start_time) AS week,
EXTRACT(MONTH from start_time) AS month,
EXTRACT(YEAR from start_time) AS year,
EXTRACT(DOW from start_time) AS weekday
FROM
staging_events AS s
WHERE
s.page = 'NextSong';
""")
# QUERY LISTS
create_table_queries =[set_search_path,songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create,staging_events_table_create,staging_songs_table_create]
drop_table_queries = [create_sparkify_schema,set_search_path,staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
copy_table_queries = [set_search_path,staging_events_copy, staging_songs_copy]
insert_table_queries = [set_search_path,user_table_insert, song_table_insert, artist_table_insert, time_table_insert,songplay_table_insert]
|
normal
|
{
"blob_id": "652918e09a3506869c939be39b71a06467459f8a",
"index": 5992,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nconfig.read('dwh.cfg')\n<mask token>\n",
"step-3": "<mask token>\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\ndrop_schema = 'DROP SCHEMA IF EXISTS sparkifydb;'\nset_search_path = 'SET SEARCH_PATH to sparkifydb;'\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nuser_table_drop = 'DROP TABLE IF EXISTS sparkifydb.users;'\nsong_table_drop = 'DROP TABLE IF EXISTS sparkifydb.songs;'\nartist_table_drop = 'DROP TABLE IF EXISTS sparkifydb.artists;'\ntime_table_drop = 'DROP TABLE IF EXISTS sparkifydb.time;'\ncreate_sparkify_schema = 'CREATE SCHEMA IF NOT EXISTS sparkifydb;'\nstaging_events_table_create = \"\"\"\nCREATE TABLE staging_events\n(\nevent_id int identity(0,1) SORTKEY,\nartist_name text NULL DISTKEY,\nauth text NULL,\nfirstName text NULL,\ngender varchar(5) NULL,\nitemInSession bigint NULL,\nlastName text NULL,\nlength double precision NULL,\nlevel text NULL,\nlocation text NULL,\nmethod text NULL,\npage text NULL,\nregistration text NULL,\nsessionId bigint NULL,\nsong text NULL,\nstatus int NULL,\nts text NULL,\nuserAgent text NULL,\nuserId bigint \n);\n\"\"\"\nstaging_songs_table_create = \"\"\"\nCREATE TABLE staging_songs\n(\nnum_songs int,\nartist_id varchar(255) DISTKEY,\nartist_latitude varchar(255) NULL,\nartist_longitude varchar(255) NULL,\nartist_location varchar(255) NULL,\nartist_name text NOT NULL,\nsong_id varchar(255) SORTKEY NOT NULL,\ntitle text NOT NULL,\nduration double precision NOT NULL,\nyear int NULL\n);\n\"\"\"\nsongplay_table_create = \"\"\"\nCREATE TABLE songplay\n(\nsongplay_id int identity(0,1) PRIMARY KEY SORTKEY NOT NULL, \nstart_time timestamp NOT NULL, \nuser_id text NOT NULL, \nlevel text, \nsong_id text NOT NULL, \nartist_id text NOT NULL DISTKEY, \nsession_id text, \nlocation text, \nuser_agent text);\n\"\"\"\nuser_table_create = \"\"\"\nCREATE TABLE users(\nuser_id bigint PRIMARY KEY SORTKEY NOT NULL ,\nfirst_name text,\nlast_name text, \ngender varchar(10),\nlevel text\n)diststyle all;\n\"\"\"\nsong_table_create = \"\"\"\nCREATE TABLE songs(\nsong_id varchar(255) SORTKEY PRIMARY KEY NOT NULL,\nartist_id text NOT NULL,\nyear int, \nduration double precision,\nlevel text\n)diststyle all;\n\"\"\"\nartist_table_create = \"\"\"\nCREATE TABLE artists(\nartist_id text PRIMARY KEY SORTKEY, \nartist_name text, \nlocation text, \nlattitude text, \nlongitude text\n) diststyle all;\n\n\"\"\"\ntime_table_create = \"\"\"\nCREATE TABLE time(\nstart_time timestamp PRIMARY KEY SORTKEY,\nhour int,\nday int,\nweek int,\nmonth int,\nyear int,\nweekday int\n) diststyle all;\n\"\"\"\nstaging_events_copy = (\n \"\"\"copy staging_events from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2'\n JSON '{}'\n\"\"\"\n .format(config['S3']['LOG_DATA'], config['IAM_ROLE']['ARN'], config[\n 'S3']['LOG_JSONPATH']))\nstaging_songs_copy = (\n \"\"\"copy staging_songs from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2' \n JSON 'auto'\n\"\"\"\n .format(config['S3']['SONG_DATA'], config['IAM_ROLE']['ARN']))\nsongplay_table_insert = \"\"\"\nINSERT INTO songplay(start_time,user_id,level,song_id,artist_id,session_id,location,user_agent)\n\nSELECT\n TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 Second ' AS start_time,\n se.userId AS user_id,\n se.level AS level,\n ss.song_id AS song_id,\n ss.artist_id AS artist_id,\n se.sessionId AS session_id,\n ss.artist_location AS location,\n se.userAgent AS user_agent\nFROM staging_songs AS ss \nJOIN staging_events AS se ON (ss.title=se.song AND ss.artist_name=se.artist_name)\nAND\n se.page = 'NextSong';\n \n\"\"\"\nuser_table_insert = \"\"\"\nINSERT INTO users(user_id,first_name,last_name,gender,level)\n\nSELECT DISTINCT(s.userId) AS user_id,\n s.firstName AS first_name,\n s.lastName AS last_name,\n s.gender AS gender,\n s.level AS level\n\nFROM\n staging_events as s\nWHERE s.page = 'NextSong' \n\n\"\"\"\nsong_table_insert = \"\"\"\nINSERT INTO songs (song_id,artist_id,year, duration)\n\nSELECT DISTINCT(ss.song_id) AS song_id,\n ss.artist_id AS artist_id,\n ss.year AS year,\n ss.duration AS duration\nFROM\n staging_songs AS ss\n\n\"\"\"\nartist_table_insert = \"\"\"\nINSERT INTO artists (artist_id,artist_name,location,lattitude,longitude)\n\nSELECT DISTINCT(s.artist_id) AS artist_id,\n s.artist_name AS artist_name,\n s.artist_location AS location,\n s.artist_latitude AS lattitude,\n s.artist_longitude AS longitude\nFROM\n staging_songs AS s;\n\"\"\"\ntime_table_insert = \"\"\"\nINSERT INTO time (start_time,hour,day,week,month,year,weekday)\n\nSELECT DISTINCT(TIMESTAMP 'epoch' + s.ts/1000 * INTERVAL '1 Second ') AS start_time,\n EXTRACT(HOUR from start_time) AS hour,\n EXTRACT(DAY from start_time) AS day,\n EXTRACT(WEEK from start_time) AS week,\n EXTRACT(MONTH from start_time) AS month,\n EXTRACT(YEAR from start_time) AS year,\n EXTRACT(DOW from start_time) AS weekday\nFROM \n staging_events AS s\nWHERE \n s.page = 'NextSong'; \n\n\"\"\"\ncreate_table_queries = [set_search_path, songplay_table_create,\n user_table_create, song_table_create, artist_table_create,\n time_table_create, staging_events_table_create, staging_songs_table_create]\ndrop_table_queries = [create_sparkify_schema, set_search_path,\n staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, user_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [set_search_path, staging_events_copy, staging_songs_copy]\ninsert_table_queries = [set_search_path, user_table_insert,\n song_table_insert, artist_table_insert, time_table_insert,\n songplay_table_insert]\n",
"step-4": "import configparser\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\ndrop_schema = 'DROP SCHEMA IF EXISTS sparkifydb;'\nset_search_path = 'SET SEARCH_PATH to sparkifydb;'\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nuser_table_drop = 'DROP TABLE IF EXISTS sparkifydb.users;'\nsong_table_drop = 'DROP TABLE IF EXISTS sparkifydb.songs;'\nartist_table_drop = 'DROP TABLE IF EXISTS sparkifydb.artists;'\ntime_table_drop = 'DROP TABLE IF EXISTS sparkifydb.time;'\ncreate_sparkify_schema = 'CREATE SCHEMA IF NOT EXISTS sparkifydb;'\nstaging_events_table_create = \"\"\"\nCREATE TABLE staging_events\n(\nevent_id int identity(0,1) SORTKEY,\nartist_name text NULL DISTKEY,\nauth text NULL,\nfirstName text NULL,\ngender varchar(5) NULL,\nitemInSession bigint NULL,\nlastName text NULL,\nlength double precision NULL,\nlevel text NULL,\nlocation text NULL,\nmethod text NULL,\npage text NULL,\nregistration text NULL,\nsessionId bigint NULL,\nsong text NULL,\nstatus int NULL,\nts text NULL,\nuserAgent text NULL,\nuserId bigint \n);\n\"\"\"\nstaging_songs_table_create = \"\"\"\nCREATE TABLE staging_songs\n(\nnum_songs int,\nartist_id varchar(255) DISTKEY,\nartist_latitude varchar(255) NULL,\nartist_longitude varchar(255) NULL,\nartist_location varchar(255) NULL,\nartist_name text NOT NULL,\nsong_id varchar(255) SORTKEY NOT NULL,\ntitle text NOT NULL,\nduration double precision NOT NULL,\nyear int NULL\n);\n\"\"\"\nsongplay_table_create = \"\"\"\nCREATE TABLE songplay\n(\nsongplay_id int identity(0,1) PRIMARY KEY SORTKEY NOT NULL, \nstart_time timestamp NOT NULL, \nuser_id text NOT NULL, \nlevel text, \nsong_id text NOT NULL, \nartist_id text NOT NULL DISTKEY, \nsession_id text, \nlocation text, \nuser_agent text);\n\"\"\"\nuser_table_create = \"\"\"\nCREATE TABLE users(\nuser_id bigint PRIMARY KEY SORTKEY NOT NULL ,\nfirst_name text,\nlast_name text, \ngender varchar(10),\nlevel text\n)diststyle all;\n\"\"\"\nsong_table_create = \"\"\"\nCREATE TABLE songs(\nsong_id varchar(255) SORTKEY PRIMARY KEY NOT NULL,\nartist_id text NOT NULL,\nyear int, \nduration double precision,\nlevel text\n)diststyle all;\n\"\"\"\nartist_table_create = \"\"\"\nCREATE TABLE artists(\nartist_id text PRIMARY KEY SORTKEY, \nartist_name text, \nlocation text, \nlattitude text, \nlongitude text\n) diststyle all;\n\n\"\"\"\ntime_table_create = \"\"\"\nCREATE TABLE time(\nstart_time timestamp PRIMARY KEY SORTKEY,\nhour int,\nday int,\nweek int,\nmonth int,\nyear int,\nweekday int\n) diststyle all;\n\"\"\"\nstaging_events_copy = (\n \"\"\"copy staging_events from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2'\n JSON '{}'\n\"\"\"\n .format(config['S3']['LOG_DATA'], config['IAM_ROLE']['ARN'], config[\n 'S3']['LOG_JSONPATH']))\nstaging_songs_copy = (\n \"\"\"copy staging_songs from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2' \n JSON 'auto'\n\"\"\"\n .format(config['S3']['SONG_DATA'], config['IAM_ROLE']['ARN']))\nsongplay_table_insert = \"\"\"\nINSERT INTO songplay(start_time,user_id,level,song_id,artist_id,session_id,location,user_agent)\n\nSELECT\n TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 Second ' AS start_time,\n se.userId AS user_id,\n se.level AS level,\n ss.song_id AS song_id,\n ss.artist_id AS artist_id,\n se.sessionId AS session_id,\n ss.artist_location AS location,\n se.userAgent AS user_agent\nFROM staging_songs AS ss \nJOIN staging_events AS se ON (ss.title=se.song AND ss.artist_name=se.artist_name)\nAND\n se.page = 'NextSong';\n \n\"\"\"\nuser_table_insert = \"\"\"\nINSERT INTO users(user_id,first_name,last_name,gender,level)\n\nSELECT DISTINCT(s.userId) AS user_id,\n s.firstName AS first_name,\n s.lastName AS last_name,\n s.gender AS gender,\n s.level AS level\n\nFROM\n staging_events as s\nWHERE s.page = 'NextSong' \n\n\"\"\"\nsong_table_insert = \"\"\"\nINSERT INTO songs (song_id,artist_id,year, duration)\n\nSELECT DISTINCT(ss.song_id) AS song_id,\n ss.artist_id AS artist_id,\n ss.year AS year,\n ss.duration AS duration\nFROM\n staging_songs AS ss\n\n\"\"\"\nartist_table_insert = \"\"\"\nINSERT INTO artists (artist_id,artist_name,location,lattitude,longitude)\n\nSELECT DISTINCT(s.artist_id) AS artist_id,\n s.artist_name AS artist_name,\n s.artist_location AS location,\n s.artist_latitude AS lattitude,\n s.artist_longitude AS longitude\nFROM\n staging_songs AS s;\n\"\"\"\ntime_table_insert = \"\"\"\nINSERT INTO time (start_time,hour,day,week,month,year,weekday)\n\nSELECT DISTINCT(TIMESTAMP 'epoch' + s.ts/1000 * INTERVAL '1 Second ') AS start_time,\n EXTRACT(HOUR from start_time) AS hour,\n EXTRACT(DAY from start_time) AS day,\n EXTRACT(WEEK from start_time) AS week,\n EXTRACT(MONTH from start_time) AS month,\n EXTRACT(YEAR from start_time) AS year,\n EXTRACT(DOW from start_time) AS weekday\nFROM \n staging_events AS s\nWHERE \n s.page = 'NextSong'; \n\n\"\"\"\ncreate_table_queries = [set_search_path, songplay_table_create,\n user_table_create, song_table_create, artist_table_create,\n time_table_create, staging_events_table_create, staging_songs_table_create]\ndrop_table_queries = [create_sparkify_schema, set_search_path,\n staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, user_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [set_search_path, staging_events_copy, staging_songs_copy]\ninsert_table_queries = [set_search_path, user_table_insert,\n song_table_insert, artist_table_insert, time_table_insert,\n songplay_table_insert]\n",
"step-5": "import configparser\n\n\n# CONFIG\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\n\n# DROP TABLES\ndrop_schema=\"DROP SCHEMA IF EXISTS sparkifydb;\"\nset_search_path=\"SET SEARCH_PATH to sparkifydb;\"\nstaging_events_table_drop = \"DROP TABLE IF EXISTS staging_events;\"\nstaging_songs_table_drop = \"DROP TABLE IF EXISTS staging_songs;\"\nsongplay_table_drop = \"DROP TABLE IF EXISTS songplay;\"\nuser_table_drop = \"DROP TABLE IF EXISTS sparkifydb.users;\"\nsong_table_drop =\"DROP TABLE IF EXISTS sparkifydb.songs;\"\nartist_table_drop = \"DROP TABLE IF EXISTS sparkifydb.artists;\"\ntime_table_drop = \"DROP TABLE IF EXISTS sparkifydb.time;\"\n\n#CREATE SCHEMA\n\ncreate_sparkify_schema=\"CREATE SCHEMA IF NOT EXISTS sparkifydb;\"\n\n# CREATE TABLES\n\nstaging_events_table_create= (\"\"\"\nCREATE TABLE staging_events\n(\nevent_id int identity(0,1) SORTKEY,\nartist_name text NULL DISTKEY,\nauth text NULL,\nfirstName text NULL,\ngender varchar(5) NULL,\nitemInSession bigint NULL,\nlastName text NULL,\nlength double precision NULL,\nlevel text NULL,\nlocation text NULL,\nmethod text NULL,\npage text NULL,\nregistration text NULL,\nsessionId bigint NULL,\nsong text NULL,\nstatus int NULL,\nts text NULL,\nuserAgent text NULL,\nuserId bigint \n);\n\"\"\")\n\nstaging_songs_table_create = (\"\"\"\nCREATE TABLE staging_songs\n(\nnum_songs int,\nartist_id varchar(255) DISTKEY,\nartist_latitude varchar(255) NULL,\nartist_longitude varchar(255) NULL,\nartist_location varchar(255) NULL,\nartist_name text NOT NULL,\nsong_id varchar(255) SORTKEY NOT NULL,\ntitle text NOT NULL,\nduration double precision NOT NULL,\nyear int NULL\n);\n\"\"\")\n\nsongplay_table_create = (\"\"\"\nCREATE TABLE songplay\n(\nsongplay_id int identity(0,1) PRIMARY KEY SORTKEY NOT NULL, \nstart_time timestamp NOT NULL, \nuser_id text NOT NULL, \nlevel text, \nsong_id text NOT NULL, \nartist_id text NOT NULL DISTKEY, \nsession_id text, \nlocation text, \nuser_agent text);\n\"\"\")\n\nuser_table_create = (\"\"\"\nCREATE TABLE users(\nuser_id bigint PRIMARY KEY SORTKEY NOT NULL ,\nfirst_name text,\nlast_name text, \ngender varchar(10),\nlevel text\n)diststyle all;\n\"\"\")\n\nsong_table_create = (\"\"\"\nCREATE TABLE songs(\nsong_id varchar(255) SORTKEY PRIMARY KEY NOT NULL,\nartist_id text NOT NULL,\nyear int, \nduration double precision,\nlevel text\n)diststyle all;\n\"\"\")\n\nartist_table_create = (\"\"\"\nCREATE TABLE artists(\nartist_id text PRIMARY KEY SORTKEY, \nartist_name text, \nlocation text, \nlattitude text, \nlongitude text\n) diststyle all;\n\n\"\"\")\n\ntime_table_create = (\"\"\"\nCREATE TABLE time(\nstart_time timestamp PRIMARY KEY SORTKEY,\nhour int,\nday int,\nweek int,\nmonth int,\nyear int,\nweekday int\n) diststyle all;\n\"\"\")\n\n# STAGING TABLES\n\nstaging_events_copy = (\"\"\"copy staging_events from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2'\n JSON '{}'\n\"\"\").format(config['S3']['LOG_DATA'],config['IAM_ROLE']['ARN'],config['S3']['LOG_JSONPATH'])\n\nstaging_songs_copy = (\"\"\"copy staging_songs from '{}'\n credentials 'aws_iam_role={}'\n compupdate off \n region 'us-west-2' \n JSON 'auto'\n\"\"\").format(config['S3']['SONG_DATA'],config['IAM_ROLE']['ARN'])\n\n# FINAL TABLES\n\nsongplay_table_insert = (\"\"\"\nINSERT INTO songplay(start_time,user_id,level,song_id,artist_id,session_id,location,user_agent)\n\nSELECT\n TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 Second ' AS start_time,\n se.userId AS user_id,\n se.level AS level,\n ss.song_id AS song_id,\n ss.artist_id AS artist_id,\n se.sessionId AS session_id,\n ss.artist_location AS location,\n se.userAgent AS user_agent\nFROM staging_songs AS ss \nJOIN staging_events AS se ON (ss.title=se.song AND ss.artist_name=se.artist_name)\nAND\n se.page = 'NextSong';\n \n\"\"\")\n\nuser_table_insert = (\"\"\"\nINSERT INTO users(user_id,first_name,last_name,gender,level)\n\nSELECT DISTINCT(s.userId) AS user_id,\n s.firstName AS first_name,\n s.lastName AS last_name,\n s.gender AS gender,\n s.level AS level\n\nFROM\n staging_events as s\nWHERE s.page = 'NextSong' \n\n\"\"\")\n\nsong_table_insert = (\"\"\"\nINSERT INTO songs (song_id,artist_id,year, duration)\n\nSELECT DISTINCT(ss.song_id) AS song_id,\n ss.artist_id AS artist_id,\n ss.year AS year,\n ss.duration AS duration\nFROM\n staging_songs AS ss\n\n\"\"\")\n\nartist_table_insert = (\"\"\"\nINSERT INTO artists (artist_id,artist_name,location,lattitude,longitude)\n\nSELECT DISTINCT(s.artist_id) AS artist_id,\n s.artist_name AS artist_name,\n s.artist_location AS location,\n s.artist_latitude AS lattitude,\n s.artist_longitude AS longitude\nFROM\n staging_songs AS s;\n\"\"\")\n\ntime_table_insert = (\"\"\"\nINSERT INTO time (start_time,hour,day,week,month,year,weekday)\n\nSELECT DISTINCT(TIMESTAMP 'epoch' + s.ts/1000 * INTERVAL '1 Second ') AS start_time,\n EXTRACT(HOUR from start_time) AS hour,\n EXTRACT(DAY from start_time) AS day,\n EXTRACT(WEEK from start_time) AS week,\n EXTRACT(MONTH from start_time) AS month,\n EXTRACT(YEAR from start_time) AS year,\n EXTRACT(DOW from start_time) AS weekday\nFROM \n staging_events AS s\nWHERE \n s.page = 'NextSong'; \n\n\"\"\")\n\n# QUERY LISTS\n\ncreate_table_queries =[set_search_path,songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create,staging_events_table_create,staging_songs_table_create]\n\ndrop_table_queries = [create_sparkify_schema,set_search_path,staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]\n\ncopy_table_queries = [set_search_path,staging_events_copy, staging_songs_copy]\n\ninsert_table_queries = [set_search_path,user_table_insert, song_table_insert, artist_table_insert, time_table_insert,songplay_table_insert]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
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
] |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# pylint: disable=dangerous-default-value,wrong-import-position,unused-import, import-outside-toplevel
def create_app(settings_override={}):
app = Flask(__name__)
app.config.from_object('zezin.settings.Configuration')
app.config.update(settings_override)
db.init_app(app)
from zezin.views import partners_routes
app.register_blueprint(blueprint=partners_routes)
return app
import zezin.models # isort:skip
|
normal
|
{
"blob_id": "6affc182f5d3353d46f6e9a21344bc85bf894165",
"index": 948,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef create_app(settings_override={}):\n app = Flask(__name__)\n app.config.from_object('zezin.settings.Configuration')\n app.config.update(settings_override)\n db.init_app(app)\n from zezin.views import partners_routes\n app.register_blueprint(blueprint=partners_routes)\n return app\n\n\n<mask token>\n",
"step-3": "<mask token>\ndb = SQLAlchemy()\n\n\ndef create_app(settings_override={}):\n app = Flask(__name__)\n app.config.from_object('zezin.settings.Configuration')\n app.config.update(settings_override)\n db.init_app(app)\n from zezin.views import partners_routes\n app.register_blueprint(blueprint=partners_routes)\n return app\n\n\n<mask token>\n",
"step-4": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\ndb = SQLAlchemy()\n\n\ndef create_app(settings_override={}):\n app = Flask(__name__)\n app.config.from_object('zezin.settings.Configuration')\n app.config.update(settings_override)\n db.init_app(app)\n from zezin.views import partners_routes\n app.register_blueprint(blueprint=partners_routes)\n return app\n\n\nimport zezin.models\n",
"step-5": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\n\n# pylint: disable=dangerous-default-value,wrong-import-position,unused-import, import-outside-toplevel\ndef create_app(settings_override={}):\n app = Flask(__name__)\n app.config.from_object('zezin.settings.Configuration')\n app.config.update(settings_override)\n\n db.init_app(app)\n\n from zezin.views import partners_routes\n\n app.register_blueprint(blueprint=partners_routes)\n\n return app\n\n\nimport zezin.models # isort:skip\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 11:43:58 2020
@author: Dr. Tang
"""
import tensorflow as tf
# 需要你编程:将下面转换成tensorflow
#x = 10
#y = 2
#u=x/y
#z = u- 1
x=tf.placeholder(tf.int32)
y=tf.placeholder(tf.int32)
u=tf.divide(x,y)
z=tf.subtract(u,tf.constant(1.0,dtype=tf.float64))
# 需要你编程:从session中打印 z
with tf.Session() as sess:
output=sess.run(z,feed_dict={x:10,y:2})
print(output)
|
normal
|
{
"blob_id": "ca91052072d7b2da5729cf55f7f4ba4b54608017",
"index": 3477,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith tf.Session() as sess:\n output = sess.run(z, feed_dict={x: 10, y: 2})\n print(output)\n",
"step-3": "<mask token>\nx = tf.placeholder(tf.int32)\ny = tf.placeholder(tf.int32)\nu = tf.divide(x, y)\nz = tf.subtract(u, tf.constant(1.0, dtype=tf.float64))\nwith tf.Session() as sess:\n output = sess.run(z, feed_dict={x: 10, y: 2})\n print(output)\n",
"step-4": "<mask token>\nimport tensorflow as tf\nx = tf.placeholder(tf.int32)\ny = tf.placeholder(tf.int32)\nu = tf.divide(x, y)\nz = tf.subtract(u, tf.constant(1.0, dtype=tf.float64))\nwith tf.Session() as sess:\n output = sess.run(z, feed_dict={x: 10, y: 2})\n print(output)\n",
"step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 13 11:43:58 2020\n\n@author: Dr. Tang\n\"\"\"\n\nimport tensorflow as tf\n# 需要你编程:将下面转换成tensorflow\n#x = 10\n#y = 2\n#u=x/y\n#z = u- 1\n\nx=tf.placeholder(tf.int32)\ny=tf.placeholder(tf.int32)\nu=tf.divide(x,y)\nz=tf.subtract(u,tf.constant(1.0,dtype=tf.float64))\n# 需要你编程:从session中打印 z\nwith tf.Session() as sess:\n output=sess.run(z,feed_dict={x:10,y:2})\n print(output)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import tensorflow as tf
from model import CabbageModel
import numpy as np
from krx import KrxCrawler
from naver_stock import StockModel as sm
from scattertest import scattertest as st
class CabbageController:
def __init__(self):
#def __init__(self, avg_temp, min_temp, max_temp, rain_fall):
#self._avg_temp = avg_temp
#self._min_temp = min_temp
#self._max_temp= max_temp
#self._rain_fall = rain_fall
self._avg_temp = 1
self._min_temp = 2
self._max_temp = 3
self._rain_fall = 4
def service(self):
#NONE -> 행 값
#4 -> 열 값
X = tf.placeholder(tf.float32, shape=[None,4])
#Y는 미래의 값이기 때문에 현재 존재할 수 가없다. Y의 값을 예측하는 것
W = tf.Variable(tf.random_normal([4,1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
saver = tf.train.Saver()
#텐서 세션의 영역
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess, 'cabbage/saved_model/saved.ckpt')
#매트릭스 구조
data = [[self._avg_temp, self._min_temp, self._max_temp, self._rain_fall],]
arr = np.array(data, dtype = np.float32)
dict = sess.run(tf.matmul(X,W) +b,{X: arr[0:4]})
return dict[0]
def exec(self, flag):
if flag == 'd':
url = "http://kind.krx.co.kr/disclosureSimpleSearch.do?method=disclosureSimpleSearchMain"
d = KrxCrawler(url)
d.scrap()
elif flag == 'e':
url = ''
e = sm('005930')
e.selWeb()
#e.scrap()
elif flag == 'f':
scat = st()
scat.test()
|
normal
|
{
"blob_id": "90a220775efcc8ff9e83f1a1f011f424ddc3476d",
"index": 4487,
"step-1": "<mask token>\n\n\nclass CabbageController:\n <mask token>\n\n def service(self):\n X = tf.placeholder(tf.float32, shape=[None, 4])\n W = tf.Variable(tf.random_normal([4, 1]), name='weight')\n b = tf.Variable(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, 'cabbage/saved_model/saved.ckpt')\n data = [[self._avg_temp, self._min_temp, self._max_temp, self.\n _rain_fall]]\n arr = np.array(data, dtype=np.float32)\n dict = sess.run(tf.matmul(X, W) + b, {X: arr[0:4]})\n return dict[0]\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CabbageController:\n\n def __init__(self):\n self._avg_temp = 1\n self._min_temp = 2\n self._max_temp = 3\n self._rain_fall = 4\n\n def service(self):\n X = tf.placeholder(tf.float32, shape=[None, 4])\n W = tf.Variable(tf.random_normal([4, 1]), name='weight')\n b = tf.Variable(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, 'cabbage/saved_model/saved.ckpt')\n data = [[self._avg_temp, self._min_temp, self._max_temp, self.\n _rain_fall]]\n arr = np.array(data, dtype=np.float32)\n dict = sess.run(tf.matmul(X, W) + b, {X: arr[0:4]})\n return dict[0]\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass CabbageController:\n\n def __init__(self):\n self._avg_temp = 1\n self._min_temp = 2\n self._max_temp = 3\n self._rain_fall = 4\n\n def service(self):\n X = tf.placeholder(tf.float32, shape=[None, 4])\n W = tf.Variable(tf.random_normal([4, 1]), name='weight')\n b = tf.Variable(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, 'cabbage/saved_model/saved.ckpt')\n data = [[self._avg_temp, self._min_temp, self._max_temp, self.\n _rain_fall]]\n arr = np.array(data, dtype=np.float32)\n dict = sess.run(tf.matmul(X, W) + b, {X: arr[0:4]})\n return dict[0]\n\n def exec(self, flag):\n if flag == 'd':\n url = (\n 'http://kind.krx.co.kr/disclosureSimpleSearch.do?method=disclosureSimpleSearchMain'\n )\n d = KrxCrawler(url)\n d.scrap()\n elif flag == 'e':\n url = ''\n e = sm('005930')\n e.selWeb()\n elif flag == 'f':\n scat = st()\n scat.test()\n",
"step-4": "import tensorflow as tf\nfrom model import CabbageModel\nimport numpy as np\nfrom krx import KrxCrawler\nfrom naver_stock import StockModel as sm\nfrom scattertest import scattertest as st\n\n\nclass CabbageController:\n\n def __init__(self):\n self._avg_temp = 1\n self._min_temp = 2\n self._max_temp = 3\n self._rain_fall = 4\n\n def service(self):\n X = tf.placeholder(tf.float32, shape=[None, 4])\n W = tf.Variable(tf.random_normal([4, 1]), name='weight')\n b = tf.Variable(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, 'cabbage/saved_model/saved.ckpt')\n data = [[self._avg_temp, self._min_temp, self._max_temp, self.\n _rain_fall]]\n arr = np.array(data, dtype=np.float32)\n dict = sess.run(tf.matmul(X, W) + b, {X: arr[0:4]})\n return dict[0]\n\n def exec(self, flag):\n if flag == 'd':\n url = (\n 'http://kind.krx.co.kr/disclosureSimpleSearch.do?method=disclosureSimpleSearchMain'\n )\n d = KrxCrawler(url)\n d.scrap()\n elif flag == 'e':\n url = ''\n e = sm('005930')\n e.selWeb()\n elif flag == 'f':\n scat = st()\n scat.test()\n",
"step-5": "import tensorflow as tf\nfrom model import CabbageModel\nimport numpy as np\nfrom krx import KrxCrawler\nfrom naver_stock import StockModel as sm\nfrom scattertest import scattertest as st\n\nclass CabbageController:\n def __init__(self):\n #def __init__(self, avg_temp, min_temp, max_temp, rain_fall):\n #self._avg_temp = avg_temp\n #self._min_temp = min_temp\n #self._max_temp= max_temp\n #self._rain_fall = rain_fall\n self._avg_temp = 1\n self._min_temp = 2\n self._max_temp = 3\n self._rain_fall = 4\n\n def service(self):\n #NONE -> 행 값\n #4 -> 열 값\n X = tf.placeholder(tf.float32, shape=[None,4])\n #Y는 미래의 값이기 때문에 현재 존재할 수 가없다. Y의 값을 예측하는 것\n W = tf.Variable(tf.random_normal([4,1]), name='weight')\n b = tf.Variable(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n #텐서 세션의 영역\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, 'cabbage/saved_model/saved.ckpt')\n #매트릭스 구조\n data = [[self._avg_temp, self._min_temp, self._max_temp, self._rain_fall],]\n arr = np.array(data, dtype = np.float32)\n dict = sess.run(tf.matmul(X,W) +b,{X: arr[0:4]})\n return dict[0]\n\n def exec(self, flag):\n if flag == 'd':\n url = \"http://kind.krx.co.kr/disclosureSimpleSearch.do?method=disclosureSimpleSearchMain\"\n d = KrxCrawler(url)\n d.scrap()\n elif flag == 'e':\n url = ''\n e = sm('005930')\n e.selWeb()\n #e.scrap()\n elif flag == 'f':\n scat = st()\n scat.test()",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
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
] |
import math
class Rank:
class Stats(object):
'''Holds info used to calculate amount of xp a player gets'''
post_likes = 0
post_dislikes = 0
comment_likes = 0
comment_dislikes = 0
usage = 0
class Interval(object):
'''A class representing an interval. It is always [a, b).'''
def __init__(self, a, b):
self.a = a
self.b = b
def contains(self, n):
return self.a >= n and n < b
# Each index in this array corresponds to the level for that xp interval.
XP_INTERVALS = [
Interval(0, 100),
Interval(100, 250),
Interval(250, 1000),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
Interval(100, 250),
]
STAT_WORTH = {
'post_likes': 1,
'post_dislikes': -1,
'comment_likes': 1,
'comment_dislikes': -1,
'usage': 1
}
# Tweaks how far apart each of the levels are. For example, the closer to
# zero this is, the further apart the levels.
LEVEL_RATE = 0.2
def __init__(self):
self._xp = 0
self._level = 0
self._label = ''
def consume_stats(self, stats):
total_arr = [
STAT_WORTH['post_likes']*stats.post_likes,
STAT_WORTH['post_dislikes']*stats.post_dislikes,
STAT_WORTH['comment_likes']*stats.comment_likes,
STAT_WORTH['comment_dislikes']*stats.comment_dislikes,
STAT_WORTH['usage']*stats.usage,
]
self._xp = sum(total_arr)
self._level = self._calculate_level()
def _calculate_level(self):
return math.sqrt(LEVEL_RATE*self._xp)
def from_model(self):
pass
def from_proto(self):
pass
def to_model(self):
pass
def to_proto(self):
pass
|
normal
|
{
"blob_id": "cd0b55e163851344273ad020d434cc8662083d19",
"index": 6593,
"step-1": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n",
"step-2": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n",
"step-3": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def consume_stats(self, stats):\n total_arr = [STAT_WORTH['post_likes'] * stats.post_likes, \n STAT_WORTH['post_dislikes'] * stats.post_dislikes, STAT_WORTH[\n 'comment_likes'] * stats.comment_likes, STAT_WORTH[\n 'comment_dislikes'] * stats.comment_dislikes, STAT_WORTH[\n 'usage'] * stats.usage]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n",
"step-4": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n XP_INTERVALS = [Interval(0, 100), Interval(100, 250), Interval(250, \n 1000), Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250)]\n STAT_WORTH = {'post_likes': 1, 'post_dislikes': -1, 'comment_likes': 1,\n 'comment_dislikes': -1, 'usage': 1}\n LEVEL_RATE = 0.2\n\n def __init__(self):\n self._xp = 0\n self._level = 0\n self._label = ''\n\n def consume_stats(self, stats):\n total_arr = [STAT_WORTH['post_likes'] * stats.post_likes, \n STAT_WORTH['post_dislikes'] * stats.post_dislikes, STAT_WORTH[\n 'comment_likes'] * stats.comment_likes, STAT_WORTH[\n 'comment_dislikes'] * stats.comment_dislikes, STAT_WORTH[\n 'usage'] * stats.usage]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n",
"step-5": "import math\n\nclass Rank:\n\n class Stats(object):\n '''Holds info used to calculate amount of xp a player gets'''\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n class Interval(object):\n '''A class representing an interval. It is always [a, b).'''\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n\n # Each index in this array corresponds to the level for that xp interval.\n XP_INTERVALS = [\n Interval(0, 100),\n Interval(100, 250),\n Interval(250, 1000),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n ]\n\n STAT_WORTH = {\n 'post_likes': 1,\n 'post_dislikes': -1,\n 'comment_likes': 1,\n 'comment_dislikes': -1,\n 'usage': 1\n }\n\n # Tweaks how far apart each of the levels are. For example, the closer to\n # zero this is, the further apart the levels.\n LEVEL_RATE = 0.2\n\n def __init__(self):\n self._xp = 0\n self._level = 0\n self._label = ''\n\n def consume_stats(self, stats):\n total_arr = [\n STAT_WORTH['post_likes']*stats.post_likes,\n STAT_WORTH['post_dislikes']*stats.post_dislikes,\n STAT_WORTH['comment_likes']*stats.comment_likes,\n STAT_WORTH['comment_dislikes']*stats.comment_dislikes,\n STAT_WORTH['usage']*stats.usage,\n ]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE*self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n",
"step-ids": [
5,
6,
7,
9,
11
]
}
|
[
5,
6,
7,
9,
11
] |
# Compute grid scores using the new dataset format
import matplotlib
import os
# allow code to work on machines without a display or in a screen session
display = os.environ.get('DISPLAY')
if display is None or 'localhost' in display:
matplotlib.use('agg')
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from datasets import train_test_loaders, angular_train_test_loaders, tf_train_test_loaders, load_from_cache
from models import SSPPathIntegrationModel
from datetime import datetime
from tensorboardX import SummaryWriter
import json
from spatial_semantic_pointers.utils import get_heatmap_vectors, ssp_to_loc, ssp_to_loc_v
from spatial_semantic_pointers.plots import plot_predictions, plot_predictions_v
import matplotlib.pyplot as plt
from path_integration_utils import pc_to_loc_v, encoding_func_from_model, pc_gauss_encoding_func, ssp_encoding_func, \
hd_gauss_encoding_func, hex_trig_encoding_func
from ssp_navigation.utils.encodings import get_encoding_function
import grid_scoring.scores as scores
import grid_scoring.utils as utils
# from grid_scoring.run_network import run_and_gather_activations, run_and_gather_localization_activations
from path_integration_utils import encoding_func_from_model, pc_gauss_encoding_func
parser = argparse.ArgumentParser('Compute grid scores for a path integration model')
parser.add_argument('--n-samples', type=int, default=5000)
parser.add_argument('--use-localization', action='store_true')
# TODO: use these parameters
parser.add_argument('--dataset', type=str, default='')
parser.add_argument('--model', type=str, default='')
parser.add_argument('--fname-prefix', type=str, default='sac')
parser.add_argument('--spatial-encoding', type=str, default='ssp',
choices=[
'ssp', 'hex-ssp', 'periodic-hex-ssp', 'grid-ssp', 'ind-ssp', 'orth-proj-ssp',
'rec-ssp', 'rec-hex-ssp', 'rec-ind-ssp', 'sub-toroid-ssp', 'var-sub-toroid-ssp',
'random', '2d', '2d-normalized', 'one-hot', 'hex-trig',
'trig', 'random-trig', 'random-rotated-trig', 'random-proj', 'legendre',
'learned', 'learned-normalized', 'frozen-learned', 'frozen-learned-normalized',
'pc-gauss', 'pc-dog', 'tile-coding'
])
# choices=['ssp', '2d', 'frozen-learned', 'pc-gauss', 'pc-dog', 'pc-gauss-softmax', 'hex-trig', 'hex-trig-all-freq'])
parser.add_argument('--frozen-model', type=str, default='', help='model to use frozen encoding weights from')
parser.add_argument('--pc-gauss-sigma', type=float, default=0.25)
parser.add_argument('--pc-diff-sigma', type=float, default=0.5)
parser.add_argument('--hex-freq-coef', type=float, default=2.5, help='constant to scale frequencies by')
parser.add_argument('--n-tiles', type=int, default=8, help='number of layers for tile coding')
parser.add_argument('--n-bins', type=int, default=8, help='number of bins for tile coding')
parser.add_argument('--ssp-scaling', type=float, default=1.0)
parser.add_argument('--grid-ssp-min', type=float, default=0.25, help='minimum plane wave scale')
parser.add_argument('--grid-ssp-max', type=float, default=2.0, help='maximum plane wave scale')
parser.add_argument('--phi', type=float, default=0.5, help='phi as a fraction of pi for orth-proj-ssp')
parser.add_argument('--n-proj', type=int, default=3, help='projection dimension for sub toroids')
parser.add_argument('--scale-ratio', type=float, default=0, help='ratio between sub toroid scales')
parser.add_argument('--hilbert-points', type=int, default=1, choices=[0, 1, 2, 3],
help='pc centers. 0: random uniform. 1: hilbert curve. 2: evenly spaced grid. 3: hex grid')
parser.add_argument('--seed', type=int, default=13)
parser.add_argument('--dropout-p', type=float, default=0.5)
parser.add_argument('--dim', type=int, default=512)
parser.add_argument('--train-split', type=float, default=0.8, help='Training fraction of the train/test split')
parser.add_argument('--allow-cache', action='store_true',
help='once the dataset has been generated, it will be saved to a file to be loaded faster')
parser.add_argument('--trajectory-length', type=int, default=100)
parser.add_argument('--minibatch-size', type=int, default=10)
parser.add_argument('--n-image-bins', type=int, default=20)
parser.add_argument('--n-hd-cells', type=int, default=0, help='If non-zero, use linear and angular velocity as well as HD cell output')
parser.add_argument('--sin-cos-ang', type=int, default=1, choices=[0, 1],
help='Use the sin and cos of the angular velocity if angular velocities are used')
parser.add_argument('--use-lmu', action='store_true')
parser.add_argument('--lmu-order', type=int, default=6)
parser.add_argument('--no-cache-load', action='store_true', help='do not load from cache')
args = parser.parse_args()
ssp_scaling = args.ssp_scaling
torch.manual_seed(args.seed)
np.random.seed(args.seed)
data = np.load(args.dataset)
# only used for frozen-learned and other custom encoding functions
# encoding_func = None
limit_low = 0 #* args.ssp_scaling
limit_high = 2.2 #* args.ssp_scaling
res = 128 #256
encoding_func, dim = get_encoding_function(args, limit_low=limit_low, limit_high=limit_high)
xs = np.linspace(limit_low, limit_high, res)
ys = np.linspace(limit_low, limit_high, res)
# FIXME: inefficient but will work for now
heatmap_vectors = np.zeros((len(xs), len(ys), dim))
print("Generating Heatmap Vectors")
for i, x in enumerate(xs):
for j, y in enumerate(ys):
heatmap_vectors[i, j, :] = encoding_func(
# batch dim
# np.array(
# [[x, y]]
# )
# no batch dim
# np.array(
# [x, y]
# )
# new signature
x=x, y=y
)
heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])
print("Heatmap Vector Generation Complete")
n_samples = args.n_samples
rollout_length = args.trajectory_length
batch_size = args.minibatch_size
if args.n_hd_cells > 0:
hd_encoding_func = hd_gauss_encoding_func(dim=args.n_hd_cells, sigma=0.25, use_softmax=False, rng=np.random.RandomState(args.seed))
if args.sin_cos_ang:
input_size = 3
else:
input_size = 2
model = SSPPathIntegrationModel(
input_size=input_size, unroll_length=rollout_length,
sp_dim=dim + args.n_hd_cells, dropout_p=args.dropout_p, use_lmu=args.use_lmu, order=args.lmu_order
)
else:
hd_encoding_func = None
model = SSPPathIntegrationModel(
input_size=2, unroll_length=rollout_length,
sp_dim=dim, dropout_p=args.dropout_p, use_lmu=args.use_lmu, order=args.lmu_order
)
# model = SSPPathIntegrationModel(unroll_length=rollout_length, sp_dim=dim, dropout_p=args.dropout_p)
model.load_state_dict(torch.load(args.model), strict=False)
model.eval()
# encoding specific cache string
encoding_specific = ''
if 'ssp' in args.spatial_encoding:
encoding_specific = args.ssp_scaling
elif args.spatial_encoding == 'frozen-learned':
encoding_specific = args.frozen_model
elif args.spatial_encoding == 'pc-gauss' or args.spatial_encoding == 'pc-gauss-softmax':
encoding_specific = args.pc_gauss_sigma
elif args.spatial_encoding == 'pc-dog':
encoding_specific = '{}-{}'.format(args.pc_gauss_sigma, args.pc_diff_sigma)
elif args.spatial_encoding == 'hex-trig':
encoding_specific = args.hex_freq_coef
if 'tf' in args.dataset:
cache_fname = 'dataset_cache/tf_{}_{}_{}_{}_{}_{}.npz'.format(
args.spatial_encoding, args.dim, args.seed, args.n_samples, args.n_hd_cells, encoding_specific
)
else:
cache_fname = 'dataset_cache/{}_{}_{}_{}_{}_{}.npz'.format(
args.spatial_encoding, args.dim, args.seed, args.n_samples, args.n_hd_cells, encoding_specific
)
# if the file exists, load it from cache
if os.path.exists(cache_fname) and not args.no_cache_load:
print("Generating Train and Test Loaders from Cache")
trainloader, testloader = load_from_cache(cache_fname, batch_size=batch_size, n_samples=n_samples)
else:
print("Generating Train and Test Loaders")
if 'tf' in args.dataset:
# tfrecord dataset only supports using the sin and cos of angular velocity
assert args.sin_cos_ang == 1
trainloader, testloader = tf_train_test_loaders(
data,
n_train_samples=n_samples,
n_test_samples=n_samples,
rollout_length=rollout_length,
batch_size=batch_size,
encoding=args.spatial_encoding,
encoding_func=encoding_func,
encoding_dim=args.dim,
train_split=args.train_split,
hd_dim=args.n_hd_cells,
hd_encoding_func=hd_encoding_func,
sin_cos_ang=args.sin_cos_ang,
)
else:
if args.n_hd_cells > 0:
trainloader, testloader = angular_train_test_loaders(
data,
n_train_samples=n_samples,
n_test_samples=n_samples,
rollout_length=rollout_length,
batch_size=batch_size,
encoding=args.spatial_encoding,
encoding_func=encoding_func,
encoding_dim=args.dim,
train_split=args.train_split,
hd_dim=args.n_hd_cells,
hd_encoding_func=hd_encoding_func,
sin_cos_ang=args.sin_cos_ang,
)
else:
trainloader, testloader = train_test_loaders(
data,
n_train_samples=n_samples,
n_test_samples=n_samples,
rollout_length=rollout_length,
batch_size=batch_size,
encoding=args.spatial_encoding,
encoding_func=encoding_func,
encoding_dim=args.dim,
train_split=args.train_split,
)
if args.allow_cache:
if not os.path.exists('dataset_cache'):
os.makedirs('dataset_cache')
np.savez(
cache_fname,
train_velocity_inputs=trainloader.dataset.velocity_inputs,
train_ssp_inputs=trainloader.dataset.ssp_inputs,
train_ssp_outputs=trainloader.dataset.ssp_outputs,
test_velocity_inputs=testloader.dataset.velocity_inputs,
test_ssp_inputs=testloader.dataset.ssp_inputs,
test_ssp_outputs=testloader.dataset.ssp_outputs,
)
print("Train and Test Loaders Generation Complete")
starts = [0.2] * 10
ends = np.linspace(0.4, 1.0, num=10)
masks_parameters = zip(starts, ends.tolist())
latest_epoch_scorer = scores.GridScorer(
nbins=args.n_image_bins,
coords_range=((0, 2.2), (0, 2.2)), # data_reader.get_coord_range(),
mask_parameters=masks_parameters,
)
fname_lstm_pred = '{}_{}samples_lstm_pred.pdf'.format(args.fname_prefix, args.n_samples)
fname_lstm_truth = '{}_{}samples_lstm_truth.pdf'.format(args.fname_prefix, args.n_samples)
fname_dense_pred = '{}_{}samples_dense_pred.pdf'.format(args.fname_prefix, args.n_samples)
fname_dense_truth = '{}_{}samples_dense_truth.pdf'.format(args.fname_prefix, args.n_samples)
# Run and gather activations
print("Testing")
with torch.no_grad():
# Everything is in one batch, so this loop will only happen once
for i, data in enumerate(testloader):
velocity_inputs, ssp_inputs, ssp_outputs = data
ssp_pred, lstm_outputs, dense_outputs = model.forward_activations(velocity_inputs, ssp_inputs)
predictions = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], 2))
coords = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], 2))
lstm_activations = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], model.lstm_hidden_size))
dense_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], model.linear_hidden_size))
assert rollout_length == ssp_pred.shape[0]
# # For each neuron, contains the average activity at each spatial bin
# # Computing for both ground truth and predicted location
# rate_maps_pred = np.zeros((model.lstm_hidden_size, len(xs), len(ys)))
# rate_maps_truth = np.zeros((model.lstm_hidden_size, len(xs), len(ys)))
print("Computing predicted locations and true locations")
# Using all data, one chunk at a time
for ri in range(rollout_length):
# trim out head direction info if that was included by only looking up to args.encoding_dim
# computing 'predicted' coordinates, where the agent thinks it is
pred = ssp_pred.detach().numpy()[ri, :, :args.dim]
# pred = pred / pred.sum(axis=1)[:, np.newaxis]
predictions[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = ssp_to_loc_v(
pred,
heatmap_vectors, xs, ys
)
# computing 'ground truth' coordinates, where the agent should be
coord = ssp_outputs.detach().numpy()[:, ri, :args.dim]
# coord = coord / coord.sum(axis=1)[:, np.newaxis]
coords[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = ssp_to_loc_v(
coord,
heatmap_vectors, xs, ys
)
# reshaping activations and converting to numpy array
lstm_activations[ri*ssp_pred.shape[1]:(ri+1)*ssp_pred.shape[1], :] = lstm_outputs.detach().numpy()[ri, :, :]
dense_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = dense_outputs.detach().numpy()[ri, :, :]
# predictions = predictions / args.ssp_scaling
# coords = coords / args.ssp_scaling
print(np.max(predictions))
print(np.min(predictions))
grid_scores_60_pred, grid_scores_90_pred, grid_scores_60_separation_pred, grid_scores_90_separation_pred = utils.get_scores_and_plot(
scorer=latest_epoch_scorer,
data_abs_xy=predictions, #res['pos_xy'],
activations=lstm_activations, #res['bottleneck'],
directory='output_grid_scores', #FLAGS.saver_results_directory,
filename=fname_lstm_pred,
)
grid_scores_60_truth, grid_scores_90_truth, grid_scores_60_separation_truth, grid_scores_90_separation_truth = utils.get_scores_and_plot(
scorer=latest_epoch_scorer,
data_abs_xy=coords, #res['pos_xy'],
activations=lstm_activations, #res['bottleneck'],
directory='output_grid_scores', #FLAGS.saver_results_directory,
filename=fname_lstm_truth,
)
grid_scores_60_dense_pred, grid_scores_90_dense_pred, grid_scores_60_separation_dense_pred, grid_scores_90_separation_dense_pred = utils.get_scores_and_plot(
scorer=latest_epoch_scorer,
data_abs_xy=predictions, #res['pos_xy'],
activations=dense_activations, #res['bottleneck'],
directory='output_grid_scores', #FLAGS.saver_results_directory,
filename=fname_dense_pred,
)
grid_scores_60_dense_truth, grid_scores_90_dense_truth, grid_scores_60_separation_dense_truth, grid_scores_90_separation_dense_truth = utils.get_scores_and_plot(
scorer=latest_epoch_scorer,
data_abs_xy=coords, #res['pos_xy'],
activations=dense_activations, #res['bottleneck'],
directory='output_grid_scores', #FLAGS.saver_results_directory,
filename=fname_dense_truth,
)
print(grid_scores_60_truth, grid_scores_90_truth, grid_scores_60_separation_truth, grid_scores_90_separation_truth)
# Saving to make grid score values easy to compare for different variations
fname = 'output_grid_scores/{}_{}samples.npz'.format(args.fname_prefix, args.n_samples)
np.savez(
fname,
grid_scores_60_pred=grid_scores_60_pred,
grid_scores_90_pred=grid_scores_90_pred,
grid_scores_60_separation_pred=grid_scores_60_separation_pred,
grid_scores_90_separation_pred=grid_scores_90_separation_pred,
grid_scores_60_truth=grid_scores_60_truth,
grid_scores_90_truth=grid_scores_90_truth,
grid_scores_60_separation_truth=grid_scores_60_separation_truth,
grid_scores_90_separation_truth=grid_scores_90_separation_truth,
grid_scores_60_dense_pred=grid_scores_60_dense_pred,
grid_scores_90_dense_pred=grid_scores_90_dense_pred,
grid_scores_60_separation_dense_pred=grid_scores_60_separation_dense_pred,
grid_scores_90_separation_dense_pred=grid_scores_90_separation_dense_pred,
grid_scores_60_dense_truth=grid_scores_60_dense_truth,
grid_scores_90_dense_truth=grid_scores_90_dense_truth,
grid_scores_60_separation_dense_truth=grid_scores_60_separation_dense_truth,
grid_scores_90_separation_dense_truth=grid_scores_90_separation_dense_truth,
)
|
normal
|
{
"blob_id": "f4bc5663ab2b2a6dbb41a2fc3d7ca67100b455a4",
"index": 838,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif display is None or 'localhost' in display:\n matplotlib.use('agg')\n<mask token>\nparser.add_argument('--n-samples', type=int, default=5000)\nparser.add_argument('--use-localization', action='store_true')\nparser.add_argument('--dataset', type=str, default='')\nparser.add_argument('--model', type=str, default='')\nparser.add_argument('--fname-prefix', type=str, default='sac')\nparser.add_argument('--spatial-encoding', type=str, default='ssp', choices=\n ['ssp', 'hex-ssp', 'periodic-hex-ssp', 'grid-ssp', 'ind-ssp',\n 'orth-proj-ssp', 'rec-ssp', 'rec-hex-ssp', 'rec-ind-ssp',\n 'sub-toroid-ssp', 'var-sub-toroid-ssp', 'random', '2d', '2d-normalized',\n 'one-hot', 'hex-trig', 'trig', 'random-trig', 'random-rotated-trig',\n 'random-proj', 'legendre', 'learned', 'learned-normalized',\n 'frozen-learned', 'frozen-learned-normalized', 'pc-gauss', 'pc-dog',\n 'tile-coding'])\nparser.add_argument('--frozen-model', type=str, default='', help=\n 'model to use frozen encoding weights from')\nparser.add_argument('--pc-gauss-sigma', type=float, default=0.25)\nparser.add_argument('--pc-diff-sigma', type=float, default=0.5)\nparser.add_argument('--hex-freq-coef', type=float, default=2.5, help=\n 'constant to scale frequencies by')\nparser.add_argument('--n-tiles', type=int, default=8, help=\n 'number of layers for tile coding')\nparser.add_argument('--n-bins', type=int, default=8, help=\n 'number of bins for tile coding')\nparser.add_argument('--ssp-scaling', type=float, default=1.0)\nparser.add_argument('--grid-ssp-min', type=float, default=0.25, help=\n 'minimum plane wave scale')\nparser.add_argument('--grid-ssp-max', type=float, default=2.0, help=\n 'maximum plane wave scale')\nparser.add_argument('--phi', type=float, default=0.5, help=\n 'phi as a fraction of pi for orth-proj-ssp')\nparser.add_argument('--n-proj', type=int, default=3, help=\n 'projection dimension for sub toroids')\nparser.add_argument('--scale-ratio', type=float, default=0, help=\n 'ratio between sub toroid scales')\nparser.add_argument('--hilbert-points', type=int, default=1, choices=[0, 1,\n 2, 3], help=\n 'pc centers. 0: random uniform. 1: hilbert curve. 2: evenly spaced grid. 3: hex grid'\n )\nparser.add_argument('--seed', type=int, default=13)\nparser.add_argument('--dropout-p', type=float, default=0.5)\nparser.add_argument('--dim', type=int, default=512)\nparser.add_argument('--train-split', type=float, default=0.8, help=\n 'Training fraction of the train/test split')\nparser.add_argument('--allow-cache', action='store_true', help=\n 'once the dataset has been generated, it will be saved to a file to be loaded faster'\n )\nparser.add_argument('--trajectory-length', type=int, default=100)\nparser.add_argument('--minibatch-size', type=int, default=10)\nparser.add_argument('--n-image-bins', type=int, default=20)\nparser.add_argument('--n-hd-cells', type=int, default=0, help=\n 'If non-zero, use linear and angular velocity as well as HD cell output')\nparser.add_argument('--sin-cos-ang', type=int, default=1, choices=[0, 1],\n help=\n 'Use the sin and cos of the angular velocity if angular velocities are used'\n )\nparser.add_argument('--use-lmu', action='store_true')\nparser.add_argument('--lmu-order', type=int, default=6)\nparser.add_argument('--no-cache-load', action='store_true', help=\n 'do not load from cache')\n<mask token>\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n<mask token>\nprint('Generating Heatmap Vectors')\nfor i, x in enumerate(xs):\n for j, y in enumerate(ys):\n heatmap_vectors[i, j, :] = encoding_func(x=x, y=y)\n heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])\nprint('Heatmap Vector Generation Complete')\n<mask token>\nif args.n_hd_cells > 0:\n hd_encoding_func = hd_gauss_encoding_func(dim=args.n_hd_cells, sigma=\n 0.25, use_softmax=False, rng=np.random.RandomState(args.seed))\n if args.sin_cos_ang:\n input_size = 3\n else:\n input_size = 2\n model = SSPPathIntegrationModel(input_size=input_size, unroll_length=\n rollout_length, sp_dim=dim + args.n_hd_cells, dropout_p=args.\n dropout_p, use_lmu=args.use_lmu, order=args.lmu_order)\nelse:\n hd_encoding_func = None\n model = SSPPathIntegrationModel(input_size=2, unroll_length=\n rollout_length, sp_dim=dim, dropout_p=args.dropout_p, use_lmu=args.\n use_lmu, order=args.lmu_order)\nmodel.load_state_dict(torch.load(args.model), strict=False)\nmodel.eval()\n<mask token>\nif 'ssp' in args.spatial_encoding:\n encoding_specific = args.ssp_scaling\nelif args.spatial_encoding == 'frozen-learned':\n encoding_specific = args.frozen_model\nelif args.spatial_encoding == 'pc-gauss' or args.spatial_encoding == 'pc-gauss-softmax':\n encoding_specific = args.pc_gauss_sigma\nelif args.spatial_encoding == 'pc-dog':\n encoding_specific = '{}-{}'.format(args.pc_gauss_sigma, args.pc_diff_sigma)\nelif args.spatial_encoding == 'hex-trig':\n encoding_specific = args.hex_freq_coef\nif 'tf' in args.dataset:\n cache_fname = 'dataset_cache/tf_{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nelse:\n cache_fname = 'dataset_cache/{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nif os.path.exists(cache_fname) and not args.no_cache_load:\n print('Generating Train and Test Loaders from Cache')\n trainloader, testloader = load_from_cache(cache_fname, batch_size=\n batch_size, n_samples=n_samples)\nelse:\n print('Generating Train and Test Loaders')\n if 'tf' in args.dataset:\n assert args.sin_cos_ang == 1\n trainloader, testloader = tf_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n elif args.n_hd_cells > 0:\n trainloader, testloader = angular_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n else:\n trainloader, testloader = train_test_loaders(data, n_train_samples=\n n_samples, n_test_samples=n_samples, rollout_length=\n rollout_length, batch_size=batch_size, encoding=args.\n spatial_encoding, encoding_func=encoding_func, encoding_dim=\n args.dim, train_split=args.train_split)\n if args.allow_cache:\n if not os.path.exists('dataset_cache'):\n os.makedirs('dataset_cache')\n np.savez(cache_fname, train_velocity_inputs=trainloader.dataset.\n velocity_inputs, train_ssp_inputs=trainloader.dataset.\n ssp_inputs, train_ssp_outputs=trainloader.dataset.ssp_outputs,\n test_velocity_inputs=testloader.dataset.velocity_inputs,\n test_ssp_inputs=testloader.dataset.ssp_inputs, test_ssp_outputs\n =testloader.dataset.ssp_outputs)\nprint('Train and Test Loaders Generation Complete')\n<mask token>\nprint('Testing')\nwith torch.no_grad():\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n ssp_pred, lstm_outputs, dense_outputs = model.forward_activations(\n velocity_inputs, ssp_inputs)\n predictions = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n coords = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n lstm_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.lstm_hidden_size))\n dense_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.linear_hidden_size))\n assert rollout_length == ssp_pred.shape[0]\n print('Computing predicted locations and true locations')\n for ri in range(rollout_length):\n pred = ssp_pred.detach().numpy()[ri, :, :args.dim]\n predictions[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(pred, heatmap_vectors, xs, ys)\n coord = ssp_outputs.detach().numpy()[:, ri, :args.dim]\n coords[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(coord, heatmap_vectors, xs, ys)\n lstm_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = lstm_outputs.detach().numpy()[ri, :, :]\n dense_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[\n 1], :] = dense_outputs.detach().numpy()[ri, :, :]\nprint(np.max(predictions))\nprint(np.min(predictions))\n<mask token>\nprint(grid_scores_60_truth, grid_scores_90_truth,\n grid_scores_60_separation_truth, grid_scores_90_separation_truth)\n<mask token>\nnp.savez(fname, grid_scores_60_pred=grid_scores_60_pred,\n grid_scores_90_pred=grid_scores_90_pred, grid_scores_60_separation_pred\n =grid_scores_60_separation_pred, grid_scores_90_separation_pred=\n grid_scores_90_separation_pred, grid_scores_60_truth=\n grid_scores_60_truth, grid_scores_90_truth=grid_scores_90_truth,\n grid_scores_60_separation_truth=grid_scores_60_separation_truth,\n grid_scores_90_separation_truth=grid_scores_90_separation_truth,\n grid_scores_60_dense_pred=grid_scores_60_dense_pred,\n grid_scores_90_dense_pred=grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred=\n grid_scores_60_separation_dense_pred,\n grid_scores_90_separation_dense_pred=\n grid_scores_90_separation_dense_pred, grid_scores_60_dense_truth=\n grid_scores_60_dense_truth, grid_scores_90_dense_truth=\n grid_scores_90_dense_truth, grid_scores_60_separation_dense_truth=\n grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth=grid_scores_90_separation_dense_truth\n )\n",
"step-3": "<mask token>\ndisplay = os.environ.get('DISPLAY')\nif display is None or 'localhost' in display:\n matplotlib.use('agg')\n<mask token>\nparser = argparse.ArgumentParser(\n 'Compute grid scores for a path integration model')\nparser.add_argument('--n-samples', type=int, default=5000)\nparser.add_argument('--use-localization', action='store_true')\nparser.add_argument('--dataset', type=str, default='')\nparser.add_argument('--model', type=str, default='')\nparser.add_argument('--fname-prefix', type=str, default='sac')\nparser.add_argument('--spatial-encoding', type=str, default='ssp', choices=\n ['ssp', 'hex-ssp', 'periodic-hex-ssp', 'grid-ssp', 'ind-ssp',\n 'orth-proj-ssp', 'rec-ssp', 'rec-hex-ssp', 'rec-ind-ssp',\n 'sub-toroid-ssp', 'var-sub-toroid-ssp', 'random', '2d', '2d-normalized',\n 'one-hot', 'hex-trig', 'trig', 'random-trig', 'random-rotated-trig',\n 'random-proj', 'legendre', 'learned', 'learned-normalized',\n 'frozen-learned', 'frozen-learned-normalized', 'pc-gauss', 'pc-dog',\n 'tile-coding'])\nparser.add_argument('--frozen-model', type=str, default='', help=\n 'model to use frozen encoding weights from')\nparser.add_argument('--pc-gauss-sigma', type=float, default=0.25)\nparser.add_argument('--pc-diff-sigma', type=float, default=0.5)\nparser.add_argument('--hex-freq-coef', type=float, default=2.5, help=\n 'constant to scale frequencies by')\nparser.add_argument('--n-tiles', type=int, default=8, help=\n 'number of layers for tile coding')\nparser.add_argument('--n-bins', type=int, default=8, help=\n 'number of bins for tile coding')\nparser.add_argument('--ssp-scaling', type=float, default=1.0)\nparser.add_argument('--grid-ssp-min', type=float, default=0.25, help=\n 'minimum plane wave scale')\nparser.add_argument('--grid-ssp-max', type=float, default=2.0, help=\n 'maximum plane wave scale')\nparser.add_argument('--phi', type=float, default=0.5, help=\n 'phi as a fraction of pi for orth-proj-ssp')\nparser.add_argument('--n-proj', type=int, default=3, help=\n 'projection dimension for sub toroids')\nparser.add_argument('--scale-ratio', type=float, default=0, help=\n 'ratio between sub toroid scales')\nparser.add_argument('--hilbert-points', type=int, default=1, choices=[0, 1,\n 2, 3], help=\n 'pc centers. 0: random uniform. 1: hilbert curve. 2: evenly spaced grid. 3: hex grid'\n )\nparser.add_argument('--seed', type=int, default=13)\nparser.add_argument('--dropout-p', type=float, default=0.5)\nparser.add_argument('--dim', type=int, default=512)\nparser.add_argument('--train-split', type=float, default=0.8, help=\n 'Training fraction of the train/test split')\nparser.add_argument('--allow-cache', action='store_true', help=\n 'once the dataset has been generated, it will be saved to a file to be loaded faster'\n )\nparser.add_argument('--trajectory-length', type=int, default=100)\nparser.add_argument('--minibatch-size', type=int, default=10)\nparser.add_argument('--n-image-bins', type=int, default=20)\nparser.add_argument('--n-hd-cells', type=int, default=0, help=\n 'If non-zero, use linear and angular velocity as well as HD cell output')\nparser.add_argument('--sin-cos-ang', type=int, default=1, choices=[0, 1],\n help=\n 'Use the sin and cos of the angular velocity if angular velocities are used'\n )\nparser.add_argument('--use-lmu', action='store_true')\nparser.add_argument('--lmu-order', type=int, default=6)\nparser.add_argument('--no-cache-load', action='store_true', help=\n 'do not load from cache')\nargs = parser.parse_args()\nssp_scaling = args.ssp_scaling\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\ndata = np.load(args.dataset)\nlimit_low = 0\nlimit_high = 2.2\nres = 128\nencoding_func, dim = get_encoding_function(args, limit_low=limit_low,\n limit_high=limit_high)\nxs = np.linspace(limit_low, limit_high, res)\nys = np.linspace(limit_low, limit_high, res)\nheatmap_vectors = np.zeros((len(xs), len(ys), dim))\nprint('Generating Heatmap Vectors')\nfor i, x in enumerate(xs):\n for j, y in enumerate(ys):\n heatmap_vectors[i, j, :] = encoding_func(x=x, y=y)\n heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])\nprint('Heatmap Vector Generation Complete')\nn_samples = args.n_samples\nrollout_length = args.trajectory_length\nbatch_size = args.minibatch_size\nif args.n_hd_cells > 0:\n hd_encoding_func = hd_gauss_encoding_func(dim=args.n_hd_cells, sigma=\n 0.25, use_softmax=False, rng=np.random.RandomState(args.seed))\n if args.sin_cos_ang:\n input_size = 3\n else:\n input_size = 2\n model = SSPPathIntegrationModel(input_size=input_size, unroll_length=\n rollout_length, sp_dim=dim + args.n_hd_cells, dropout_p=args.\n dropout_p, use_lmu=args.use_lmu, order=args.lmu_order)\nelse:\n hd_encoding_func = None\n model = SSPPathIntegrationModel(input_size=2, unroll_length=\n rollout_length, sp_dim=dim, dropout_p=args.dropout_p, use_lmu=args.\n use_lmu, order=args.lmu_order)\nmodel.load_state_dict(torch.load(args.model), strict=False)\nmodel.eval()\nencoding_specific = ''\nif 'ssp' in args.spatial_encoding:\n encoding_specific = args.ssp_scaling\nelif args.spatial_encoding == 'frozen-learned':\n encoding_specific = args.frozen_model\nelif args.spatial_encoding == 'pc-gauss' or args.spatial_encoding == 'pc-gauss-softmax':\n encoding_specific = args.pc_gauss_sigma\nelif args.spatial_encoding == 'pc-dog':\n encoding_specific = '{}-{}'.format(args.pc_gauss_sigma, args.pc_diff_sigma)\nelif args.spatial_encoding == 'hex-trig':\n encoding_specific = args.hex_freq_coef\nif 'tf' in args.dataset:\n cache_fname = 'dataset_cache/tf_{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nelse:\n cache_fname = 'dataset_cache/{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nif os.path.exists(cache_fname) and not args.no_cache_load:\n print('Generating Train and Test Loaders from Cache')\n trainloader, testloader = load_from_cache(cache_fname, batch_size=\n batch_size, n_samples=n_samples)\nelse:\n print('Generating Train and Test Loaders')\n if 'tf' in args.dataset:\n assert args.sin_cos_ang == 1\n trainloader, testloader = tf_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n elif args.n_hd_cells > 0:\n trainloader, testloader = angular_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n else:\n trainloader, testloader = train_test_loaders(data, n_train_samples=\n n_samples, n_test_samples=n_samples, rollout_length=\n rollout_length, batch_size=batch_size, encoding=args.\n spatial_encoding, encoding_func=encoding_func, encoding_dim=\n args.dim, train_split=args.train_split)\n if args.allow_cache:\n if not os.path.exists('dataset_cache'):\n os.makedirs('dataset_cache')\n np.savez(cache_fname, train_velocity_inputs=trainloader.dataset.\n velocity_inputs, train_ssp_inputs=trainloader.dataset.\n ssp_inputs, train_ssp_outputs=trainloader.dataset.ssp_outputs,\n test_velocity_inputs=testloader.dataset.velocity_inputs,\n test_ssp_inputs=testloader.dataset.ssp_inputs, test_ssp_outputs\n =testloader.dataset.ssp_outputs)\nprint('Train and Test Loaders Generation Complete')\nstarts = [0.2] * 10\nends = np.linspace(0.4, 1.0, num=10)\nmasks_parameters = zip(starts, ends.tolist())\nlatest_epoch_scorer = scores.GridScorer(nbins=args.n_image_bins,\n coords_range=((0, 2.2), (0, 2.2)), mask_parameters=masks_parameters)\nfname_lstm_pred = '{}_{}samples_lstm_pred.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_lstm_truth = '{}_{}samples_lstm_truth.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_dense_pred = '{}_{}samples_dense_pred.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_dense_truth = '{}_{}samples_dense_truth.pdf'.format(args.fname_prefix,\n args.n_samples)\nprint('Testing')\nwith torch.no_grad():\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n ssp_pred, lstm_outputs, dense_outputs = model.forward_activations(\n velocity_inputs, ssp_inputs)\n predictions = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n coords = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n lstm_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.lstm_hidden_size))\n dense_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.linear_hidden_size))\n assert rollout_length == ssp_pred.shape[0]\n print('Computing predicted locations and true locations')\n for ri in range(rollout_length):\n pred = ssp_pred.detach().numpy()[ri, :, :args.dim]\n predictions[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(pred, heatmap_vectors, xs, ys)\n coord = ssp_outputs.detach().numpy()[:, ri, :args.dim]\n coords[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(coord, heatmap_vectors, xs, ys)\n lstm_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = lstm_outputs.detach().numpy()[ri, :, :]\n dense_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[\n 1], :] = dense_outputs.detach().numpy()[ri, :, :]\nprint(np.max(predictions))\nprint(np.min(predictions))\n(grid_scores_60_pred, grid_scores_90_pred, grid_scores_60_separation_pred,\n grid_scores_90_separation_pred) = (utils.get_scores_and_plot(scorer=\n latest_epoch_scorer, data_abs_xy=predictions, activations=\n lstm_activations, directory='output_grid_scores', filename=fname_lstm_pred)\n )\n(grid_scores_60_truth, grid_scores_90_truth,\n grid_scores_60_separation_truth, grid_scores_90_separation_truth) = (utils\n .get_scores_and_plot(scorer=latest_epoch_scorer, data_abs_xy=coords,\n activations=lstm_activations, directory='output_grid_scores', filename=\n fname_lstm_truth))\n(grid_scores_60_dense_pred, grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred, grid_scores_90_separation_dense_pred\n ) = (utils.get_scores_and_plot(scorer=latest_epoch_scorer, data_abs_xy=\n predictions, activations=dense_activations, directory=\n 'output_grid_scores', filename=fname_dense_pred))\n(grid_scores_60_dense_truth, grid_scores_90_dense_truth,\n grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth) = (utils.get_scores_and_plot(\n scorer=latest_epoch_scorer, data_abs_xy=coords, activations=\n dense_activations, directory='output_grid_scores', filename=\n fname_dense_truth))\nprint(grid_scores_60_truth, grid_scores_90_truth,\n grid_scores_60_separation_truth, grid_scores_90_separation_truth)\nfname = 'output_grid_scores/{}_{}samples.npz'.format(args.fname_prefix,\n args.n_samples)\nnp.savez(fname, grid_scores_60_pred=grid_scores_60_pred,\n grid_scores_90_pred=grid_scores_90_pred, grid_scores_60_separation_pred\n =grid_scores_60_separation_pred, grid_scores_90_separation_pred=\n grid_scores_90_separation_pred, grid_scores_60_truth=\n grid_scores_60_truth, grid_scores_90_truth=grid_scores_90_truth,\n grid_scores_60_separation_truth=grid_scores_60_separation_truth,\n grid_scores_90_separation_truth=grid_scores_90_separation_truth,\n grid_scores_60_dense_pred=grid_scores_60_dense_pred,\n grid_scores_90_dense_pred=grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred=\n grid_scores_60_separation_dense_pred,\n grid_scores_90_separation_dense_pred=\n grid_scores_90_separation_dense_pred, grid_scores_60_dense_truth=\n grid_scores_60_dense_truth, grid_scores_90_dense_truth=\n grid_scores_90_dense_truth, grid_scores_60_separation_dense_truth=\n grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth=grid_scores_90_separation_dense_truth\n )\n",
"step-4": "import matplotlib\nimport os\ndisplay = os.environ.get('DISPLAY')\nif display is None or 'localhost' in display:\n matplotlib.use('agg')\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom datasets import train_test_loaders, angular_train_test_loaders, tf_train_test_loaders, load_from_cache\nfrom models import SSPPathIntegrationModel\nfrom datetime import datetime\nfrom tensorboardX import SummaryWriter\nimport json\nfrom spatial_semantic_pointers.utils import get_heatmap_vectors, ssp_to_loc, ssp_to_loc_v\nfrom spatial_semantic_pointers.plots import plot_predictions, plot_predictions_v\nimport matplotlib.pyplot as plt\nfrom path_integration_utils import pc_to_loc_v, encoding_func_from_model, pc_gauss_encoding_func, ssp_encoding_func, hd_gauss_encoding_func, hex_trig_encoding_func\nfrom ssp_navigation.utils.encodings import get_encoding_function\nimport grid_scoring.scores as scores\nimport grid_scoring.utils as utils\nfrom path_integration_utils import encoding_func_from_model, pc_gauss_encoding_func\nparser = argparse.ArgumentParser(\n 'Compute grid scores for a path integration model')\nparser.add_argument('--n-samples', type=int, default=5000)\nparser.add_argument('--use-localization', action='store_true')\nparser.add_argument('--dataset', type=str, default='')\nparser.add_argument('--model', type=str, default='')\nparser.add_argument('--fname-prefix', type=str, default='sac')\nparser.add_argument('--spatial-encoding', type=str, default='ssp', choices=\n ['ssp', 'hex-ssp', 'periodic-hex-ssp', 'grid-ssp', 'ind-ssp',\n 'orth-proj-ssp', 'rec-ssp', 'rec-hex-ssp', 'rec-ind-ssp',\n 'sub-toroid-ssp', 'var-sub-toroid-ssp', 'random', '2d', '2d-normalized',\n 'one-hot', 'hex-trig', 'trig', 'random-trig', 'random-rotated-trig',\n 'random-proj', 'legendre', 'learned', 'learned-normalized',\n 'frozen-learned', 'frozen-learned-normalized', 'pc-gauss', 'pc-dog',\n 'tile-coding'])\nparser.add_argument('--frozen-model', type=str, default='', help=\n 'model to use frozen encoding weights from')\nparser.add_argument('--pc-gauss-sigma', type=float, default=0.25)\nparser.add_argument('--pc-diff-sigma', type=float, default=0.5)\nparser.add_argument('--hex-freq-coef', type=float, default=2.5, help=\n 'constant to scale frequencies by')\nparser.add_argument('--n-tiles', type=int, default=8, help=\n 'number of layers for tile coding')\nparser.add_argument('--n-bins', type=int, default=8, help=\n 'number of bins for tile coding')\nparser.add_argument('--ssp-scaling', type=float, default=1.0)\nparser.add_argument('--grid-ssp-min', type=float, default=0.25, help=\n 'minimum plane wave scale')\nparser.add_argument('--grid-ssp-max', type=float, default=2.0, help=\n 'maximum plane wave scale')\nparser.add_argument('--phi', type=float, default=0.5, help=\n 'phi as a fraction of pi for orth-proj-ssp')\nparser.add_argument('--n-proj', type=int, default=3, help=\n 'projection dimension for sub toroids')\nparser.add_argument('--scale-ratio', type=float, default=0, help=\n 'ratio between sub toroid scales')\nparser.add_argument('--hilbert-points', type=int, default=1, choices=[0, 1,\n 2, 3], help=\n 'pc centers. 0: random uniform. 1: hilbert curve. 2: evenly spaced grid. 3: hex grid'\n )\nparser.add_argument('--seed', type=int, default=13)\nparser.add_argument('--dropout-p', type=float, default=0.5)\nparser.add_argument('--dim', type=int, default=512)\nparser.add_argument('--train-split', type=float, default=0.8, help=\n 'Training fraction of the train/test split')\nparser.add_argument('--allow-cache', action='store_true', help=\n 'once the dataset has been generated, it will be saved to a file to be loaded faster'\n )\nparser.add_argument('--trajectory-length', type=int, default=100)\nparser.add_argument('--minibatch-size', type=int, default=10)\nparser.add_argument('--n-image-bins', type=int, default=20)\nparser.add_argument('--n-hd-cells', type=int, default=0, help=\n 'If non-zero, use linear and angular velocity as well as HD cell output')\nparser.add_argument('--sin-cos-ang', type=int, default=1, choices=[0, 1],\n help=\n 'Use the sin and cos of the angular velocity if angular velocities are used'\n )\nparser.add_argument('--use-lmu', action='store_true')\nparser.add_argument('--lmu-order', type=int, default=6)\nparser.add_argument('--no-cache-load', action='store_true', help=\n 'do not load from cache')\nargs = parser.parse_args()\nssp_scaling = args.ssp_scaling\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\ndata = np.load(args.dataset)\nlimit_low = 0\nlimit_high = 2.2\nres = 128\nencoding_func, dim = get_encoding_function(args, limit_low=limit_low,\n limit_high=limit_high)\nxs = np.linspace(limit_low, limit_high, res)\nys = np.linspace(limit_low, limit_high, res)\nheatmap_vectors = np.zeros((len(xs), len(ys), dim))\nprint('Generating Heatmap Vectors')\nfor i, x in enumerate(xs):\n for j, y in enumerate(ys):\n heatmap_vectors[i, j, :] = encoding_func(x=x, y=y)\n heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])\nprint('Heatmap Vector Generation Complete')\nn_samples = args.n_samples\nrollout_length = args.trajectory_length\nbatch_size = args.minibatch_size\nif args.n_hd_cells > 0:\n hd_encoding_func = hd_gauss_encoding_func(dim=args.n_hd_cells, sigma=\n 0.25, use_softmax=False, rng=np.random.RandomState(args.seed))\n if args.sin_cos_ang:\n input_size = 3\n else:\n input_size = 2\n model = SSPPathIntegrationModel(input_size=input_size, unroll_length=\n rollout_length, sp_dim=dim + args.n_hd_cells, dropout_p=args.\n dropout_p, use_lmu=args.use_lmu, order=args.lmu_order)\nelse:\n hd_encoding_func = None\n model = SSPPathIntegrationModel(input_size=2, unroll_length=\n rollout_length, sp_dim=dim, dropout_p=args.dropout_p, use_lmu=args.\n use_lmu, order=args.lmu_order)\nmodel.load_state_dict(torch.load(args.model), strict=False)\nmodel.eval()\nencoding_specific = ''\nif 'ssp' in args.spatial_encoding:\n encoding_specific = args.ssp_scaling\nelif args.spatial_encoding == 'frozen-learned':\n encoding_specific = args.frozen_model\nelif args.spatial_encoding == 'pc-gauss' or args.spatial_encoding == 'pc-gauss-softmax':\n encoding_specific = args.pc_gauss_sigma\nelif args.spatial_encoding == 'pc-dog':\n encoding_specific = '{}-{}'.format(args.pc_gauss_sigma, args.pc_diff_sigma)\nelif args.spatial_encoding == 'hex-trig':\n encoding_specific = args.hex_freq_coef\nif 'tf' in args.dataset:\n cache_fname = 'dataset_cache/tf_{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nelse:\n cache_fname = 'dataset_cache/{}_{}_{}_{}_{}_{}.npz'.format(args.\n spatial_encoding, args.dim, args.seed, args.n_samples, args.\n n_hd_cells, encoding_specific)\nif os.path.exists(cache_fname) and not args.no_cache_load:\n print('Generating Train and Test Loaders from Cache')\n trainloader, testloader = load_from_cache(cache_fname, batch_size=\n batch_size, n_samples=n_samples)\nelse:\n print('Generating Train and Test Loaders')\n if 'tf' in args.dataset:\n assert args.sin_cos_ang == 1\n trainloader, testloader = tf_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n elif args.n_hd_cells > 0:\n trainloader, testloader = angular_train_test_loaders(data,\n n_train_samples=n_samples, n_test_samples=n_samples,\n rollout_length=rollout_length, batch_size=batch_size, encoding=\n args.spatial_encoding, encoding_func=encoding_func,\n encoding_dim=args.dim, train_split=args.train_split, hd_dim=\n args.n_hd_cells, hd_encoding_func=hd_encoding_func, sin_cos_ang\n =args.sin_cos_ang)\n else:\n trainloader, testloader = train_test_loaders(data, n_train_samples=\n n_samples, n_test_samples=n_samples, rollout_length=\n rollout_length, batch_size=batch_size, encoding=args.\n spatial_encoding, encoding_func=encoding_func, encoding_dim=\n args.dim, train_split=args.train_split)\n if args.allow_cache:\n if not os.path.exists('dataset_cache'):\n os.makedirs('dataset_cache')\n np.savez(cache_fname, train_velocity_inputs=trainloader.dataset.\n velocity_inputs, train_ssp_inputs=trainloader.dataset.\n ssp_inputs, train_ssp_outputs=trainloader.dataset.ssp_outputs,\n test_velocity_inputs=testloader.dataset.velocity_inputs,\n test_ssp_inputs=testloader.dataset.ssp_inputs, test_ssp_outputs\n =testloader.dataset.ssp_outputs)\nprint('Train and Test Loaders Generation Complete')\nstarts = [0.2] * 10\nends = np.linspace(0.4, 1.0, num=10)\nmasks_parameters = zip(starts, ends.tolist())\nlatest_epoch_scorer = scores.GridScorer(nbins=args.n_image_bins,\n coords_range=((0, 2.2), (0, 2.2)), mask_parameters=masks_parameters)\nfname_lstm_pred = '{}_{}samples_lstm_pred.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_lstm_truth = '{}_{}samples_lstm_truth.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_dense_pred = '{}_{}samples_dense_pred.pdf'.format(args.fname_prefix,\n args.n_samples)\nfname_dense_truth = '{}_{}samples_dense_truth.pdf'.format(args.fname_prefix,\n args.n_samples)\nprint('Testing')\nwith torch.no_grad():\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n ssp_pred, lstm_outputs, dense_outputs = model.forward_activations(\n velocity_inputs, ssp_inputs)\n predictions = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n coords = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n lstm_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.lstm_hidden_size))\n dense_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1],\n model.linear_hidden_size))\n assert rollout_length == ssp_pred.shape[0]\n print('Computing predicted locations and true locations')\n for ri in range(rollout_length):\n pred = ssp_pred.detach().numpy()[ri, :, :args.dim]\n predictions[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(pred, heatmap_vectors, xs, ys)\n coord = ssp_outputs.detach().numpy()[:, ri, :args.dim]\n coords[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = ssp_to_loc_v(coord, heatmap_vectors, xs, ys)\n lstm_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :\n ] = lstm_outputs.detach().numpy()[ri, :, :]\n dense_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[\n 1], :] = dense_outputs.detach().numpy()[ri, :, :]\nprint(np.max(predictions))\nprint(np.min(predictions))\n(grid_scores_60_pred, grid_scores_90_pred, grid_scores_60_separation_pred,\n grid_scores_90_separation_pred) = (utils.get_scores_and_plot(scorer=\n latest_epoch_scorer, data_abs_xy=predictions, activations=\n lstm_activations, directory='output_grid_scores', filename=fname_lstm_pred)\n )\n(grid_scores_60_truth, grid_scores_90_truth,\n grid_scores_60_separation_truth, grid_scores_90_separation_truth) = (utils\n .get_scores_and_plot(scorer=latest_epoch_scorer, data_abs_xy=coords,\n activations=lstm_activations, directory='output_grid_scores', filename=\n fname_lstm_truth))\n(grid_scores_60_dense_pred, grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred, grid_scores_90_separation_dense_pred\n ) = (utils.get_scores_and_plot(scorer=latest_epoch_scorer, data_abs_xy=\n predictions, activations=dense_activations, directory=\n 'output_grid_scores', filename=fname_dense_pred))\n(grid_scores_60_dense_truth, grid_scores_90_dense_truth,\n grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth) = (utils.get_scores_and_plot(\n scorer=latest_epoch_scorer, data_abs_xy=coords, activations=\n dense_activations, directory='output_grid_scores', filename=\n fname_dense_truth))\nprint(grid_scores_60_truth, grid_scores_90_truth,\n grid_scores_60_separation_truth, grid_scores_90_separation_truth)\nfname = 'output_grid_scores/{}_{}samples.npz'.format(args.fname_prefix,\n args.n_samples)\nnp.savez(fname, grid_scores_60_pred=grid_scores_60_pred,\n grid_scores_90_pred=grid_scores_90_pred, grid_scores_60_separation_pred\n =grid_scores_60_separation_pred, grid_scores_90_separation_pred=\n grid_scores_90_separation_pred, grid_scores_60_truth=\n grid_scores_60_truth, grid_scores_90_truth=grid_scores_90_truth,\n grid_scores_60_separation_truth=grid_scores_60_separation_truth,\n grid_scores_90_separation_truth=grid_scores_90_separation_truth,\n grid_scores_60_dense_pred=grid_scores_60_dense_pred,\n grid_scores_90_dense_pred=grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred=\n grid_scores_60_separation_dense_pred,\n grid_scores_90_separation_dense_pred=\n grid_scores_90_separation_dense_pred, grid_scores_60_dense_truth=\n grid_scores_60_dense_truth, grid_scores_90_dense_truth=\n grid_scores_90_dense_truth, grid_scores_60_separation_dense_truth=\n grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth=grid_scores_90_separation_dense_truth\n )\n",
"step-5": "# Compute grid scores using the new dataset format\n\nimport matplotlib\nimport os\n# allow code to work on machines without a display or in a screen session\ndisplay = os.environ.get('DISPLAY')\nif display is None or 'localhost' in display:\n matplotlib.use('agg')\n\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom datasets import train_test_loaders, angular_train_test_loaders, tf_train_test_loaders, load_from_cache\nfrom models import SSPPathIntegrationModel\nfrom datetime import datetime\nfrom tensorboardX import SummaryWriter\nimport json\nfrom spatial_semantic_pointers.utils import get_heatmap_vectors, ssp_to_loc, ssp_to_loc_v\nfrom spatial_semantic_pointers.plots import plot_predictions, plot_predictions_v\nimport matplotlib.pyplot as plt\nfrom path_integration_utils import pc_to_loc_v, encoding_func_from_model, pc_gauss_encoding_func, ssp_encoding_func, \\\n hd_gauss_encoding_func, hex_trig_encoding_func\nfrom ssp_navigation.utils.encodings import get_encoding_function\n\nimport grid_scoring.scores as scores\nimport grid_scoring.utils as utils\n# from grid_scoring.run_network import run_and_gather_activations, run_and_gather_localization_activations\nfrom path_integration_utils import encoding_func_from_model, pc_gauss_encoding_func\n\n\nparser = argparse.ArgumentParser('Compute grid scores for a path integration model')\nparser.add_argument('--n-samples', type=int, default=5000)\nparser.add_argument('--use-localization', action='store_true')\n# TODO: use these parameters\nparser.add_argument('--dataset', type=str, default='')\nparser.add_argument('--model', type=str, default='')\nparser.add_argument('--fname-prefix', type=str, default='sac')\n\nparser.add_argument('--spatial-encoding', type=str, default='ssp',\n choices=[\n 'ssp', 'hex-ssp', 'periodic-hex-ssp', 'grid-ssp', 'ind-ssp', 'orth-proj-ssp',\n 'rec-ssp', 'rec-hex-ssp', 'rec-ind-ssp', 'sub-toroid-ssp', 'var-sub-toroid-ssp',\n 'random', '2d', '2d-normalized', 'one-hot', 'hex-trig',\n 'trig', 'random-trig', 'random-rotated-trig', 'random-proj', 'legendre',\n 'learned', 'learned-normalized', 'frozen-learned', 'frozen-learned-normalized',\n 'pc-gauss', 'pc-dog', 'tile-coding'\n ])\n # choices=['ssp', '2d', 'frozen-learned', 'pc-gauss', 'pc-dog', 'pc-gauss-softmax', 'hex-trig', 'hex-trig-all-freq'])\nparser.add_argument('--frozen-model', type=str, default='', help='model to use frozen encoding weights from')\nparser.add_argument('--pc-gauss-sigma', type=float, default=0.25)\nparser.add_argument('--pc-diff-sigma', type=float, default=0.5)\nparser.add_argument('--hex-freq-coef', type=float, default=2.5, help='constant to scale frequencies by')\nparser.add_argument('--n-tiles', type=int, default=8, help='number of layers for tile coding')\nparser.add_argument('--n-bins', type=int, default=8, help='number of bins for tile coding')\nparser.add_argument('--ssp-scaling', type=float, default=1.0)\nparser.add_argument('--grid-ssp-min', type=float, default=0.25, help='minimum plane wave scale')\nparser.add_argument('--grid-ssp-max', type=float, default=2.0, help='maximum plane wave scale')\nparser.add_argument('--phi', type=float, default=0.5, help='phi as a fraction of pi for orth-proj-ssp')\nparser.add_argument('--n-proj', type=int, default=3, help='projection dimension for sub toroids')\nparser.add_argument('--scale-ratio', type=float, default=0, help='ratio between sub toroid scales')\nparser.add_argument('--hilbert-points', type=int, default=1, choices=[0, 1, 2, 3],\n help='pc centers. 0: random uniform. 1: hilbert curve. 2: evenly spaced grid. 3: hex grid')\n\nparser.add_argument('--seed', type=int, default=13)\nparser.add_argument('--dropout-p', type=float, default=0.5)\nparser.add_argument('--dim', type=int, default=512)\nparser.add_argument('--train-split', type=float, default=0.8, help='Training fraction of the train/test split')\nparser.add_argument('--allow-cache', action='store_true',\n help='once the dataset has been generated, it will be saved to a file to be loaded faster')\n\nparser.add_argument('--trajectory-length', type=int, default=100)\nparser.add_argument('--minibatch-size', type=int, default=10)\n\nparser.add_argument('--n-image-bins', type=int, default=20)\n\nparser.add_argument('--n-hd-cells', type=int, default=0, help='If non-zero, use linear and angular velocity as well as HD cell output')\nparser.add_argument('--sin-cos-ang', type=int, default=1, choices=[0, 1],\n help='Use the sin and cos of the angular velocity if angular velocities are used')\nparser.add_argument('--use-lmu', action='store_true')\nparser.add_argument('--lmu-order', type=int, default=6)\n\nparser.add_argument('--no-cache-load', action='store_true', help='do not load from cache')\n\nargs = parser.parse_args()\n\nssp_scaling = args.ssp_scaling\n\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\ndata = np.load(args.dataset)\n\n# only used for frozen-learned and other custom encoding functions\n# encoding_func = None\n\nlimit_low = 0 #* args.ssp_scaling\nlimit_high = 2.2 #* args.ssp_scaling\nres = 128 #256\n\nencoding_func, dim = get_encoding_function(args, limit_low=limit_low, limit_high=limit_high)\n\nxs = np.linspace(limit_low, limit_high, res)\nys = np.linspace(limit_low, limit_high, res)\n\n# FIXME: inefficient but will work for now\nheatmap_vectors = np.zeros((len(xs), len(ys), dim))\n\nprint(\"Generating Heatmap Vectors\")\n\nfor i, x in enumerate(xs):\n for j, y in enumerate(ys):\n heatmap_vectors[i, j, :] = encoding_func(\n # batch dim\n # np.array(\n # [[x, y]]\n # )\n # no batch dim\n # np.array(\n # [x, y]\n # )\n # new signature\n x=x, y=y\n )\n\n heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])\n\nprint(\"Heatmap Vector Generation Complete\")\n\nn_samples = args.n_samples\nrollout_length = args.trajectory_length\nbatch_size = args.minibatch_size\n\n\nif args.n_hd_cells > 0:\n hd_encoding_func = hd_gauss_encoding_func(dim=args.n_hd_cells, sigma=0.25, use_softmax=False, rng=np.random.RandomState(args.seed))\n if args.sin_cos_ang:\n input_size = 3\n else:\n input_size = 2\n model = SSPPathIntegrationModel(\n input_size=input_size, unroll_length=rollout_length,\n sp_dim=dim + args.n_hd_cells, dropout_p=args.dropout_p, use_lmu=args.use_lmu, order=args.lmu_order\n )\nelse:\n hd_encoding_func = None\n model = SSPPathIntegrationModel(\n input_size=2, unroll_length=rollout_length,\n sp_dim=dim, dropout_p=args.dropout_p, use_lmu=args.use_lmu, order=args.lmu_order\n )\n\n\n# model = SSPPathIntegrationModel(unroll_length=rollout_length, sp_dim=dim, dropout_p=args.dropout_p)\n\nmodel.load_state_dict(torch.load(args.model), strict=False)\n\nmodel.eval()\n\n# encoding specific cache string\nencoding_specific = ''\nif 'ssp' in args.spatial_encoding:\n encoding_specific = args.ssp_scaling\nelif args.spatial_encoding == 'frozen-learned':\n encoding_specific = args.frozen_model\nelif args.spatial_encoding == 'pc-gauss' or args.spatial_encoding == 'pc-gauss-softmax':\n encoding_specific = args.pc_gauss_sigma\nelif args.spatial_encoding == 'pc-dog':\n encoding_specific = '{}-{}'.format(args.pc_gauss_sigma, args.pc_diff_sigma)\nelif args.spatial_encoding == 'hex-trig':\n encoding_specific = args.hex_freq_coef\n\nif 'tf' in args.dataset:\n cache_fname = 'dataset_cache/tf_{}_{}_{}_{}_{}_{}.npz'.format(\n args.spatial_encoding, args.dim, args.seed, args.n_samples, args.n_hd_cells, encoding_specific\n )\nelse:\n cache_fname = 'dataset_cache/{}_{}_{}_{}_{}_{}.npz'.format(\n args.spatial_encoding, args.dim, args.seed, args.n_samples, args.n_hd_cells, encoding_specific\n )\n\n# if the file exists, load it from cache\nif os.path.exists(cache_fname) and not args.no_cache_load:\n print(\"Generating Train and Test Loaders from Cache\")\n trainloader, testloader = load_from_cache(cache_fname, batch_size=batch_size, n_samples=n_samples)\nelse:\n print(\"Generating Train and Test Loaders\")\n\n if 'tf' in args.dataset:\n # tfrecord dataset only supports using the sin and cos of angular velocity\n assert args.sin_cos_ang == 1\n\n trainloader, testloader = tf_train_test_loaders(\n data,\n n_train_samples=n_samples,\n n_test_samples=n_samples,\n rollout_length=rollout_length,\n batch_size=batch_size,\n encoding=args.spatial_encoding,\n encoding_func=encoding_func,\n encoding_dim=args.dim,\n train_split=args.train_split,\n hd_dim=args.n_hd_cells,\n hd_encoding_func=hd_encoding_func,\n sin_cos_ang=args.sin_cos_ang,\n )\n\n else:\n\n if args.n_hd_cells > 0:\n trainloader, testloader = angular_train_test_loaders(\n data,\n n_train_samples=n_samples,\n n_test_samples=n_samples,\n rollout_length=rollout_length,\n batch_size=batch_size,\n encoding=args.spatial_encoding,\n encoding_func=encoding_func,\n encoding_dim=args.dim,\n train_split=args.train_split,\n hd_dim=args.n_hd_cells,\n hd_encoding_func=hd_encoding_func,\n sin_cos_ang=args.sin_cos_ang,\n )\n else:\n trainloader, testloader = train_test_loaders(\n data,\n n_train_samples=n_samples,\n n_test_samples=n_samples,\n rollout_length=rollout_length,\n batch_size=batch_size,\n encoding=args.spatial_encoding,\n encoding_func=encoding_func,\n encoding_dim=args.dim,\n train_split=args.train_split,\n )\n\n if args.allow_cache:\n\n if not os.path.exists('dataset_cache'):\n os.makedirs('dataset_cache')\n\n np.savez(\n cache_fname,\n train_velocity_inputs=trainloader.dataset.velocity_inputs,\n train_ssp_inputs=trainloader.dataset.ssp_inputs,\n train_ssp_outputs=trainloader.dataset.ssp_outputs,\n test_velocity_inputs=testloader.dataset.velocity_inputs,\n test_ssp_inputs=testloader.dataset.ssp_inputs,\n test_ssp_outputs=testloader.dataset.ssp_outputs,\n )\n\nprint(\"Train and Test Loaders Generation Complete\")\n\nstarts = [0.2] * 10\nends = np.linspace(0.4, 1.0, num=10)\nmasks_parameters = zip(starts, ends.tolist())\nlatest_epoch_scorer = scores.GridScorer(\n nbins=args.n_image_bins,\n coords_range=((0, 2.2), (0, 2.2)), # data_reader.get_coord_range(),\n mask_parameters=masks_parameters,\n)\n\n\nfname_lstm_pred = '{}_{}samples_lstm_pred.pdf'.format(args.fname_prefix, args.n_samples)\nfname_lstm_truth = '{}_{}samples_lstm_truth.pdf'.format(args.fname_prefix, args.n_samples)\nfname_dense_pred = '{}_{}samples_dense_pred.pdf'.format(args.fname_prefix, args.n_samples)\nfname_dense_truth = '{}_{}samples_dense_truth.pdf'.format(args.fname_prefix, args.n_samples)\n\n# Run and gather activations\n\nprint(\"Testing\")\nwith torch.no_grad():\n # Everything is in one batch, so this loop will only happen once\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n\n ssp_pred, lstm_outputs, dense_outputs = model.forward_activations(velocity_inputs, ssp_inputs)\n\n predictions = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], 2))\n coords = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], 2))\n lstm_activations = np.zeros((ssp_pred.shape[0]*ssp_pred.shape[1], model.lstm_hidden_size))\n dense_activations = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], model.linear_hidden_size))\n\n assert rollout_length == ssp_pred.shape[0]\n\n # # For each neuron, contains the average activity at each spatial bin\n # # Computing for both ground truth and predicted location\n # rate_maps_pred = np.zeros((model.lstm_hidden_size, len(xs), len(ys)))\n # rate_maps_truth = np.zeros((model.lstm_hidden_size, len(xs), len(ys)))\n\n print(\"Computing predicted locations and true locations\")\n # Using all data, one chunk at a time\n for ri in range(rollout_length):\n\n # trim out head direction info if that was included by only looking up to args.encoding_dim\n\n # computing 'predicted' coordinates, where the agent thinks it is\n pred = ssp_pred.detach().numpy()[ri, :, :args.dim]\n # pred = pred / pred.sum(axis=1)[:, np.newaxis]\n predictions[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = ssp_to_loc_v(\n pred,\n heatmap_vectors, xs, ys\n )\n\n # computing 'ground truth' coordinates, where the agent should be\n coord = ssp_outputs.detach().numpy()[:, ri, :args.dim]\n # coord = coord / coord.sum(axis=1)[:, np.newaxis]\n coords[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = ssp_to_loc_v(\n coord,\n heatmap_vectors, xs, ys\n )\n\n # reshaping activations and converting to numpy array\n lstm_activations[ri*ssp_pred.shape[1]:(ri+1)*ssp_pred.shape[1], :] = lstm_outputs.detach().numpy()[ri, :, :]\n dense_activations[ri * ssp_pred.shape[1]:(ri + 1) * ssp_pred.shape[1], :] = dense_outputs.detach().numpy()[ri, :, :]\n\n# predictions = predictions / args.ssp_scaling\n# coords = coords / args.ssp_scaling\n\nprint(np.max(predictions))\nprint(np.min(predictions))\n\ngrid_scores_60_pred, grid_scores_90_pred, grid_scores_60_separation_pred, grid_scores_90_separation_pred = utils.get_scores_and_plot(\n scorer=latest_epoch_scorer,\n data_abs_xy=predictions, #res['pos_xy'],\n activations=lstm_activations, #res['bottleneck'],\n directory='output_grid_scores', #FLAGS.saver_results_directory,\n filename=fname_lstm_pred,\n)\n\ngrid_scores_60_truth, grid_scores_90_truth, grid_scores_60_separation_truth, grid_scores_90_separation_truth = utils.get_scores_and_plot(\n scorer=latest_epoch_scorer,\n data_abs_xy=coords, #res['pos_xy'],\n activations=lstm_activations, #res['bottleneck'],\n directory='output_grid_scores', #FLAGS.saver_results_directory,\n filename=fname_lstm_truth,\n)\n\ngrid_scores_60_dense_pred, grid_scores_90_dense_pred, grid_scores_60_separation_dense_pred, grid_scores_90_separation_dense_pred = utils.get_scores_and_plot(\n scorer=latest_epoch_scorer,\n data_abs_xy=predictions, #res['pos_xy'],\n activations=dense_activations, #res['bottleneck'],\n directory='output_grid_scores', #FLAGS.saver_results_directory,\n filename=fname_dense_pred,\n)\n\ngrid_scores_60_dense_truth, grid_scores_90_dense_truth, grid_scores_60_separation_dense_truth, grid_scores_90_separation_dense_truth = utils.get_scores_and_plot(\n scorer=latest_epoch_scorer,\n data_abs_xy=coords, #res['pos_xy'],\n activations=dense_activations, #res['bottleneck'],\n directory='output_grid_scores', #FLAGS.saver_results_directory,\n filename=fname_dense_truth,\n)\n\n\nprint(grid_scores_60_truth, grid_scores_90_truth, grid_scores_60_separation_truth, grid_scores_90_separation_truth)\n\n# Saving to make grid score values easy to compare for different variations\nfname = 'output_grid_scores/{}_{}samples.npz'.format(args.fname_prefix, args.n_samples)\nnp.savez(\n fname,\n grid_scores_60_pred=grid_scores_60_pred,\n grid_scores_90_pred=grid_scores_90_pred,\n grid_scores_60_separation_pred=grid_scores_60_separation_pred,\n grid_scores_90_separation_pred=grid_scores_90_separation_pred,\n grid_scores_60_truth=grid_scores_60_truth,\n grid_scores_90_truth=grid_scores_90_truth,\n grid_scores_60_separation_truth=grid_scores_60_separation_truth,\n grid_scores_90_separation_truth=grid_scores_90_separation_truth,\n\n grid_scores_60_dense_pred=grid_scores_60_dense_pred,\n grid_scores_90_dense_pred=grid_scores_90_dense_pred,\n grid_scores_60_separation_dense_pred=grid_scores_60_separation_dense_pred,\n grid_scores_90_separation_dense_pred=grid_scores_90_separation_dense_pred,\n grid_scores_60_dense_truth=grid_scores_60_dense_truth,\n grid_scores_90_dense_truth=grid_scores_90_dense_truth,\n grid_scores_60_separation_dense_truth=grid_scores_60_separation_dense_truth,\n grid_scores_90_separation_dense_truth=grid_scores_90_separation_dense_truth,\n)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import os
from flask import Flask,request
from flask_restful import Resource,Api,reqparse
from flask_jwt import JWT,jwt_required
from resources.Users import UserRegister
from security import authenticate,identity
from resources.items import Item, ItemList
from resources.stores import Store, StoreList
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL','sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'naveen'
api = Api(app)
jwt = JWT(app,authenticate,identity)
api.add_resource(StoreList,"/stores")
api.add_resource(Store,"/store/<string:name>")
api.add_resource(ItemList,"/items")
api.add_resource(Item,"/item/<string:name>")
api.add_resource(UserRegister,"/register")
if __name__ =="__main__":
from db import db
db.init_app(app)
app.run(port=5000,debug=True)
|
normal
|
{
"blob_id": "bf8f7b51b685f0e9131cb4d8a0bfc16ee5ad1263",
"index": 3281,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napi.add_resource(StoreList, '/stores')\napi.add_resource(Store, '/store/<string:name>')\napi.add_resource(ItemList, '/items')\napi.add_resource(Item, '/item/<string:name>')\napi.add_resource(UserRegister, '/register')\nif __name__ == '__main__':\n from db import db\n db.init_app(app)\n app.run(port=5000, debug=True)\n",
"step-3": "<mask token>\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',\n 'sqlite:///data.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'naveen'\napi = Api(app)\njwt = JWT(app, authenticate, identity)\napi.add_resource(StoreList, '/stores')\napi.add_resource(Store, '/store/<string:name>')\napi.add_resource(ItemList, '/items')\napi.add_resource(Item, '/item/<string:name>')\napi.add_resource(UserRegister, '/register')\nif __name__ == '__main__':\n from db import db\n db.init_app(app)\n app.run(port=5000, debug=True)\n",
"step-4": "import os\nfrom flask import Flask, request\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_jwt import JWT, jwt_required\nfrom resources.Users import UserRegister\nfrom security import authenticate, identity\nfrom resources.items import Item, ItemList\nfrom resources.stores import Store, StoreList\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',\n 'sqlite:///data.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'naveen'\napi = Api(app)\njwt = JWT(app, authenticate, identity)\napi.add_resource(StoreList, '/stores')\napi.add_resource(Store, '/store/<string:name>')\napi.add_resource(ItemList, '/items')\napi.add_resource(Item, '/item/<string:name>')\napi.add_resource(UserRegister, '/register')\nif __name__ == '__main__':\n from db import db\n db.init_app(app)\n app.run(port=5000, debug=True)\n",
"step-5": "import os\nfrom flask import Flask,request\nfrom flask_restful import Resource,Api,reqparse\nfrom flask_jwt import JWT,jwt_required\nfrom resources.Users import UserRegister\nfrom security import authenticate,identity\nfrom resources.items import Item, ItemList\nfrom resources.stores import Store, StoreList\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL','sqlite:///data.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'naveen'\napi = Api(app)\n\n\n\njwt = JWT(app,authenticate,identity)\n\n\n\napi.add_resource(StoreList,\"/stores\")\napi.add_resource(Store,\"/store/<string:name>\")\napi.add_resource(ItemList,\"/items\")\napi.add_resource(Item,\"/item/<string:name>\")\napi.add_resource(UserRegister,\"/register\")\n\nif __name__ ==\"__main__\":\n from db import db\n db.init_app(app)\n app.run(port=5000,debug=True) ",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# coding: utf-8
num = int(input())
str = input().split()
table = [int(i) for i in str]
list.sort(table)
print(table[num-1] - table[0])
|
normal
|
{
"blob_id": "d853964d424e628d6331b27123ad045f8d945dc0",
"index": 4026,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlist.sort(table)\nprint(table[num - 1] - table[0])\n",
"step-3": "num = int(input())\nstr = input().split()\ntable = [int(i) for i in str]\nlist.sort(table)\nprint(table[num - 1] - table[0])\n",
"step-4": "# coding: utf-8\n\nnum = int(input())\nstr = input().split()\ntable = [int(i) for i in str]\nlist.sort(table)\nprint(table[num-1] - table[0])",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
#
#
#
# ------------------------------------------------------------------------------------------------------------------------------
#
# This program have been developed by Hamed Noori and with citiation of the related publicaitons
# can be used without permission.
# This program is for a novel architecture for traffic light control system which can form and manipulate
# vehicular platoons using clusters of traffic lights. This method, called Platoon-Based Intelligent Traffic Lights (PB-ITL)
# is based on coordinated traffic lights that are connected and are also able to communicate with vehicles wirelessly. PB-ITL
# groups traffic lights in clusters and each cluster tries to provide proper green status for the platoon of vehicles, using the
# Platooning concept which is seeking to utilize close to full capacity of roads.
# This lib is a Python-based program which can simulate a city with dynamic intelligent traffic lights.
# The author can be reach at [email protected]
#
# ------------------------------------------------------------------------------------------------------------------------------
#
#
def start_simulation(sumo, scenario, network, begin, end, interval, output):
logging.debug("Finding unused port")
unused_port_lock = UnusedPortLock()
unused_port_lock.__enter__()
remote_port = find_unused_port()
logging.debug("Port %d was found" % remote_port)
logging.debug("Starting SUMO as a server")
sumo = subprocess.Popen(["D:\\PATH\\sumo-gui.exe", "-c", "D:\\\PATH\\Your.sumo.cfg", "--tripinfo-output", output,"--device.emissions.probability", "1.0" , "--remote-port", str(remote_port)], stdout=sys.stdout, stderr=sys.stderr)
unused_port_lock.release()
try:
traci.init(remote_port)
run(network, begin, end, interval)
except Exception:
logging.exception("Something bad happened")
finally:
logging.exception("Terminating SUMO")
terminate_sumo(sumo)
unused_port_lock.__exit__()
|
normal
|
{
"blob_id": "4775bef3623497e9bbe79ca2d4e9e9da0422c450",
"index": 401,
"step-1": "<mask token>\n",
"step-2": "def start_simulation(sumo, scenario, network, begin, end, interval, output):\n logging.debug('Finding unused port')\n unused_port_lock = UnusedPortLock()\n unused_port_lock.__enter__()\n remote_port = find_unused_port()\n logging.debug('Port %d was found' % remote_port)\n logging.debug('Starting SUMO as a server')\n sumo = subprocess.Popen(['D:\\\\PATH\\\\sumo-gui.exe', '-c',\n 'D:\\\\\\\\PATH\\\\Your.sumo.cfg', '--tripinfo-output', output,\n '--device.emissions.probability', '1.0', '--remote-port', str(\n remote_port)], stdout=sys.stdout, stderr=sys.stderr)\n unused_port_lock.release()\n try:\n traci.init(remote_port)\n run(network, begin, end, interval)\n except Exception:\n logging.exception('Something bad happened')\n finally:\n logging.exception('Terminating SUMO')\n terminate_sumo(sumo)\n unused_port_lock.__exit__()\n",
"step-3": "# \r\n#\r\n#\r\n# ------------------------------------------------------------------------------------------------------------------------------\r\n#\r\n# This program have been developed by Hamed Noori and with citiation of the related publicaitons\r\n# can be used without permission.\r\n# This program is for a novel architecture for traffic light control system which can form and manipulate \r\n# vehicular platoons using clusters of traffic lights. This method, called Platoon-Based Intelligent Traffic Lights (PB-ITL) \r\n# is based on coordinated traffic lights that are connected and are also able to communicate with vehicles wirelessly. PB-ITL \r\n# groups traffic lights in clusters and each cluster tries to provide proper green status for the platoon of vehicles, using the\r\n# Platooning concept which is seeking to utilize close to full capacity of roads. \r\n# This lib is a Python-based program which can simulate a city with dynamic intelligent traffic lights. \r\n# The author can be reach at [email protected]\r\n#\r\n# ------------------------------------------------------------------------------------------------------------------------------\r\n#\r\n# \r\ndef start_simulation(sumo, scenario, network, begin, end, interval, output):\r\n logging.debug(\"Finding unused port\")\r\n \r\n unused_port_lock = UnusedPortLock()\r\n unused_port_lock.__enter__()\r\n remote_port = find_unused_port()\r\n \r\n logging.debug(\"Port %d was found\" % remote_port)\r\n \r\n logging.debug(\"Starting SUMO as a server\")\r\n \r\n sumo = subprocess.Popen([\"D:\\\\PATH\\\\sumo-gui.exe\", \"-c\", \"D:\\\\\\PATH\\\\Your.sumo.cfg\", \"--tripinfo-output\", output,\"--device.emissions.probability\", \"1.0\" , \"--remote-port\", str(remote_port)], stdout=sys.stdout, stderr=sys.stderr) \r\n unused_port_lock.release()\r\n \r\n try: \r\n traci.init(remote_port) \r\n run(network, begin, end, interval)\r\n except Exception:\r\n logging.exception(\"Something bad happened\")\r\n finally:\r\n logging.exception(\"Terminating SUMO\") \r\n terminate_sumo(sumo)\r\n unused_port_lock.__exit__()\r\n \r\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import math
from os.path import join, relpath, dirname
from typing import List, Tuple
from common import read_input
convert_output = List[str]
class GridWalker:
def __init__(self):
self._current_pos = [0, 0]
self._heading = math.pi / 2
@property
def position(self):
return self._current_pos
@property
def distance_from_home(self):
return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))
def __repr__(self):
return (
f"Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}"
)
def walk(self, direction: str):
heading, distance = self._convert_direction(direction)
self._heading += heading
self._current_pos[0] += int(math.cos(self._heading) * distance)
self._current_pos[1] += int(math.sin(self._heading) * distance)
@staticmethod
def _convert_direction(direction: str) -> Tuple[float, int]:
"""Converts a direction into a heading and distance."""
direction_to_heading = {"L": math.pi / 2, "R": -math.pi / 2}
return direction_to_heading[direction[0]], int(direction[1])
def input_converter(input_line: str) -> convert_output:
return input_line.split(", ")
def solve_part1(converted_input: List[convert_output]):
walker = GridWalker()
for direction in converted_input[0]:
walker.walk(direction)
return walker.distance_from_home
def solve_part2(converted_input: List[convert_output]):
return 1
if __name__ == "__main__":
raw_input = read_input(
join(relpath(dirname(__file__)), "input.txt"), input_converter
)
print(f"Solution of 2016/1 - Part 1 is '{solve_part1(raw_input)}'")
print(f"Solution of 2016/1 - Part 2 is '{solve_part2(raw_input)}'")
|
normal
|
{
"blob_id": "907f0564d574f197c25b05a79569a8b6f260a8cd",
"index": 7817,
"step-1": "<mask token>\n\n\nclass GridWalker:\n\n def __init__(self):\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):\n return self._current_pos\n\n @property\n def distance_from_home(self):\n return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))\n\n def __repr__(self):\n return (\n f'Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}'\n )\n\n def walk(self, direction: str):\n heading, distance = self._convert_direction(direction)\n self._heading += heading\n self._current_pos[0] += int(math.cos(self._heading) * distance)\n self._current_pos[1] += int(math.sin(self._heading) * distance)\n\n @staticmethod\n def _convert_direction(direction: str) ->Tuple[float, int]:\n \"\"\"Converts a direction into a heading and distance.\"\"\"\n direction_to_heading = {'L': math.pi / 2, 'R': -math.pi / 2}\n return direction_to_heading[direction[0]], int(direction[1])\n\n\n<mask token>\n\n\ndef solve_part1(converted_input: List[convert_output]):\n walker = GridWalker()\n for direction in converted_input[0]:\n walker.walk(direction)\n return walker.distance_from_home\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass GridWalker:\n\n def __init__(self):\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):\n return self._current_pos\n\n @property\n def distance_from_home(self):\n return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))\n\n def __repr__(self):\n return (\n f'Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}'\n )\n\n def walk(self, direction: str):\n heading, distance = self._convert_direction(direction)\n self._heading += heading\n self._current_pos[0] += int(math.cos(self._heading) * distance)\n self._current_pos[1] += int(math.sin(self._heading) * distance)\n\n @staticmethod\n def _convert_direction(direction: str) ->Tuple[float, int]:\n \"\"\"Converts a direction into a heading and distance.\"\"\"\n direction_to_heading = {'L': math.pi / 2, 'R': -math.pi / 2}\n return direction_to_heading[direction[0]], int(direction[1])\n\n\ndef input_converter(input_line: str) ->convert_output:\n return input_line.split(', ')\n\n\ndef solve_part1(converted_input: List[convert_output]):\n walker = GridWalker()\n for direction in converted_input[0]:\n walker.walk(direction)\n return walker.distance_from_home\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass GridWalker:\n\n def __init__(self):\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):\n return self._current_pos\n\n @property\n def distance_from_home(self):\n return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))\n\n def __repr__(self):\n return (\n f'Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}'\n )\n\n def walk(self, direction: str):\n heading, distance = self._convert_direction(direction)\n self._heading += heading\n self._current_pos[0] += int(math.cos(self._heading) * distance)\n self._current_pos[1] += int(math.sin(self._heading) * distance)\n\n @staticmethod\n def _convert_direction(direction: str) ->Tuple[float, int]:\n \"\"\"Converts a direction into a heading and distance.\"\"\"\n direction_to_heading = {'L': math.pi / 2, 'R': -math.pi / 2}\n return direction_to_heading[direction[0]], int(direction[1])\n\n\ndef input_converter(input_line: str) ->convert_output:\n return input_line.split(', ')\n\n\ndef solve_part1(converted_input: List[convert_output]):\n walker = GridWalker()\n for direction in converted_input[0]:\n walker.walk(direction)\n return walker.distance_from_home\n\n\ndef solve_part2(converted_input: List[convert_output]):\n return 1\n\n\nif __name__ == '__main__':\n raw_input = read_input(join(relpath(dirname(__file__)), 'input.txt'),\n input_converter)\n print(f\"Solution of 2016/1 - Part 1 is '{solve_part1(raw_input)}'\")\n print(f\"Solution of 2016/1 - Part 2 is '{solve_part2(raw_input)}'\")\n",
"step-4": "import math\nfrom os.path import join, relpath, dirname\nfrom typing import List, Tuple\nfrom common import read_input\nconvert_output = List[str]\n\n\nclass GridWalker:\n\n def __init__(self):\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):\n return self._current_pos\n\n @property\n def distance_from_home(self):\n return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))\n\n def __repr__(self):\n return (\n f'Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}'\n )\n\n def walk(self, direction: str):\n heading, distance = self._convert_direction(direction)\n self._heading += heading\n self._current_pos[0] += int(math.cos(self._heading) * distance)\n self._current_pos[1] += int(math.sin(self._heading) * distance)\n\n @staticmethod\n def _convert_direction(direction: str) ->Tuple[float, int]:\n \"\"\"Converts a direction into a heading and distance.\"\"\"\n direction_to_heading = {'L': math.pi / 2, 'R': -math.pi / 2}\n return direction_to_heading[direction[0]], int(direction[1])\n\n\ndef input_converter(input_line: str) ->convert_output:\n return input_line.split(', ')\n\n\ndef solve_part1(converted_input: List[convert_output]):\n walker = GridWalker()\n for direction in converted_input[0]:\n walker.walk(direction)\n return walker.distance_from_home\n\n\ndef solve_part2(converted_input: List[convert_output]):\n return 1\n\n\nif __name__ == '__main__':\n raw_input = read_input(join(relpath(dirname(__file__)), 'input.txt'),\n input_converter)\n print(f\"Solution of 2016/1 - Part 1 is '{solve_part1(raw_input)}'\")\n print(f\"Solution of 2016/1 - Part 2 is '{solve_part2(raw_input)}'\")\n",
"step-5": "import math\nfrom os.path import join, relpath, dirname\nfrom typing import List, Tuple\nfrom common import read_input\n\n\nconvert_output = List[str]\n\n\nclass GridWalker:\n def __init__(self):\n\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):\n return self._current_pos\n\n @property\n def distance_from_home(self):\n return int(abs(self._current_pos[0]) + abs(self._current_pos[1]))\n\n def __repr__(self):\n return (\n f\"Self @ {self.position[0]},{self.position[1]} - {self.distance_from_home}\"\n )\n\n def walk(self, direction: str):\n\n heading, distance = self._convert_direction(direction)\n\n self._heading += heading\n\n self._current_pos[0] += int(math.cos(self._heading) * distance)\n self._current_pos[1] += int(math.sin(self._heading) * distance)\n\n @staticmethod\n def _convert_direction(direction: str) -> Tuple[float, int]:\n \"\"\"Converts a direction into a heading and distance.\"\"\"\n\n direction_to_heading = {\"L\": math.pi / 2, \"R\": -math.pi / 2}\n\n return direction_to_heading[direction[0]], int(direction[1])\n\n\ndef input_converter(input_line: str) -> convert_output:\n return input_line.split(\", \")\n\n\ndef solve_part1(converted_input: List[convert_output]):\n\n walker = GridWalker()\n for direction in converted_input[0]:\n walker.walk(direction)\n return walker.distance_from_home\n\n\ndef solve_part2(converted_input: List[convert_output]):\n return 1\n\n\nif __name__ == \"__main__\":\n raw_input = read_input(\n join(relpath(dirname(__file__)), \"input.txt\"), input_converter\n )\n\n print(f\"Solution of 2016/1 - Part 1 is '{solve_part1(raw_input)}'\")\n print(f\"Solution of 2016/1 - Part 2 is '{solve_part2(raw_input)}'\")\n",
"step-ids": [
8,
9,
11,
13,
14
]
}
|
[
8,
9,
11,
13,
14
] |
from django.shortcuts import render, redirect
from .models import Game, Player, CardsInHand, Feedback
from django.db.models import Q
from .forms import GameForm, JoinForm, FeedbackForm
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.generic import CreateView
import json
# from django.contrib.auth.decorators import login_required
def get_joined_players(request, game_id):
game = get_object_or_404(Game, pk=game_id)
return HttpResponse(str(game.joined_players))
def create_new_game(request):
if request.method == "POST":
form_data = json.loads(request.body.decode('utf-8'))
form = GameForm(form_data)
if form.is_valid():
number_of_players = form.cleaned_data["number_of_players"]
new_game = Game(number_of_players=int(number_of_players))
new_game.instantiate() # initializes new game
new_game.save() # save new game to db
# create first player
new_player = Player(name=form.cleaned_data["creator_name"], game_id=new_game)
new_player.save()
# create new session to allow the user to play the game
request.session['player_id'] = new_player.pk
return JsonResponse({
"code": new_game.code,
"game_id": new_game.pk,
"number_of_players": number_of_players,
})
# return render(request, "game_created.html", {
# "form": form,
# "game_code": new_game.code,
# "n_players": number_of_players,
# "game_id": new_game.pk,
# "your_name": new_player.name,
# })
else:
return JsonResponse(form.errors.as_json(), safe=False, status=400)
else:
# set a dummy player id in player's session. this is needed to make channels session persistence work (for matchmaking)
if('player_id' not in request.session):
request.session['player_id'] = 0
create_form = GameForm(initial={'number_of_players': '2'})
join_form = JoinForm()
feedback_form = FeedbackForm()
return render(
request,
"newhome.html",
{
"create_form": create_form,
"join_form": join_form,
"feedback_form": feedback_form,
}
)
def join_game(request):
if request.method != "POST":
return HttpResponseRedirect("/game")
form_data = json.loads(request.body.decode('utf-8'))
form = JoinForm(form_data)
if form.is_valid():
code = int(form.cleaned_data['code'])
input_name = form.cleaned_data['name']
else:
return JsonResponse(form.errors.as_json(), safe=False, status=400)
game = get_object_or_404(Game, code=code)
if(game.joined_players < game.number_of_players):
# increment the number of players who joined this game
game.joined_players = game.joined_players + 1
game.save()
# create player and append it to this game
new_player = Player(name=input_name, game_id=game, player_number=game.joined_players)
new_player.save()
# create new session to allow user to play
request.session['player_id'] = new_player.pk
if(new_player.player_number == game.number_of_players):
# last player joined: deal cards to all players; game can now being
game.deal_cards_to_players()
return JsonResponse(game.pk, safe=False)
def game(request, game_id):
err_str = ''
this_game = get_object_or_404(Game, pk=game_id)
print(request.session.keys())
# if game is over, redirect to home
if this_game.has_been_won:
return redirect(create_new_game)
# get players who joined this game
players = Player.objects.filter(game_id=game_id)
if('player_id' not in request.session): # check if user has a session variable player_id
err_str = "Unauthenticated user"
this_player = get_object_or_404(Player, pk=request.session['player_id'])
if(this_player not in players): # check if this player has joined the game
err_str = "La partita richiesta non esiste o si è già conclusa."
if err_str != '':
return render(
request,
'error.html',
{
'error': err_str,
},
status=403
)
return render(request, 'gametest.html', {
'game_id': this_game.pk,
'number_of_players': this_game.number_of_players,
})
def feedback_create(request):
if request.method != "POST":
return HttpResponseRedirect("/game")
form_data = json.loads(request.body.decode('utf-8'))
form = FeedbackForm(form_data)
if form.is_valid():
sender_name = form.cleaned_data['sender_name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
else:
return JsonResponse(form.errors.as_json(), safe=False, status=400)
feedback = Feedback(sender_name=sender_name, email=email, message=message)
feedback.save()
return JsonResponse("[]", status=200, safe=False)
def restart_game(request, game_id):
this_game = get_object_or_404(Game, pk=game_id)
# if game isn't over, redirect to home
if not this_game.has_been_won:
return redirect(create_new_game)
# get players who joined this game
players = Player.objects.filter(game_id=game_id)
if('player_id' not in request.session): # check if user has a session variable player_id
return redirect(create_new_game)
this_player = get_object_or_404(Player, pk=request.session['player_id'])
if(this_player not in players): # check if this player has joined the game
return redirect(create_new_game)
this_game.reset()
this_game.deal_cards_to_players()
return JsonResponse({'status': 'ok'})
|
normal
|
{
"blob_id": "d650f578ea30772489625ee26f3e4bf04131964b",
"index": 6140,
"step-1": "<mask token>\n\n\ndef join_game(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = JoinForm(form_data)\n if form.is_valid():\n code = int(form.cleaned_data['code'])\n input_name = form.cleaned_data['name']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n game = get_object_or_404(Game, code=code)\n if game.joined_players < game.number_of_players:\n game.joined_players = game.joined_players + 1\n game.save()\n new_player = Player(name=input_name, game_id=game, player_number=\n game.joined_players)\n new_player.save()\n request.session['player_id'] = new_player.pk\n if new_player.player_number == game.number_of_players:\n game.deal_cards_to_players()\n return JsonResponse(game.pk, safe=False)\n\n\ndef game(request, game_id):\n err_str = ''\n this_game = get_object_or_404(Game, pk=game_id)\n print(request.session.keys())\n if this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n err_str = 'Unauthenticated user'\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n err_str = 'La partita richiesta non esiste o si è già conclusa.'\n if err_str != '':\n return render(request, 'error.html', {'error': err_str}, status=403)\n return render(request, 'gametest.html', {'game_id': this_game.pk,\n 'number_of_players': this_game.number_of_players})\n\n\n<mask token>\n\n\ndef restart_game(request, game_id):\n this_game = get_object_or_404(Game, pk=game_id)\n if not this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n return redirect(create_new_game)\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n return redirect(create_new_game)\n this_game.reset()\n this_game.deal_cards_to_players()\n return JsonResponse({'status': 'ok'})\n",
"step-2": "<mask token>\n\n\ndef get_joined_players(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n return HttpResponse(str(game.joined_players))\n\n\n<mask token>\n\n\ndef join_game(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = JoinForm(form_data)\n if form.is_valid():\n code = int(form.cleaned_data['code'])\n input_name = form.cleaned_data['name']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n game = get_object_or_404(Game, code=code)\n if game.joined_players < game.number_of_players:\n game.joined_players = game.joined_players + 1\n game.save()\n new_player = Player(name=input_name, game_id=game, player_number=\n game.joined_players)\n new_player.save()\n request.session['player_id'] = new_player.pk\n if new_player.player_number == game.number_of_players:\n game.deal_cards_to_players()\n return JsonResponse(game.pk, safe=False)\n\n\ndef game(request, game_id):\n err_str = ''\n this_game = get_object_or_404(Game, pk=game_id)\n print(request.session.keys())\n if this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n err_str = 'Unauthenticated user'\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n err_str = 'La partita richiesta non esiste o si è già conclusa.'\n if err_str != '':\n return render(request, 'error.html', {'error': err_str}, status=403)\n return render(request, 'gametest.html', {'game_id': this_game.pk,\n 'number_of_players': this_game.number_of_players})\n\n\ndef feedback_create(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = FeedbackForm(form_data)\n if form.is_valid():\n sender_name = form.cleaned_data['sender_name']\n email = form.cleaned_data['email']\n message = form.cleaned_data['message']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n feedback = Feedback(sender_name=sender_name, email=email, message=message)\n feedback.save()\n return JsonResponse('[]', status=200, safe=False)\n\n\ndef restart_game(request, game_id):\n this_game = get_object_or_404(Game, pk=game_id)\n if not this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n return redirect(create_new_game)\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n return redirect(create_new_game)\n this_game.reset()\n this_game.deal_cards_to_players()\n return JsonResponse({'status': 'ok'})\n",
"step-3": "<mask token>\n\n\ndef get_joined_players(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n return HttpResponse(str(game.joined_players))\n\n\ndef create_new_game(request):\n if request.method == 'POST':\n form_data = json.loads(request.body.decode('utf-8'))\n form = GameForm(form_data)\n if form.is_valid():\n number_of_players = form.cleaned_data['number_of_players']\n new_game = Game(number_of_players=int(number_of_players))\n new_game.instantiate()\n new_game.save()\n new_player = Player(name=form.cleaned_data['creator_name'],\n game_id=new_game)\n new_player.save()\n request.session['player_id'] = new_player.pk\n return JsonResponse({'code': new_game.code, 'game_id': new_game\n .pk, 'number_of_players': number_of_players})\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n else:\n if 'player_id' not in request.session:\n request.session['player_id'] = 0\n create_form = GameForm(initial={'number_of_players': '2'})\n join_form = JoinForm()\n feedback_form = FeedbackForm()\n return render(request, 'newhome.html', {'create_form': create_form,\n 'join_form': join_form, 'feedback_form': feedback_form})\n\n\ndef join_game(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = JoinForm(form_data)\n if form.is_valid():\n code = int(form.cleaned_data['code'])\n input_name = form.cleaned_data['name']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n game = get_object_or_404(Game, code=code)\n if game.joined_players < game.number_of_players:\n game.joined_players = game.joined_players + 1\n game.save()\n new_player = Player(name=input_name, game_id=game, player_number=\n game.joined_players)\n new_player.save()\n request.session['player_id'] = new_player.pk\n if new_player.player_number == game.number_of_players:\n game.deal_cards_to_players()\n return JsonResponse(game.pk, safe=False)\n\n\ndef game(request, game_id):\n err_str = ''\n this_game = get_object_or_404(Game, pk=game_id)\n print(request.session.keys())\n if this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n err_str = 'Unauthenticated user'\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n err_str = 'La partita richiesta non esiste o si è già conclusa.'\n if err_str != '':\n return render(request, 'error.html', {'error': err_str}, status=403)\n return render(request, 'gametest.html', {'game_id': this_game.pk,\n 'number_of_players': this_game.number_of_players})\n\n\ndef feedback_create(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = FeedbackForm(form_data)\n if form.is_valid():\n sender_name = form.cleaned_data['sender_name']\n email = form.cleaned_data['email']\n message = form.cleaned_data['message']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n feedback = Feedback(sender_name=sender_name, email=email, message=message)\n feedback.save()\n return JsonResponse('[]', status=200, safe=False)\n\n\ndef restart_game(request, game_id):\n this_game = get_object_or_404(Game, pk=game_id)\n if not this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n return redirect(create_new_game)\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n return redirect(create_new_game)\n this_game.reset()\n this_game.deal_cards_to_players()\n return JsonResponse({'status': 'ok'})\n",
"step-4": "from django.shortcuts import render, redirect\nfrom .models import Game, Player, CardsInHand, Feedback\nfrom django.db.models import Q\nfrom .forms import GameForm, JoinForm, FeedbackForm\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.views.generic import CreateView\nimport json\n\n\ndef get_joined_players(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n return HttpResponse(str(game.joined_players))\n\n\ndef create_new_game(request):\n if request.method == 'POST':\n form_data = json.loads(request.body.decode('utf-8'))\n form = GameForm(form_data)\n if form.is_valid():\n number_of_players = form.cleaned_data['number_of_players']\n new_game = Game(number_of_players=int(number_of_players))\n new_game.instantiate()\n new_game.save()\n new_player = Player(name=form.cleaned_data['creator_name'],\n game_id=new_game)\n new_player.save()\n request.session['player_id'] = new_player.pk\n return JsonResponse({'code': new_game.code, 'game_id': new_game\n .pk, 'number_of_players': number_of_players})\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n else:\n if 'player_id' not in request.session:\n request.session['player_id'] = 0\n create_form = GameForm(initial={'number_of_players': '2'})\n join_form = JoinForm()\n feedback_form = FeedbackForm()\n return render(request, 'newhome.html', {'create_form': create_form,\n 'join_form': join_form, 'feedback_form': feedback_form})\n\n\ndef join_game(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = JoinForm(form_data)\n if form.is_valid():\n code = int(form.cleaned_data['code'])\n input_name = form.cleaned_data['name']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n game = get_object_or_404(Game, code=code)\n if game.joined_players < game.number_of_players:\n game.joined_players = game.joined_players + 1\n game.save()\n new_player = Player(name=input_name, game_id=game, player_number=\n game.joined_players)\n new_player.save()\n request.session['player_id'] = new_player.pk\n if new_player.player_number == game.number_of_players:\n game.deal_cards_to_players()\n return JsonResponse(game.pk, safe=False)\n\n\ndef game(request, game_id):\n err_str = ''\n this_game = get_object_or_404(Game, pk=game_id)\n print(request.session.keys())\n if this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n err_str = 'Unauthenticated user'\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n err_str = 'La partita richiesta non esiste o si è già conclusa.'\n if err_str != '':\n return render(request, 'error.html', {'error': err_str}, status=403)\n return render(request, 'gametest.html', {'game_id': this_game.pk,\n 'number_of_players': this_game.number_of_players})\n\n\ndef feedback_create(request):\n if request.method != 'POST':\n return HttpResponseRedirect('/game')\n form_data = json.loads(request.body.decode('utf-8'))\n form = FeedbackForm(form_data)\n if form.is_valid():\n sender_name = form.cleaned_data['sender_name']\n email = form.cleaned_data['email']\n message = form.cleaned_data['message']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n feedback = Feedback(sender_name=sender_name, email=email, message=message)\n feedback.save()\n return JsonResponse('[]', status=200, safe=False)\n\n\ndef restart_game(request, game_id):\n this_game = get_object_or_404(Game, pk=game_id)\n if not this_game.has_been_won:\n return redirect(create_new_game)\n players = Player.objects.filter(game_id=game_id)\n if 'player_id' not in request.session:\n return redirect(create_new_game)\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if this_player not in players:\n return redirect(create_new_game)\n this_game.reset()\n this_game.deal_cards_to_players()\n return JsonResponse({'status': 'ok'})\n",
"step-5": "from django.shortcuts import render, redirect\nfrom .models import Game, Player, CardsInHand, Feedback\nfrom django.db.models import Q\nfrom .forms import GameForm, JoinForm, FeedbackForm\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.views.generic import CreateView\nimport json\n# from django.contrib.auth.decorators import login_required\n\ndef get_joined_players(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n return HttpResponse(str(game.joined_players))\n\ndef create_new_game(request):\n if request.method == \"POST\":\n form_data = json.loads(request.body.decode('utf-8'))\n form = GameForm(form_data)\n\n if form.is_valid():\n number_of_players = form.cleaned_data[\"number_of_players\"]\n\n new_game = Game(number_of_players=int(number_of_players))\n new_game.instantiate() # initializes new game\n new_game.save() # save new game to db\n\n # create first player\n new_player = Player(name=form.cleaned_data[\"creator_name\"], game_id=new_game)\n new_player.save()\n\n # create new session to allow the user to play the game\n request.session['player_id'] = new_player.pk\n\n return JsonResponse({\n \"code\": new_game.code,\n \"game_id\": new_game.pk,\n \"number_of_players\": number_of_players,\n })\n # return render(request, \"game_created.html\", {\n # \"form\": form,\n # \"game_code\": new_game.code,\n # \"n_players\": number_of_players,\n # \"game_id\": new_game.pk,\n # \"your_name\": new_player.name,\n # })\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n else:\n # set a dummy player id in player's session. this is needed to make channels session persistence work (for matchmaking)\n if('player_id' not in request.session):\n request.session['player_id'] = 0\n\n create_form = GameForm(initial={'number_of_players': '2'})\n join_form = JoinForm()\n feedback_form = FeedbackForm()\n return render(\n request,\n \"newhome.html\",\n {\n \"create_form\": create_form,\n \"join_form\": join_form,\n \"feedback_form\": feedback_form,\n }\n )\n\ndef join_game(request):\n if request.method != \"POST\":\n return HttpResponseRedirect(\"/game\")\n\n form_data = json.loads(request.body.decode('utf-8'))\n form = JoinForm(form_data)\n if form.is_valid():\n code = int(form.cleaned_data['code'])\n input_name = form.cleaned_data['name']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n\n game = get_object_or_404(Game, code=code)\n if(game.joined_players < game.number_of_players):\n # increment the number of players who joined this game\n game.joined_players = game.joined_players + 1\n game.save()\n # create player and append it to this game\n new_player = Player(name=input_name, game_id=game, player_number=game.joined_players)\n new_player.save()\n\n # create new session to allow user to play\n request.session['player_id'] = new_player.pk\n\n if(new_player.player_number == game.number_of_players):\n # last player joined: deal cards to all players; game can now being\n game.deal_cards_to_players()\n\n return JsonResponse(game.pk, safe=False)\n\ndef game(request, game_id):\n err_str = ''\n this_game = get_object_or_404(Game, pk=game_id)\n print(request.session.keys())\n\n # if game is over, redirect to home\n if this_game.has_been_won:\n return redirect(create_new_game)\n\n # get players who joined this game\n players = Player.objects.filter(game_id=game_id)\n\n if('player_id' not in request.session): # check if user has a session variable player_id\n err_str = \"Unauthenticated user\"\n\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if(this_player not in players): # check if this player has joined the game\n err_str = \"La partita richiesta non esiste o si è già conclusa.\"\n\n if err_str != '':\n return render(\n request,\n 'error.html',\n {\n 'error': err_str,\n },\n status=403\n )\n\n return render(request, 'gametest.html', {\n 'game_id': this_game.pk,\n 'number_of_players': this_game.number_of_players,\n })\n\ndef feedback_create(request):\n if request.method != \"POST\":\n return HttpResponseRedirect(\"/game\")\n\n form_data = json.loads(request.body.decode('utf-8'))\n form = FeedbackForm(form_data)\n if form.is_valid():\n sender_name = form.cleaned_data['sender_name']\n email = form.cleaned_data['email']\n message = form.cleaned_data['message']\n else:\n return JsonResponse(form.errors.as_json(), safe=False, status=400)\n\n feedback = Feedback(sender_name=sender_name, email=email, message=message)\n feedback.save()\n return JsonResponse(\"[]\", status=200, safe=False)\n\ndef restart_game(request, game_id):\n this_game = get_object_or_404(Game, pk=game_id)\n\n # if game isn't over, redirect to home\n if not this_game.has_been_won:\n return redirect(create_new_game)\n\n # get players who joined this game\n players = Player.objects.filter(game_id=game_id)\n\n if('player_id' not in request.session): # check if user has a session variable player_id\n return redirect(create_new_game)\n\n this_player = get_object_or_404(Player, pk=request.session['player_id'])\n if(this_player not in players): # check if this player has joined the game\n return redirect(create_new_game)\n\n this_game.reset()\n this_game.deal_cards_to_players()\n\n return JsonResponse({'status': 'ok'})\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
import imp
from django.shortcuts import render
# ***************** API ****************
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser,FileUploadParser,MultiPartParser,FormParser
from .models import *
from django.http import Http404
from .serializers import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status,viewsets,permissions
from rest_framework import generics
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth import get_user_model
from client.models import ClientModel
from adminapp.models import SchoolModel
from adminapp.serializers import SchoolSerializer
from .custompermissions import *
from client.permissions import *
from rest_framework.authentication import SessionAuthentication
from Student.permissions import IsStudent
User = get_user_model()
def get_user_from_token(request):
token = request.user.auth_token #auth key(token) of current user 91391f4c12b94b753d08008150d2315d9d8d7e1e
print("token.user_id",token.user_id) #gives id of user (pk) 2
user = User.objects.get(id=token.user_id) #gives user name
return user
# Create your views here.
# class UserListView(generics.ListAPIView):
# parser_classes = (MultiPartParser,FormParser)
# queryset = UserModel.objects.all()
# serializer_class = UserSerializer
# class UserDetailView(generics.RetrieveAPIView):
# parser_classes = (MultiPartParser,FormParser)
# queryset = UserModel.objects.all()
# serializer_class = UserSerializer
class AddArticleView(generics.CreateAPIView):
#All authenticated users can add articles
permission_classes = (IsAuthenticated, )
serializer_class = ArticleSerializer
queryset = ArticleModel.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class ListArticleView(generics.ListAPIView):
#Anyone can see the published Articles
permission_classes = (AllowAny, )
serializer_class = ArticleSerializer
queryset = ArticleModel.objects.filter(status__exact="P")
class ArticleDetail(generics.RetrieveAPIView):
#anyone can see detail of published article
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = ArticleSerializer
queryset = ArticleModel.objects.filter(status__exact="P")
class ArticleDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):
'''
Get: superadmin can see all articles (draft, published)
PATCH : superadmin can mark article as published by changing status = P
Delete: superadmin can delete article.
'''
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = UpdateArticleSerializer
queryset = ArticleModel.objects.all()
class AddQuestions(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = QuestionSerializer
queryset = QuestionModel.objects.all()
class ViewQuestion(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = QuestionSerializer
queryset = QuestionModel.objects.all()
class QuestionDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = QuestionSerializer
queryset = QuestionModel.objects.all()
class QuestionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = QuestionSerializer
queryset = QuestionModel.objects.all()
class AddSchools(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = SchoolSerializer
queryset = SchoolModel.objects.all()
class ViewSchool(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = SchoolSerializer
queryset = SchoolModel.objects.all()
class SchoolDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = SchoolSerializer
queryset = SchoolModel.objects.all()
class SchoolDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = SchoolSerializer
queryset = SchoolModel.objects.all()
class AddBlogs(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = BlogSerializer
queryset = BlogModel.objects.all()
class ViewBlog(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = BlogSerializer
queryset = BlogModel.objects.all()
class BlogDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = BlogSerializer
queryset = BlogModel.objects.all()
class BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = BlogSerializer
queryset = BlogModel.objects.all()
class AddEventView(generics.CreateAPIView):
#only super user can add events
permission_classes = (IsSuperUser, )
serializer_class = EventSerializer
queryset = EventModel.objects.all()
class ListEventView(generics.ListAPIView):
#Anyone can see the events
permission_classes = (AllowAny, )
serializer_class = EventSerializer
queryset = EventModel.objects.all()
class EventDetailView(generics.RetrieveAPIView):
#Anyone can see the detail of events
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = EventSerializer
queryset = EventModel.objects.all()
class EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
#only superadmin can delete and update events
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = EventSerializer
queryset = EventModel.objects.all()
class AddBusinessPartners(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = BusinessPartnersSerializer
queryset = BusinessPartnersModel.objects.all()
class ViewBusinessPartner(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = BusinessPartnersSerializer
queryset = BusinessPartnersModel.objects.all()
class BusinessPartnerDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = BusinessPartnersSerializer
queryset = BusinessPartnersModel.objects.all()
class BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = BusinessPartnersSerializer
queryset = BusinessPartnersModel.objects.all()
class AddKidStory(generics.CreateAPIView):
#Students can add kidstory
permission_classes = (IsStudent, )
serializer_class = KidStorySerializer
queryset = KidStoryModel.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class ViewKidStory(generics.ListAPIView):
# anyone can see published kids story
permission_classes = (AllowAny, )
serializer_class = KidStorySerializer
queryset = KidStoryModel.objects.filter(status__exact="P")
class KidStoryDetailView(generics.RetrieveAPIView):
#anyone can see detail of published kids story
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = KidStorySerializer
queryset = KidStoryModel.objects.filter(status__exact="P")
class KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
'''
Get: superadmin can see all stories (draft, published)
PATCH : superadmin can mark stories as published by changing status = P
Delete: superadmin can delete stories.
'''
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = UpdateKidsStorySerializer
queryset = KidStoryModel.objects.all()
class AddKidTalent(generics.CreateAPIView):
#Students or client can add KidsTalent
permission_classes = (IsStudentORClient, )
serializer_class = KidTalentSerializer
queryset = KidTalentModel.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class ViewKidTalent(generics.ListAPIView):
# anyone can see published kids talent
permission_classes = (AllowAny, )
serializer_class = KidTalentSerializer
queryset = KidTalentModel.objects.filter(status__exact="P")
class KidTalentDetailView(generics.RetrieveAPIView):
#anyone can see detail of published kids talent
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = KidTalentSerializer
queryset = KidTalentModel.objects.filter(status__exact="P")
class KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
'''
Get: superadmin can see all kids talent (draft, published)
PATCH : superadmin can mark kids talent as published by changing status = P
Delete: superadmin can delete kids talent.
'''
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = UpdateKidsTalentSerializer
queryset = KidTalentModel.objects.all()
class AddCourses(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = CourseSerializer
queryset = CourseModel.objects.all()
class ViewCourse(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = CourseSerializer
queryset = CourseModel.objects.all()
class CourseDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = CourseSerializer
queryset = CourseModel.objects.all()
class CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = CourseSerializer
queryset = CourseModel.objects.all()
class AddQuizContext(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = QuizContextSerializer
queryset = QuizContextModel.objects.all()
class ViewQuizContext(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = QuizContextSerializer
queryset = QuizContextModel.objects.all()
class QuizContextDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = QuizContextSerializer
queryset = QuizContextModel.objects.all()
class QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = QuizContextSerializer
queryset = QuizContextModel.objects.all()
class AddFeedback(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = ClientFeedbackSerializer
queryset = ClientFeedBackModel.objects.all()
class ViewFeedback(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = ClientFeedbackSerializer
queryset = ClientFeedBackModel.objects.all()
class FeedbackDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = ClientFeedbackSerializer
queryset = ClientFeedBackModel.objects.all()
class FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = ClientFeedbackSerializer
queryset = ClientFeedBackModel.objects.all()
class AddWebsiteAd(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = WebsiteAdSerializer
queryset = WebsiteAdModel.objects.all()
class ViewWebsiteAd(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = WebsiteAdSerializer
queryset = WebsiteAdModel.objects.all()
class WebsiteAdDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = WebsiteAdSerializer
queryset = WebsiteAdModel.objects.all()
class WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = WebsiteAdSerializer
queryset = WebsiteAdModel.objects.all()
# class AddApproval(generics.CreateAPIView):
# permission_classes = (IsSuperUser, )
# serializer_class = ApprovalSerializer
# queryset = ApprovalModel.objects.all()
# class ViewApproval(generics.ListAPIView):
# permission_classes = (IsClient, )
# serializer_class = ApprovalSerializer
# queryset = ApprovalModel.objects.all()
# class ApprovalDetailView(generics.RetrieveAPIView):
# lookup_field = 'slug'
# permission_classes = (IsClient, )
# serializer_class = ApprovalSerializer
# queryset = ApprovalModel.objects.all()
# class ApprovalDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
# lookup_field = 'slug'
# permission_classes = (IsSuperUser, )
# serializer_class = ApprovalSerializer
# queryset = ApprovalModel.objects.all()
class AddBusinessPromotion(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = BusinessPromotionSerializer
queryset = BusinessPromotionModel.objects.all()
class ViewBusinessPromotion(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = BusinessPromotionSerializer
queryset = BusinessPromotionModel.objects.all()
class BusinessPromotionDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = BusinessPromotionSerializer
queryset = BusinessPromotionModel.objects.all()
class BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = BusinessPromotionSerializer
queryset = BusinessPromotionModel.objects.all()
class AddTeam(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = TeamSerializer
queryset = TeamModel.objects.all()
class ViewTeam(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = TeamSerializer
queryset = TeamModel.objects.all()
class TeamDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = TeamSerializer
queryset = TeamModel.objects.all()
class TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = TeamSerializer
queryset = TeamModel.objects.all()
class AddAdvisoryBoard(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = AdvisoryBoardSerializer
queryset = AdvisoryBoardModel.objects.all()
class ViewAdvisoryBoard(generics.ListAPIView):
permission_classes = (IsSuperUser, )
serializer_class = AdvisoryBoardSerializer
queryset = AdvisoryBoardModel.objects.all()
class AdvisoryBoardDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = AdvisoryBoardSerializer
queryset = AdvisoryBoardModel.objects.all()
class AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = AdvisoryBoardSerializer
queryset = AdvisoryBoardModel.objects.all()
class AddAnnouncement(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = AnnouncementSerializer
queryset = AnnouncementModel.objects.all()
class ListAnnouncement(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = AnnouncementSerializer
queryset = AnnouncementModel.objects.all()
class AnnouncementDetail(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = AnnouncementSerializer
queryset = AnnouncementModel.objects.all()
class AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = AnnouncementSerializer
queryset = AnnouncementModel.objects.all()
class SuperadminProfileView(APIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
user = get_user_from_token(request)
data = {
'name': user.username,
'email': user.email
}
return Response(data)
class AddJobClassified(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = JobClassifiedSerializer
queryset = JobClassifiedModel.objects.all()
class ViewJobClassified(generics.ListAPIView):
permission_classes = (AllowAny, )
serializer_class = JobClassifiedSerializer
queryset = JobClassifiedModel.objects.all()
class JobClassifiedDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (AllowAny, )
serializer_class = JobClassifiedSerializer
queryset = JobClassifiedModel.objects.all()
class JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = JobClassifiedSerializer
queryset = JobClassifiedModel.objects.all()
class AddCustomerReviews(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
serializer_class = CustomerReviewSerializer
queryset = CustomerReviewModel.objects.all()
class ViewCustomerReview(generics.ListAPIView):
permission_classes = (IsClient, )
serializer_class = CustomerReviewSerializer
queryset = CustomerReviewModel.objects.all()
class CustomerReviewDetailView(generics.RetrieveAPIView):
lookup_field = 'slug'
permission_classes = (IsClient, )
serializer_class = CustomerReviewSerializer
queryset = CustomerReviewModel.objects.all()
class CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'slug'
permission_classes = (IsSuperUser, )
serializer_class = CustomerReviewSerializer
queryset = CustomerReviewModel.objects.all()
class ClientComplain(APIView):
permission_classes = (IsSuperUser, )
serializer = ViewComplainSerializer(many=True)
class clientfeedback(APIView):
permission_classes = (IsSuperUser, )
def get(self, request, format=None):
feeds = ClientFeedBackModel.objects.filter(
Class__admin = self.request.user
)
serializer = ClientFeedbackSerializer(feeds, many=True)
return Response(serializer.data)
class Enroll_Course(APIView):
permission_classes = (IsSuperUser, )
def post(self, request, format=None):
serializer = EnrollCourseSerializer(data=request.data)
print(serializer)
if serializer.is_valid():
course = serializer.validated_data.get('course', '')
serializer.save()
return Response(serializer.data,status =status.HTTP_201_CREATED)
else:
return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)
class ViewEnroll_Course(APIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
course = self.kwargs['course_id']
client = self.kwargs['client_id']
data = Enroll_CourseModel.objects.filter(
course = course, client = client
)
serializer = ViewEnrollCourseSerializer(data, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class DetailEnroll_CourseView(APIView):
permission_classes = (IsSuperUser, )
def get_object(self,pk):
try:
return Enroll_CourseModel.objects.get(id=pk)
except:
raise Http404
def get(self, request, pk, format=None):
data = self.get_object(pk)
serializer = ViewEnrollCourseSerializer(data)
return Response(serializer.data)
def put(self,request,pk,format=None):
data = self.get_object(pk)
serializer = ViewEnrollCourseSerializer(data,data = request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,pk,format=None):
data = self.get_object(pk)
data.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
class CourseDetail(APIView):
permission_classes = (IsSuperUser, )
def get_object(self, slug):
try:
return CourseModel.objects.get(slug=slug)
except CourseModel.DoesNotExist:
raise Http404
def get(self, request, slug, format=None):
data = self.get_object(slug)
if data.classes.school.admin == self.request.user:
serializer = ViewCourseSerializer(data)
return Response(serializer.data)
else:
return Response(
{'message':'This course does not belong to your school'},
status=status.HTTP_400_BAD_REQUEST
)
def put(self,request,slug,format=None):
data = self.get_object(slug)
if data.course.client.admin == self.request.user:
serializer = CourseSerializer(data,data = request.data)
if serializer.is_valid(raise_exception=True):
course = serializer.validated_data.get('course', '')
if course.client.admin == self.request.user:
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(
{'message':'This Class does not belong to you'},
status=status.HTTP_400_BAD_REQUEST
)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(
{'message':'This course does not belong to you'},
status=status.HTTP_400_BAD_REQUEST
)
def delete(self,request,slug,format=None):
data = self.get_object(slug)
if data.course.client.admin == self.request.user:
data.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
else:
return Response(
{'message':'This course does not belong to you'},
status=status.HTTP_400_BAD_REQUEST
)
class SchoolRegistrationView(RegisterView):
serializer_class = RegisterSchoolSerializer
permission_classes = (IsSuperUser,)
class Add_question(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
def post(self,request,format=None):
serializer = QuestionSerializer(data=request.data)
print(serializer)
if serializer.is_valid():
course = serializer.validated_data.get('course', '')
serializer.save()
return Response(serializer.data,status =status.HTTP_201_CREATED)
else:
return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)
class Viewquestion(generics.ListAPIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
course = self.kwargs['course_id']
data = QuestionModel.objects.filter(
course_id = course)
serializer = QuestionSerializer(data, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class QuestionDetail(APIView):
permission_classes = (IsSuperUser, )
def get_object(self,pk):
try:
return QuestionModel.objects.get(id=pk)
except:
raise Http404
def get(self,request,pk,format=None):
data = self.get_object(pk)
serializer = QuestionSerializer(data)
return Response(serializer.data)
def put(self,request,pk,format=None):
data = self.get_object(pk)
serializer = QuestionSerializer(data,data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,pk,format=None):
data = self.get_object(pk)
data.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
class SubmittedQuestionView(APIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
admin = self.request.user
course = self.kwargs['course_id']
client = self.kwargs['client_id']
data = Client_SubmitquestionModel.objects.filter(
course__course = course,
client__client = client
)
serializer = Client_submittedquestionSerializer(data, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class AddonlineTest(generics.CreateAPIView):
permission_classes = (IsSuperUser, )
def post(self, request, format=None):
serializer = testSerializer(data=request.data)
print(serializer)
if serializer.is_valid():
course = serializer.validated_data.get('course', '')
serializer.save()
return Response(serializer.data,status =status.HTTP_201_CREATED)
else:
return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)
class ViewOnlinetest(generics.ListAPIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
course = self.kwargs['course_id']
data = Client_testModel.objects.filter(
course_id = course)
serializer = testSerializer(data, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class onlinetestDetail(APIView):
permission_classes = (IsSuperUser, )
def get_object(self,pk):
try:
return Client_testModel.objects.get(id=pk)
except:
raise Http404
def get(self,request,pk,format=None):
data = self.get_object(pk)
serializer = testSerializer(data)
return Response(serializer.data)
def put(self,request,pk,format=None):
data = self.get_object(pk)
serializer = testSerializer(data,data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,pk,format=None):
data = self.get_object(pk)
data.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
class SubmittedonlineTestView(APIView):
permission_classes = (IsSuperUser, )
def get(self, request, *args, **kwargs):
admin = self.request.user
course = self.kwargs['course_id']
client = self.kwargs['client_id']
data = Client_SubmittestModel.objects.filter(
course__course = course,
client__client = client
)
serializer = Client_submittedtestSerializer(data, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
|
normal
|
{
"blob_id": "aec5280869a780bbd93ef24b659d9959f7b81426",
"index": 3545,
"step-1": "<mask token>\n\n\nclass AddBlogs(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass ViewBlog(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass AddEventView(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass ListEventView(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass AddBusinessPartners(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass ViewBusinessPartner(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass AddKidStory(generics.CreateAPIView):\n permission_classes = IsStudent,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidStory(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all stories (draft, published)\n PATCH : superadmin can mark stories as published by changing status = P\n Delete: superadmin can delete stories.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsStorySerializer\n queryset = KidStoryModel.objects.all()\n\n\nclass AddKidTalent(generics.CreateAPIView):\n permission_classes = IsStudentORClient,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidTalent(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all kids talent (draft, published)\n PATCH : superadmin can mark kids talent as published by changing status = P\n Delete: superadmin can delete kids talent.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n\nclass AddCourses(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass ViewCourse(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass AddQuizContext(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass ViewQuizContext(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass AddFeedback(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass ViewFeedback(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass AddWebsiteAd(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass ViewWebsiteAd(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass AddBusinessPromotion(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass ViewBusinessPromotion(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass AddTeam(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass ViewTeam(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass AddAdvisoryBoard(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass ViewAdvisoryBoard(generics.ListAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AddAnnouncement(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass ListAnnouncement(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass SuperadminProfileView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n user = get_user_from_token(request)\n data = {'name': user.username, 'email': user.email}\n return Response(data)\n\n\nclass AddJobClassified(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass ViewJobClassified(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass AddCustomerReviews(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ViewCustomerReview(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ClientComplain(APIView):\n permission_classes = IsSuperUser,\n serializer = ViewComplainSerializer(many=True)\n\n\nclass clientfeedback(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, format=None):\n feeds = ClientFeedBackModel.objects.filter(Class__admin=self.\n request.user)\n serializer = ClientFeedbackSerializer(feeds, many=True)\n return Response(serializer.data)\n\n\nclass Enroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = EnrollCourseSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewEnroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Enroll_CourseModel.objects.filter(course=course, client=client)\n serializer = ViewEnrollCourseSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DetailEnroll_CourseView(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Enroll_CourseModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass CourseDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, slug):\n try:\n return CourseModel.objects.get(slug=slug)\n except CourseModel.DoesNotExist:\n raise Http404\n\n def get(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.classes.school.admin == self.request.user:\n serializer = ViewCourseSerializer(data)\n return Response(serializer.data)\n else:\n return Response({'message':\n 'This course does not belong to your school'}, status=\n status.HTTP_400_BAD_REQUEST)\n\n def put(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n serializer = CourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n course = serializer.validated_data.get('course', '')\n if course.client.admin == self.request.user:\n serializer.save()\n return Response(serializer.data, status=status.\n HTTP_201_CREATED)\n return Response({'message':\n 'This Class does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass SchoolRegistrationView(RegisterView):\n serializer_class = RegisterSchoolSerializer\n permission_classes = IsSuperUser,\n\n\nclass Add_question(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = QuestionSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass Viewquestion(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = QuestionModel.objects.filter(course_id=course)\n serializer = QuestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass QuestionDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return QuestionModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedQuestionView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmitquestionModel.objects.filter(course__course=\n course, client__client=client)\n serializer = Client_submittedquestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass AddonlineTest(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = testSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewOnlinetest(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = Client_testModel.objects.filter(course_id=course)\n serializer = testSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass onlinetestDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Client_testModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedonlineTestView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmittestModel.objects.filter(course__course=course,\n client__client=client)\n serializer = Client_submittedtestSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n",
"step-2": "<mask token>\n\n\nclass SchoolDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass AddBlogs(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass ViewBlog(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass AddEventView(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass ListEventView(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass AddBusinessPartners(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass ViewBusinessPartner(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass AddKidStory(generics.CreateAPIView):\n permission_classes = IsStudent,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidStory(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all stories (draft, published)\n PATCH : superadmin can mark stories as published by changing status = P\n Delete: superadmin can delete stories.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsStorySerializer\n queryset = KidStoryModel.objects.all()\n\n\nclass AddKidTalent(generics.CreateAPIView):\n permission_classes = IsStudentORClient,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidTalent(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all kids talent (draft, published)\n PATCH : superadmin can mark kids talent as published by changing status = P\n Delete: superadmin can delete kids talent.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n\nclass AddCourses(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass ViewCourse(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass AddQuizContext(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass ViewQuizContext(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass AddFeedback(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass ViewFeedback(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass AddWebsiteAd(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass ViewWebsiteAd(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass AddBusinessPromotion(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass ViewBusinessPromotion(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass AddTeam(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass ViewTeam(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass AddAdvisoryBoard(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass ViewAdvisoryBoard(generics.ListAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AddAnnouncement(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass ListAnnouncement(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass SuperadminProfileView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n user = get_user_from_token(request)\n data = {'name': user.username, 'email': user.email}\n return Response(data)\n\n\nclass AddJobClassified(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass ViewJobClassified(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass AddCustomerReviews(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ViewCustomerReview(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ClientComplain(APIView):\n permission_classes = IsSuperUser,\n serializer = ViewComplainSerializer(many=True)\n\n\nclass clientfeedback(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, format=None):\n feeds = ClientFeedBackModel.objects.filter(Class__admin=self.\n request.user)\n serializer = ClientFeedbackSerializer(feeds, many=True)\n return Response(serializer.data)\n\n\nclass Enroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = EnrollCourseSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewEnroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Enroll_CourseModel.objects.filter(course=course, client=client)\n serializer = ViewEnrollCourseSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DetailEnroll_CourseView(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Enroll_CourseModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass CourseDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, slug):\n try:\n return CourseModel.objects.get(slug=slug)\n except CourseModel.DoesNotExist:\n raise Http404\n\n def get(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.classes.school.admin == self.request.user:\n serializer = ViewCourseSerializer(data)\n return Response(serializer.data)\n else:\n return Response({'message':\n 'This course does not belong to your school'}, status=\n status.HTTP_400_BAD_REQUEST)\n\n def put(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n serializer = CourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n course = serializer.validated_data.get('course', '')\n if course.client.admin == self.request.user:\n serializer.save()\n return Response(serializer.data, status=status.\n HTTP_201_CREATED)\n return Response({'message':\n 'This Class does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass SchoolRegistrationView(RegisterView):\n serializer_class = RegisterSchoolSerializer\n permission_classes = IsSuperUser,\n\n\nclass Add_question(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = QuestionSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass Viewquestion(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = QuestionModel.objects.filter(course_id=course)\n serializer = QuestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass QuestionDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return QuestionModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedQuestionView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmitquestionModel.objects.filter(course__course=\n course, client__client=client)\n serializer = Client_submittedquestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass AddonlineTest(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = testSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewOnlinetest(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = Client_testModel.objects.filter(course_id=course)\n serializer = testSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass onlinetestDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Client_testModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedonlineTestView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmittestModel.objects.filter(course__course=course,\n client__client=client)\n serializer = Client_submittedtestSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n",
"step-3": "<mask token>\n\n\nclass AddSchools(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass ViewSchool(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass AddBlogs(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass ViewBlog(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass AddEventView(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass ListEventView(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass AddBusinessPartners(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass ViewBusinessPartner(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass AddKidStory(generics.CreateAPIView):\n permission_classes = IsStudent,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidStory(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all stories (draft, published)\n PATCH : superadmin can mark stories as published by changing status = P\n Delete: superadmin can delete stories.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsStorySerializer\n queryset = KidStoryModel.objects.all()\n\n\nclass AddKidTalent(generics.CreateAPIView):\n permission_classes = IsStudentORClient,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidTalent(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all kids talent (draft, published)\n PATCH : superadmin can mark kids talent as published by changing status = P\n Delete: superadmin can delete kids talent.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n\nclass AddCourses(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass ViewCourse(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass AddQuizContext(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass ViewQuizContext(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass AddFeedback(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass ViewFeedback(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass AddWebsiteAd(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass ViewWebsiteAd(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass AddBusinessPromotion(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass ViewBusinessPromotion(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass AddTeam(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass ViewTeam(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass AddAdvisoryBoard(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass ViewAdvisoryBoard(generics.ListAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AddAnnouncement(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass ListAnnouncement(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass SuperadminProfileView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n user = get_user_from_token(request)\n data = {'name': user.username, 'email': user.email}\n return Response(data)\n\n\nclass AddJobClassified(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass ViewJobClassified(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass AddCustomerReviews(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ViewCustomerReview(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ClientComplain(APIView):\n permission_classes = IsSuperUser,\n serializer = ViewComplainSerializer(many=True)\n\n\nclass clientfeedback(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, format=None):\n feeds = ClientFeedBackModel.objects.filter(Class__admin=self.\n request.user)\n serializer = ClientFeedbackSerializer(feeds, many=True)\n return Response(serializer.data)\n\n\nclass Enroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = EnrollCourseSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewEnroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Enroll_CourseModel.objects.filter(course=course, client=client)\n serializer = ViewEnrollCourseSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DetailEnroll_CourseView(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Enroll_CourseModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass CourseDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, slug):\n try:\n return CourseModel.objects.get(slug=slug)\n except CourseModel.DoesNotExist:\n raise Http404\n\n def get(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.classes.school.admin == self.request.user:\n serializer = ViewCourseSerializer(data)\n return Response(serializer.data)\n else:\n return Response({'message':\n 'This course does not belong to your school'}, status=\n status.HTTP_400_BAD_REQUEST)\n\n def put(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n serializer = CourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n course = serializer.validated_data.get('course', '')\n if course.client.admin == self.request.user:\n serializer.save()\n return Response(serializer.data, status=status.\n HTTP_201_CREATED)\n return Response({'message':\n 'This Class does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass SchoolRegistrationView(RegisterView):\n serializer_class = RegisterSchoolSerializer\n permission_classes = IsSuperUser,\n\n\nclass Add_question(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = QuestionSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass Viewquestion(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = QuestionModel.objects.filter(course_id=course)\n serializer = QuestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass QuestionDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return QuestionModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedQuestionView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmitquestionModel.objects.filter(course__course=\n course, client__client=client)\n serializer = Client_submittedquestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass AddonlineTest(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = testSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewOnlinetest(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = Client_testModel.objects.filter(course_id=course)\n serializer = testSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass onlinetestDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Client_testModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedonlineTestView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmittestModel.objects.filter(course__course=course,\n client__client=client)\n serializer = Client_submittedtestSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n",
"step-4": "<mask token>\n\n\nclass AddArticleView(generics.CreateAPIView):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass ListArticleView(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = ArticleSerializer\n queryset = ArticleModel.objects.filter(status__exact='P')\n\n\nclass ArticleDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = ArticleSerializer\n queryset = ArticleModel.objects.filter(status__exact='P')\n\n\nclass ArticleDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all articles (draft, published)\n PATCH : superadmin can mark article as published by changing status = P\n Delete: superadmin can delete article.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateArticleSerializer\n queryset = ArticleModel.objects.all()\n\n\nclass AddQuestions(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass ViewQuestion(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass QuestionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass QuestionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass AddSchools(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass ViewSchool(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass AddBlogs(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass ViewBlog(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass AddEventView(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass ListEventView(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass AddBusinessPartners(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass ViewBusinessPartner(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass AddKidStory(generics.CreateAPIView):\n permission_classes = IsStudent,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidStory(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact='P')\n\n\nclass KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all stories (draft, published)\n PATCH : superadmin can mark stories as published by changing status = P\n Delete: superadmin can delete stories.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsStorySerializer\n queryset = KidStoryModel.objects.all()\n\n\nclass AddKidTalent(generics.CreateAPIView):\n permission_classes = IsStudentORClient,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ViewKidTalent(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact='P')\n\n\nclass KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Get: superadmin can see all kids talent (draft, published)\n PATCH : superadmin can mark kids talent as published by changing status = P\n Delete: superadmin can delete kids talent.\n \"\"\"\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = UpdateKidsTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n\nclass AddCourses(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass ViewCourse(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass AddQuizContext(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass ViewQuizContext(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass AddFeedback(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass ViewFeedback(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass AddWebsiteAd(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass ViewWebsiteAd(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass AddBusinessPromotion(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass ViewBusinessPromotion(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass AddTeam(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass ViewTeam(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass AddAdvisoryBoard(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass ViewAdvisoryBoard(generics.ListAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AddAnnouncement(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass ListAnnouncement(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass SuperadminProfileView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n user = get_user_from_token(request)\n data = {'name': user.username, 'email': user.email}\n return Response(data)\n\n\nclass AddJobClassified(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass ViewJobClassified(generics.ListAPIView):\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = AllowAny,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass AddCustomerReviews(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ViewCustomerReview(generics.ListAPIView):\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = IsClient,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = IsSuperUser,\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass ClientComplain(APIView):\n permission_classes = IsSuperUser,\n serializer = ViewComplainSerializer(many=True)\n\n\nclass clientfeedback(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, format=None):\n feeds = ClientFeedBackModel.objects.filter(Class__admin=self.\n request.user)\n serializer = ClientFeedbackSerializer(feeds, many=True)\n return Response(serializer.data)\n\n\nclass Enroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = EnrollCourseSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewEnroll_Course(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Enroll_CourseModel.objects.filter(course=course, client=client)\n serializer = ViewEnrollCourseSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DetailEnroll_CourseView(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Enroll_CourseModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass CourseDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, slug):\n try:\n return CourseModel.objects.get(slug=slug)\n except CourseModel.DoesNotExist:\n raise Http404\n\n def get(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.classes.school.admin == self.request.user:\n serializer = ViewCourseSerializer(data)\n return Response(serializer.data)\n else:\n return Response({'message':\n 'This course does not belong to your school'}, status=\n status.HTTP_400_BAD_REQUEST)\n\n def put(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n serializer = CourseSerializer(data, data=request.data)\n if serializer.is_valid(raise_exception=True):\n course = serializer.validated_data.get('course', '')\n if course.client.admin == self.request.user:\n serializer.save()\n return Response(serializer.data, status=status.\n HTTP_201_CREATED)\n return Response({'message':\n 'This Class does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({'message':\n 'This course does not belong to you'}, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass SchoolRegistrationView(RegisterView):\n serializer_class = RegisterSchoolSerializer\n permission_classes = IsSuperUser,\n\n\nclass Add_question(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = QuestionSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass Viewquestion(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = QuestionModel.objects.filter(course_id=course)\n serializer = QuestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass QuestionDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return QuestionModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedQuestionView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmitquestionModel.objects.filter(course__course=\n course, client__client=client)\n serializer = Client_submittedquestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass AddonlineTest(generics.CreateAPIView):\n permission_classes = IsSuperUser,\n\n def post(self, request, format=None):\n serializer = testSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n\nclass ViewOnlinetest(generics.ListAPIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = Client_testModel.objects.filter(course_id=course)\n serializer = testSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass onlinetestDetail(APIView):\n permission_classes = IsSuperUser,\n\n def get_object(self, pk):\n try:\n return Client_testModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.\n HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SubmittedonlineTestView(APIView):\n permission_classes = IsSuperUser,\n\n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmittestModel.objects.filter(course__course=course,\n client__client=client)\n serializer = Client_submittedtestSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n",
"step-5": "import imp\nfrom django.shortcuts import render\n\n# ***************** API ****************\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser,FileUploadParser,MultiPartParser,FormParser\nfrom .models import *\nfrom django.http import Http404\nfrom .serializers import *\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status,viewsets,permissions\nfrom rest_framework import generics\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom django.contrib.auth import get_user_model\nfrom client.models import ClientModel\nfrom adminapp.models import SchoolModel\nfrom adminapp.serializers import SchoolSerializer\n\nfrom .custompermissions import *\nfrom client.permissions import *\nfrom rest_framework.authentication import SessionAuthentication\nfrom Student.permissions import IsStudent\n\nUser = get_user_model()\n\ndef get_user_from_token(request):\n\ttoken = request.user.auth_token #auth key(token) of current user 91391f4c12b94b753d08008150d2315d9d8d7e1e\n\tprint(\"token.user_id\",token.user_id) #gives id of user (pk) 2\n\tuser = User.objects.get(id=token.user_id) #gives user name\n\treturn user\n\n# Create your views here.\n\n# class UserListView(generics.ListAPIView):\n# parser_classes = (MultiPartParser,FormParser)\n# queryset = UserModel.objects.all()\n# serializer_class = UserSerializer\n\n# class UserDetailView(generics.RetrieveAPIView):\n# parser_classes = (MultiPartParser,FormParser)\n# queryset = UserModel.objects.all()\n# serializer_class = UserSerializer\n\nclass AddArticleView(generics.CreateAPIView):\n #All authenticated users can add articles\n permission_classes = (IsAuthenticated, )\n serializer_class = ArticleSerializer\n queryset = ArticleModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ListArticleView(generics.ListAPIView):\n #Anyone can see the published Articles\n permission_classes = (AllowAny, )\n serializer_class = ArticleSerializer\n queryset = ArticleModel.objects.filter(status__exact=\"P\")\n\n\nclass ArticleDetail(generics.RetrieveAPIView):\n #anyone can see detail of published article\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = ArticleSerializer\n queryset = ArticleModel.objects.filter(status__exact=\"P\")\n\n\nclass ArticleDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n '''\n Get: superadmin can see all articles (draft, published)\n PATCH : superadmin can mark article as published by changing status = P\n Delete: superadmin can delete article.\n '''\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = UpdateArticleSerializer\n queryset = ArticleModel.objects.all()\n\n\nclass AddQuestions(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\nclass ViewQuestion(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass QuestionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\nclass QuestionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = QuestionSerializer\n queryset = QuestionModel.objects.all()\n\n\nclass AddSchools(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\nclass ViewSchool(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass SchoolDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\nclass SchoolDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = SchoolSerializer\n queryset = SchoolModel.objects.all()\n\n\nclass AddBlogs(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\nclass ViewBlog(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass BlogDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\nclass BlogDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = BlogSerializer\n queryset = BlogModel.objects.all()\n\n\nclass AddEventView(generics.CreateAPIView):\n #only super user can add events\n permission_classes = (IsSuperUser, )\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass ListEventView(generics.ListAPIView):\n #Anyone can see the events\n permission_classes = (AllowAny, )\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\n\nclass EventDetailView(generics.RetrieveAPIView):\n #Anyone can see the detail of events\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\nclass EventDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n #only superadmin can delete and update events\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = EventSerializer\n queryset = EventModel.objects.all()\n\nclass AddBusinessPartners(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\nclass ViewBusinessPartner(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\n\nclass BusinessPartnerDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\nclass BusinessPartnerDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = BusinessPartnersSerializer\n queryset = BusinessPartnersModel.objects.all()\n\nclass AddKidStory(generics.CreateAPIView):\n #Students can add kidstory\n permission_classes = (IsStudent, )\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\nclass ViewKidStory(generics.ListAPIView):\n # anyone can see published kids story\n permission_classes = (AllowAny, )\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact=\"P\")\n\n\nclass KidStoryDetailView(generics.RetrieveAPIView):\n #anyone can see detail of published kids story\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = KidStorySerializer\n queryset = KidStoryModel.objects.filter(status__exact=\"P\")\n\nclass KidStoryDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n '''\n Get: superadmin can see all stories (draft, published)\n PATCH : superadmin can mark stories as published by changing status = P\n Delete: superadmin can delete stories.\n '''\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = UpdateKidsStorySerializer\n queryset = KidStoryModel.objects.all()\n\n\nclass AddKidTalent(generics.CreateAPIView):\n #Students or client can add KidsTalent\n permission_classes = (IsStudentORClient, )\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\nclass ViewKidTalent(generics.ListAPIView):\n # anyone can see published kids talent\n permission_classes = (AllowAny, )\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact=\"P\")\n\n\nclass KidTalentDetailView(generics.RetrieveAPIView):\n #anyone can see detail of published kids talent\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = KidTalentSerializer\n queryset = KidTalentModel.objects.filter(status__exact=\"P\")\n\nclass KidTalentDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n '''\n Get: superadmin can see all kids talent (draft, published)\n PATCH : superadmin can mark kids talent as published by changing status = P\n Delete: superadmin can delete kids talent.\n '''\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = UpdateKidsTalentSerializer\n queryset = KidTalentModel.objects.all()\n\n\nclass AddCourses(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\nclass ViewCourse(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass CourseDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\nclass CourseDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = CourseSerializer\n queryset = CourseModel.objects.all()\n\n\nclass AddQuizContext(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\nclass ViewQuizContext(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass QuizContextDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\nclass QuizContextDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = QuizContextSerializer\n queryset = QuizContextModel.objects.all()\n\n\nclass AddFeedback(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\nclass ViewFeedback(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass FeedbackDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\nclass FeedbackDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = ClientFeedbackSerializer\n queryset = ClientFeedBackModel.objects.all()\n\n\nclass AddWebsiteAd(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\nclass ViewWebsiteAd(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\nclass WebsiteAdDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\nclass WebsiteAdDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = WebsiteAdSerializer\n queryset = WebsiteAdModel.objects.all()\n\n\n\n\n\n# class AddApproval(generics.CreateAPIView):\n# permission_classes = (IsSuperUser, )\n# serializer_class = ApprovalSerializer\n# queryset = ApprovalModel.objects.all()\n\n# class ViewApproval(generics.ListAPIView):\n# permission_classes = (IsClient, )\n# serializer_class = ApprovalSerializer\n# queryset = ApprovalModel.objects.all()\n\n\n# class ApprovalDetailView(generics.RetrieveAPIView):\n# lookup_field = 'slug'\n# permission_classes = (IsClient, )\n# serializer_class = ApprovalSerializer\n# queryset = ApprovalModel.objects.all()\n\n# class ApprovalDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n# lookup_field = 'slug'\n# permission_classes = (IsSuperUser, )\n# serializer_class = ApprovalSerializer\n# queryset = ApprovalModel.objects.all()\n\n\nclass AddBusinessPromotion(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\nclass ViewBusinessPromotion(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass BusinessPromotionDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\nclass BusinessPromotionDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = BusinessPromotionSerializer\n queryset = BusinessPromotionModel.objects.all()\n\n\nclass AddTeam(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\nclass ViewTeam(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass TeamDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\nclass TeamDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = TeamSerializer\n queryset = TeamModel.objects.all()\n\n\nclass AddAdvisoryBoard(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\nclass ViewAdvisoryBoard(generics.ListAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\nclass AdvisoryBoardDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\nclass AdvisoryBoardDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = AdvisoryBoardSerializer\n queryset = AdvisoryBoardModel.objects.all()\n\n\n\nclass AddAnnouncement(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass ListAnnouncement(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass AnnouncementDetail(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\nclass AnnouncementDeleteUpdate(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = AnnouncementSerializer\n queryset = AnnouncementModel.objects.all()\n\n\nclass SuperadminProfileView(APIView):\n permission_classes = (IsSuperUser, )\n\n def get(self, request, *args, **kwargs):\n user = get_user_from_token(request)\n data = {\n 'name': user.username,\n 'email': user.email\n }\n return Response(data)\n\n\n\nclass AddJobClassified(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\nclass ViewJobClassified(generics.ListAPIView):\n permission_classes = (AllowAny, )\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\nclass JobClassifiedDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (AllowAny, )\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\nclass JobClassifiedDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = JobClassifiedSerializer\n queryset = JobClassifiedModel.objects.all()\n\n\n\nclass AddCustomerReviews(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\nclass ViewCustomerReview(generics.ListAPIView):\n permission_classes = (IsClient, )\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\nclass CustomerReviewDetailView(generics.RetrieveAPIView):\n lookup_field = 'slug'\n permission_classes = (IsClient, )\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\nclass CustomerReviewDeleteUpdateView(generics.RetrieveUpdateDestroyAPIView):\n lookup_field = 'slug'\n permission_classes = (IsSuperUser, )\n serializer_class = CustomerReviewSerializer\n queryset = CustomerReviewModel.objects.all()\n\n\n\nclass ClientComplain(APIView):\n\n permission_classes = (IsSuperUser, )\n serializer = ViewComplainSerializer(many=True)\n\n\nclass clientfeedback(APIView):\n\n permission_classes = (IsSuperUser, )\n\n def get(self, request, format=None):\n feeds = ClientFeedBackModel.objects.filter(\n Class__admin = self.request.user\n )\n serializer = ClientFeedbackSerializer(feeds, many=True)\n return Response(serializer.data)\n\nclass Enroll_Course(APIView):\n permission_classes = (IsSuperUser, )\n def post(self, request, format=None):\n serializer = EnrollCourseSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data,status =status.HTTP_201_CREATED)\n \n else:\n return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)\nclass ViewEnroll_Course(APIView):\n permission_classes = (IsSuperUser, )\n \n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Enroll_CourseModel.objects.filter(\n course = course, client = client\n )\n serializer = ViewEnrollCourseSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\nclass DetailEnroll_CourseView(APIView):\n permission_classes = (IsSuperUser, )\n\n def get_object(self,pk):\n try:\n return Enroll_CourseModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self, request, pk, format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data)\n return Response(serializer.data)\n\n def put(self,request,pk,format=None):\n data = self.get_object(pk)\n serializer = ViewEnrollCourseSerializer(data,data = request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n\n def delete(self,request,pk,format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n \n \nclass CourseDetail(APIView):\n permission_classes = (IsSuperUser, )\n\n def get_object(self, slug):\n try:\n return CourseModel.objects.get(slug=slug)\n except CourseModel.DoesNotExist:\n raise Http404\n\n def get(self, request, slug, format=None):\n data = self.get_object(slug)\n if data.classes.school.admin == self.request.user:\n serializer = ViewCourseSerializer(data)\n return Response(serializer.data)\n else:\n return Response(\n {'message':'This course does not belong to your school'}, \n status=status.HTTP_400_BAD_REQUEST\n )\n\n def put(self,request,slug,format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n serializer = CourseSerializer(data,data = request.data)\n if serializer.is_valid(raise_exception=True):\n course = serializer.validated_data.get('course', '')\n if course.client.admin == self.request.user:\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n return Response(\n {'message':'This Class does not belong to you'}, \n status=status.HTTP_400_BAD_REQUEST\n )\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response(\n {'message':'This course does not belong to you'}, \n status=status.HTTP_400_BAD_REQUEST\n )\n\n def delete(self,request,slug,format=None):\n data = self.get_object(slug)\n if data.course.client.admin == self.request.user:\n data.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n else:\n return Response(\n {'message':'This course does not belong to you'}, \n status=status.HTTP_400_BAD_REQUEST\n )\n\nclass SchoolRegistrationView(RegisterView):\n serializer_class = RegisterSchoolSerializer\n permission_classes = (IsSuperUser,)\n \nclass Add_question(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n def post(self,request,format=None):\n serializer = QuestionSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data,status =status.HTTP_201_CREATED)\n \n else:\n return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)\n\nclass Viewquestion(generics.ListAPIView):\n permission_classes = (IsSuperUser, )\n \n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = QuestionModel.objects.filter(\n course_id = course)\n serializer = QuestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n\n\nclass QuestionDetail(APIView):\n permission_classes = (IsSuperUser, )\n\n def get_object(self,pk):\n try:\n return QuestionModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self,request,pk,format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data)\n return Response(serializer.data)\n \n\n def put(self,request,pk,format=None):\n data = self.get_object(pk)\n serializer = QuestionSerializer(data,data = request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n \n \n def delete(self,request,pk,format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\nclass SubmittedQuestionView(APIView):\n permission_classes = (IsSuperUser, )\n \n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmitquestionModel.objects.filter(\n course__course = course,\n client__client = client\n )\n serializer = Client_submittedquestionSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK) \n\nclass AddonlineTest(generics.CreateAPIView):\n permission_classes = (IsSuperUser, )\n def post(self, request, format=None):\n serializer = testSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n course = serializer.validated_data.get('course', '')\n serializer.save()\n return Response(serializer.data,status =status.HTTP_201_CREATED)\n \n else:\n return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)\n\nclass ViewOnlinetest(generics.ListAPIView):\n permission_classes = (IsSuperUser, )\n \n def get(self, request, *args, **kwargs):\n course = self.kwargs['course_id']\n data = Client_testModel.objects.filter(\n course_id = course)\n serializer = testSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n\n\nclass onlinetestDetail(APIView):\n permission_classes = (IsSuperUser, )\n\n def get_object(self,pk):\n try:\n return Client_testModel.objects.get(id=pk)\n except:\n raise Http404\n\n def get(self,request,pk,format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data)\n return Response(serializer.data)\n \n\n def put(self,request,pk,format=None):\n data = self.get_object(pk)\n serializer = testSerializer(data,data = request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n \n \n def delete(self,request,pk,format=None):\n data = self.get_object(pk)\n data.delete()\n return Response(status = status.HTTP_204_NO_CONTENT) \n\nclass SubmittedonlineTestView(APIView):\n permission_classes = (IsSuperUser, )\n \n def get(self, request, *args, **kwargs):\n admin = self.request.user\n course = self.kwargs['course_id']\n client = self.kwargs['client_id']\n data = Client_SubmittestModel.objects.filter(\n course__course = course,\n client__client = client\n )\n serializer = Client_submittedtestSerializer(data, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)",
"step-ids": [
182,
186,
190,
206,
212
]
}
|
[
182,
186,
190,
206,
212
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.