ngram
listlengths 0
67.8k
|
|---|
[
"= getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year,",
"HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField()",
"def download(): \"\"\" Function downloads individual BIN files to server Returns: msg: status",
"pin = files['Pin'] szn = files['Year'] date = files['Date'] data = files['Encoded .BIN",
"from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season",
"already exists\" else: msg = \"Data input not correct\" print(msg) return \"Data input",
"def check_input(file_info): \"\"\" Function finds all .BIN folders in given path Args: file_info:",
"True: if check_exist(files) is False: pin = files['Pin'] szn = files['Year'] date =",
"print(msg) return False print(msg) return True def check_exist(file_info): \"\"\" Function checks if file",
"} # file_check = {'Pin': pin, # 'Date': date, # 'Time': time #",
"\"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN",
"files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row, \"Date\") time = getattr(row, \"Time\")",
"in given path Args: file_info: dictionary with individual file information Pin, Date, Time,",
"date, data, t) hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date': date, 'Time':",
"result: boolean to determine if all files completed \"\"\" # count = 0",
"\"Data file already exists\" print(msg) return \"Data already exists\" else: msg = \"Data",
"is True: if check_exist(files) is False: pin = files['Pin'] szn = files['Year'] date",
"# print(count) # set_logging() # logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\"",
"t = file_info['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return",
"= {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\": data",
"to run Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN",
"in given Pandas dataframe Args: files: datafram of all files Returns: result: boolean",
"message of file download \"\"\" set_logging() files = request.get_json() if check_input(files) is True:",
"return \"Data already exists\" else: msg = \"Data input not correct\" print(msg) return",
"result: boolean to determine if file was found. True is file was found.",
"= fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\"",
"str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True def create_new(file_info):",
"file_info['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return hd def",
"files.\") return True def check_input(file_info): \"\"\" Function finds all .BIN folders in given",
"Time, Year, Encoded .BIN file Returns: result: hd, HeadData object created \"\"\" set_logging()",
"Flask, request from pymodm import connect from pymodm import MongoModel, fields, errors import",
"number attached.\" print(msg) return False except ValueError: msg = \"Pin number is not",
"\"\"\" # count = 0 for row in files.itertuples(): pin = getattr(row, \"Pin\")",
"= file_info['Time'] year = file_info['Year'] msg = \"Data is ok\" try: int(pin) except",
"time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN files",
"errors import pymodm import requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app",
"True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if __name__ == \"__main__\":",
"'Year': szn, 'Date': date, 'Time': t } logging.info(file_info) msg = \"Data saved\" print(msg)",
"import requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class",
"dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: hd, HeadData object",
"files['Date'] data = files['Encoded .BIN file'] t = files['Time'] hd = HeadData(szn, pin,",
"Date, Time, Year, Encoded .BIN file Returns: result: boolean to determine if file",
"database Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN file",
"set_logging() pin = file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data = file_info['Encoded",
"requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new files.\") return True def",
"was found. True is file was found. False if not. \"\"\" pin =",
"to determine if file inputs were appropriate type \"\"\" pin = file_info['Pin'] date",
"date, # 'Time': time # } # if check_input(file_info) is True: # if",
"not necessary for server to run Args: file_info: file info dictionary Pin, Date,",
"ValueError: msg = \"Time entry is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year),",
"return False print(msg) return True def check_exist(file_info): \"\"\" Function checks if file already",
"False: pin = files['Pin'] szn = files['Year'] date = files['Date'] data = files['Encoded",
"= True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S",
"date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\": data } # file_check =",
"determine if all files completed \"\"\" # count = 0 for row in",
"for row in files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row, \"Date\") time",
"= getattr(row, \"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date,",
"check_exist(files) is False: pin = files['Pin'] szn = files['Year'] date = files['Date'] data",
"True is file was found. False if not. \"\"\" pin = file_info['Pin'] date",
"import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField()",
"dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean to determine",
"0 for row in files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row, \"Date\")",
"were appropriate type \"\"\" pin = file_info['Pin'] date = file_info['Date'] time = file_info['Time']",
"files['Encoded .BIN file'] t = files['Time'] hd = HeadData(szn, pin, date, data, t)",
"getattr(row, \"Time\") year = getattr(row, \"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\":",
"download(): \"\"\" Function downloads individual BIN files to server Returns: msg: status message",
"if file inputs were appropriate type \"\"\" pin = file_info['Pin'] date = file_info['Date']",
"pin, 'Year': szn, 'Date': date, 'Time': t } logging.info(file_info) msg = \"Data saved\"",
"if check_exist(file_check) is False: # count = count + 1 # else: #",
"dataframe Args: files: datafram of all files Returns: result: boolean to determine if",
"\"Encoded .BIN file\": data } # file_check = {'Pin': pin, # 'Date': date,",
"= \"No pin number attached.\" print(msg) return False except ValueError: msg = \"Pin",
"getattr(row, \"Pin\") date = getattr(row, \"Date\") time = getattr(row, \"Time\") year = getattr(row,",
"@app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN files to server Returns:",
"\"Time entry is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError:",
"# count = 0 for row in files.itertuples(): pin = getattr(row, \"Pin\") date",
"return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry is not",
"= \"Date entry is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except",
"not a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg =",
"file info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: hd,",
"file Returns: result: boolean to determine if file inputs were appropriate type \"\"\"",
"\"Data already exists\" else: msg = \"Data input not correct\" print(msg) return \"Data",
"getattr(row, \"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\":",
"new database file not necessary for server to run Args: file_info: file info",
"if file already exists in database Args: file_info: file info dictionary Pin, Date,",
"exists in database Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded",
"= getattr(row, \"Time\") year = getattr(row, \"Year\") data = getattr(row, \"_5\") file_info =",
"check_exist(file_info): \"\"\" Function checks if file already exists in database Args: file_info: file",
"file download \"\"\" set_logging() files = request.get_json() if check_input(files) is True: if check_exist(files)",
"file was found. True is file was found. False if not. \"\"\" pin",
"Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean to determine if",
"datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry is not Hour:Minute:Second\" print(msg) return",
"file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN file'] t = file_info['Time'] hd",
"t) hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t }",
"file info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean",
".BIN folders in given path Args: file_info: dictionary with individual file information Pin,",
"found. False if not. \"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in =",
"except pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\" Non flask function to",
"print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry is",
"return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry is not",
"szn, 'Date': date, 'Time': t } logging.info(file_info) msg = \"Data saved\" print(msg) return",
"Time, Year, Encoded .BIN file Returns: result: boolean to determine if file was",
"else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging()",
"= \"Data file already exists\" print(msg) return \"Data already exists\" else: msg =",
"entry is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg",
"= file_info['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return hd",
"given path Args: file_info: dictionary with individual file information Pin, Date, Time, Year,",
"count = 0 for row in files.itertuples(): pin = getattr(row, \"Pin\") date =",
"print(msg) return True def check_exist(file_info): \"\"\" Function checks if file already exists in",
"to server Returns: msg: status message of file download \"\"\" set_logging() files =",
"year = getattr(row, \"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\":",
"# } # if check_input(file_info) is True: # if check_exist(file_check) is False: #",
"= \"Data input not correct\" print(msg) return \"Data input not correct\" def download_all(files):",
"Year, Encoded .BIN file Returns: result: hd, HeadData object created \"\"\" set_logging() pin",
"Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns:",
"pymodm import requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__)",
"not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time",
"downloads individual BIN files to server Returns: msg: status message of file download",
"'Time': time # } # if check_input(file_info) is True: # if check_exist(file_check) is",
"= Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField()",
"else: msg = \"Data file already exists\" print(msg) return \"Data already exists\" else:",
"= fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"])",
"= fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time =",
"pin = file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg",
"try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\":",
"Args: files: datafram of all files Returns: result: boolean to determine if all",
"BIN files to server Returns: msg: status message of file download \"\"\" set_logging()",
"files['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() file_info = {'pin_number': pin,",
"except KeyError: msg = \"No pin number attached.\" print(msg) return False except ValueError:",
"pin = file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date,",
"file'] t = file_info['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info)",
"information Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean to determine",
"is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg =",
"boolean to determine if all files completed \"\"\" # count = 0 for",
"print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry is",
"logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\" Function finds all .BIN folders",
"to create new database file not necessary for server to run Args: file_info:",
"True def create_new(file_info): \"\"\" Non flask function to create new database file not",
"\"Data saved\" print(msg) return msg else: msg = \"Data file already exists\" print(msg)",
"Function downloads all .BIN folders in given Pandas dataframe Args: files: datafram of",
"Returns: result: boolean to determine if all files completed \"\"\" # count =",
"Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry",
"\"\"\" Client Function downloads all .BIN folders in given Pandas dataframe Args: files:",
"number is not a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError:",
"= HeadData(szn, pin, date, data, t) hd.save() file_info = {'pin_number': pin, 'Year': szn,",
"data = getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\":",
"<gh_stars>0 from flask import Flask, request from pymodm import connect from pymodm import",
"file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\":",
"= file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, #",
"Date, Time, Year, Encoded .BIN file Returns: result: hd, HeadData object created \"\"\"",
"+ 1 # else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) #",
"Function checks if file already exists in database Args: file_info: file info dictionary",
".BIN file Returns: result: hd, HeadData object created \"\"\" set_logging() pin = file_info['Pin']",
"time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first()",
"files Returns: result: boolean to determine if all files completed \"\"\" # count",
".BIN file'] t = files['Time'] hd = HeadData(szn, pin, date, data, t) hd.save()",
"status message of file download \"\"\" set_logging() files = request.get_json() if check_input(files) is",
"True def check_input(file_info): \"\"\" Function finds all .BIN folders in given path Args:",
"server to run Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded",
"year, \"Encoded .BIN file\": data } # file_check = {'Pin': pin, # 'Date':",
"files['Pin'] szn = files['Year'] date = files['Date'] data = files['Encoded .BIN file'] t",
"is file was found. False if not. \"\"\" pin = file_info['Pin'] date =",
"Returns: result: boolean to determine if file inputs were appropriate type \"\"\" pin",
"'Date': date, # 'Time': time # } # if check_input(file_info) is True: #",
"attached.\" print(msg) return False except ValueError: msg = \"Pin number is not a",
"create_new(file_info): \"\"\" Non flask function to create new database file not necessary for",
"already exists\" print(msg) return \"Data already exists\" else: msg = \"Data input not",
"exists\" else: msg = \"Data input not correct\" print(msg) return \"Data input not",
"request.get_json() if check_input(files) is True: if check_exist(files) is False: pin = files['Pin'] szn",
"pin = getattr(row, \"Pin\") date = getattr(row, \"Date\") time = getattr(row, \"Time\") year",
"'Date': date, 'Time': t } logging.info(file_info) msg = \"Data saved\" print(msg) return msg",
"Year, Encoded .BIN file Returns: result: boolean to determine if file was found.",
"files completed \"\"\" # count = 0 for row in files.itertuples(): pin =",
"determine if file was found. True is file was found. False if not.",
"False return True def create_new(file_info): \"\"\" Non flask function to create new database",
"{\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\": data }",
"MongoModel, fields, errors import pymodm import requests from datetime import datetime import logging",
"def download_all(files): \"\"\" Client Function downloads all .BIN folders in given Pandas dataframe",
"= {'Pin': pin, # 'Date': date, # 'Time': time # } # if",
"date_measured = fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download():",
"time, \"Year\": year, \"Encoded .BIN file\": data } # file_check = {'Pin': pin,",
"file'] t = files['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() file_info",
"= \"Season entry is not Year\" print(msg) return False print(msg) return True def",
"import Flask, request from pymodm import connect from pymodm import MongoModel, fields, errors",
"Encoded .BIN file Returns: result: hd, HeadData object created \"\"\" set_logging() pin =",
"Returns: result: hd, HeadData object created \"\"\" set_logging() pin = file_info['Pin'] szn =",
"datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number",
"HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True def",
"log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)",
"\"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time,",
"False except ValueError: msg = \"Pin number is not a number\" print(msg) return",
"= file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg =",
"pin = file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN",
"\"Pin number is not a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except",
"import connect from pymodm import MongoModel, fields, errors import pymodm import requests from",
"False: # count = count + 1 # else: # count = count",
"from flask import Flask, request from pymodm import connect from pymodm import MongoModel,",
"str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True",
"count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new files.\")",
"found. True is file was found. False if not. \"\"\" pin = file_info['Pin']",
"{'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t } logging.info(file_info) msg = \"Data",
"if check_input(file_info) is True: # if check_exist(file_check) is False: # count = count",
"import pymodm import requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app =",
"date = getattr(row, \"Date\") time = getattr(row, \"Time\") year = getattr(row, \"Year\") data",
"file inputs were appropriate type \"\"\" pin = file_info['Pin'] date = file_info['Date'] time",
"ValueError: msg = \"Pin number is not a number\" print(msg) return False try:",
"\"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\": data } # file_check",
"database file not necessary for server to run Args: file_info: file info dictionary",
"is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg =",
"Time, Year, Encoded .BIN file Returns: result: boolean to determine if file inputs",
"= HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled",
"# count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() #",
"file Returns: result: hd, HeadData object created \"\"\" set_logging() pin = file_info['Pin'] szn",
"if not. \"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try:",
"check_exist(file_check) is False: # count = count + 1 # else: # count",
"hd = HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return hd def set_logging():",
"files['Year'] date = files['Date'] data = files['Encoded .BIN file'] t = files['Time'] hd",
"download_all(files): \"\"\" Client Function downloads all .BIN folders in given Pandas dataframe Args:",
"result: hd, HeadData object created \"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year']",
"= getattr(row, \"Pin\") date = getattr(row, \"Date\") time = getattr(row, \"Time\") year =",
"r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new files.\") return",
"except ValueError: msg = \"Time entry is not Hour:Minute:Second\" print(msg) return False try:",
"szn = file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN file'] t =",
"date = file_info['Date'] data = file_info['Encoded .BIN file'] t = file_info['Time'] hd =",
"logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if __name__ == \"__main__\": app.run(host=\"127.0.0.1\",",
"= fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN files to",
"ValueError: msg = \"Season entry is not Year\" print(msg) return False print(msg) return",
"return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry is not",
"flask function to create new database file not necessary for server to run",
"files = request.get_json() if check_input(files) is True: if check_exist(files) is False: pin =",
"szn = files['Year'] date = files['Date'] data = files['Encoded .BIN file'] t =",
"file information Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean to",
"file not necessary for server to run Args: file_info: file info dictionary Pin,",
"logging.info(file_info) return hd def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled =",
"# HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date,",
"is not a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg",
"individual BIN files to server Returns: msg: status message of file download \"\"\"",
"\"Data input not correct\" def download_all(files): \"\"\" Client Function downloads all .BIN folders",
"file Returns: result: boolean to determine if file was found. True is file",
"run Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN file",
"except ValueError: msg = \"Date entry is not Month-Day-Year\" print(msg) return False try:",
"print(msg) return \"Data input not correct\" def download_all(files): \"\"\" Client Function downloads all",
"Pandas dataframe Args: files: datafram of all files Returns: result: boolean to determine",
"is False: pin = files['Pin'] szn = files['Year'] date = files['Date'] data =",
"False print(msg) return True def check_exist(file_info): \"\"\" Function checks if file already exists",
"\"Data input not correct\" print(msg) return \"Data input not correct\" def download_all(files): \"\"\"",
"datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry is not Year\" print(msg) return",
"files: datafram of all files Returns: result: boolean to determine if all files",
"year = file_info['Year'] msg = \"Data is ok\" try: int(pin) except KeyError: msg",
".BIN file Returns: result: boolean to determine if file was found. True is",
"server Returns: msg: status message of file download \"\"\" set_logging() files = request.get_json()",
"connect from pymodm import MongoModel, fields, errors import pymodm import requests from datetime",
"msg = \"Date entry is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\")",
"ok\" try: int(pin) except KeyError: msg = \"No pin number attached.\" print(msg) return",
"\"\"\" Function finds all .BIN folders in given path Args: file_info: dictionary with",
"data } # file_check = {'Pin': pin, # 'Date': date, # 'Time': time",
"date = files['Date'] data = files['Encoded .BIN file'] t = files['Time'] hd =",
"getattr(row, \"Date\") time = getattr(row, \"Time\") year = getattr(row, \"Year\") data = getattr(row,",
"not correct\" print(msg) return \"Data input not correct\" def download_all(files): \"\"\" Client Function",
"= file_info['Date'] data = file_info['Encoded .BIN file'] t = file_info['Time'] hd = HeadData(szn,",
"inputs were appropriate type \"\"\" pin = file_info['Pin'] date = file_info['Date'] time =",
"1 # else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count)",
"checks if file already exists in database Args: file_info: file info dictionary Pin,",
"= {'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t } logging.info(file_info) msg =",
"\"Date\") time = getattr(row, \"Time\") year = getattr(row, \"Year\") data = getattr(row, \"_5\")",
"file\": data } # file_check = {'Pin': pin, # 'Date': date, # 'Time':",
"\"\"\" pin = file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year = file_info['Year']",
"connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured",
"msg = \"Data saved\" print(msg) return msg else: msg = \"Data file already",
"is not Year\" print(msg) return False print(msg) return True def check_exist(file_info): \"\"\" Function",
"pin, date, data, t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled = True",
"fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN",
"False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry is not Hour:Minute:Second\"",
"input not correct\" def download_all(files): \"\"\" Client Function downloads all .BIN folders in",
"hd, HeadData object created \"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year'] date",
"\"%m-%d-%Y\") except ValueError: msg = \"Date entry is not Month-Day-Year\" print(msg) return False",
"app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y",
"return True def check_exist(file_info): \"\"\" Function checks if file already exists in database",
"logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if",
"json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new files.\") return True def check_input(file_info):",
"hd = HeadData(szn, pin, date, data, t) hd.save() file_info = {'pin_number': pin, 'Year':",
"file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result:",
"time_in}).first() except pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\" Non flask function",
"Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary",
"HeadData object created \"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year'] date =",
"created \"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data",
"except ValueError: msg = \"Season entry is not Year\" print(msg) return False print(msg)",
"ValueError: msg = \"Date entry is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time,",
"appropriate type \"\"\" pin = file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year",
"pin, # 'Date': date, # 'Time': time # } # if check_input(file_info) is",
"set_logging() # logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\" Function finds all",
"msg = \"Data is ok\" try: int(pin) except KeyError: msg = \"No pin",
"\"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return",
"log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if __name__",
"Non flask function to create new database file not necessary for server to",
"object created \"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year'] date = file_info['Date']",
"check_input(file_info): \"\"\" Function finds all .BIN folders in given path Args: file_info: dictionary",
"= True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if __name__ ==",
"def create_new(file_info): \"\"\" Non flask function to create new database file not necessary",
"if check_exist(files) is False: pin = files['Pin'] szn = files['Year'] date = files['Date']",
"= requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new files.\") return True",
"file_info['Time'] year = file_info['Year'] msg = \"Data is ok\" try: int(pin) except KeyError:",
"logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField()",
"import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number =",
"msg = \"Time entry is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\")",
"HeadData(szn, pin, date, data, t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled =",
"def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s",
"from pymodm import connect from pymodm import MongoModel, fields, errors import pymodm import",
"print(msg) return msg else: msg = \"Data file already exists\" print(msg) return \"Data",
"file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg = \"Data is ok\" try:",
"downloads all .BIN folders in given Pandas dataframe Args: files: datafram of all",
"Pin, Date, Time, Year, Encoded .BIN file Returns: result: hd, HeadData object created",
"\"%Y\") except ValueError: msg = \"Season entry is not Year\" print(msg) return False",
"False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry is not Month-Day-Year\"",
"hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled",
"input not correct\" print(msg) return \"Data input not correct\" def download_all(files): \"\"\" Client",
"= fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual",
"\"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\":",
"date, 'Time': t } logging.info(file_info) msg = \"Data saved\" print(msg) return msg else:",
"a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date",
".BIN file'] t = file_info['Time'] hd = HeadData(szn, pin, date, data, t) hd.save()",
"exists\" print(msg) return \"Data already exists\" else: msg = \"Data input not correct\"",
"with individual file information Pin, Date, Time, Year, Encoded .BIN file Returns: result:",
"pin, date, data, t) hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date': date,",
"} # if check_input(file_info) is True: # if check_exist(file_check) is False: # count",
"# count = count + 1 # else: # count = count r",
"encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads",
"= file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg = \"Data is ok\"",
"fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time = fields.CharField()",
"Client Function downloads all .BIN folders in given Pandas dataframe Args: files: datafram",
"given Pandas dataframe Args: files: datafram of all files Returns: result: boolean to",
"fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def",
"int(pin) except KeyError: msg = \"No pin number attached.\" print(msg) return False except",
"file was found. False if not. \"\"\" pin = file_info['Pin'] date = file_info['Date']",
"= \"Data is ok\" try: int(pin) except KeyError: msg = \"No pin number",
"import MongoModel, fields, errors import pymodm import requests from datetime import datetime import",
"Encoded .BIN file Returns: result: boolean to determine if file was found. True",
"is False: # count = count + 1 # else: # count =",
"date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\" Non",
"# \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except",
"# set_logging() # logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\" Function finds",
"entry is not Year\" print(msg) return False print(msg) return True def check_exist(file_info): \"\"\"",
"KeyError: msg = \"No pin number attached.\" print(msg) return False except ValueError: msg",
"HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\":",
"return False except ValueError: msg = \"Pin number is not a number\" print(msg)",
"saved\" print(msg) return msg else: msg = \"Data file already exists\" print(msg) return",
"# if check_input(file_info) is True: # if check_exist(file_check) is False: # count =",
"file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin),",
"try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry is not Month-Day-Year\" print(msg)",
"Returns: msg: status message of file download \"\"\" set_logging() files = request.get_json() if",
"necessary for server to run Args: file_info: file info dictionary Pin, Date, Time,",
"file already exists\" print(msg) return \"Data already exists\" else: msg = \"Data input",
"file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg = \"Data",
"if file was found. True is file was found. False if not. \"\"\"",
"datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel): season =",
"return msg else: msg = \"Data file already exists\" print(msg) return \"Data already",
"not Year\" print(msg) return False print(msg) return True def check_exist(file_info): \"\"\" Function checks",
"\"No pin number attached.\" print(msg) return False except ValueError: msg = \"Pin number",
"file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\":",
"function to create new database file not necessary for server to run Args:",
"pin number attached.\" print(msg) return False except ValueError: msg = \"Pin number is",
"result: boolean to determine if file inputs were appropriate type \"\"\" pin =",
"# \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False",
"class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary =",
"Function downloads individual BIN files to server Returns: msg: status message of file",
"\"\"\" Function downloads individual BIN files to server Returns: msg: status message of",
"date = file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in,",
"date = file_info['Date'] time = file_info['Time'] year = file_info['Year'] msg = \"Data is",
"\"\"\" set_logging() pin = file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data =",
"finds all .BIN folders in given path Args: file_info: dictionary with individual file",
"if check_input(files) is True: if check_exist(files) is False: pin = files['Pin'] szn =",
"fields, errors import pymodm import requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\")",
"= files['Pin'] szn = files['Year'] date = files['Date'] data = files['Encoded .BIN file']",
".BIN file Returns: result: boolean to determine if file inputs were appropriate type",
"flask import Flask, request from pymodm import connect from pymodm import MongoModel, fields,",
"pymodm import connect from pymodm import MongoModel, fields, errors import pymodm import requests",
"time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return",
"print(count) # set_logging() # logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\" Function",
"folders in given Pandas dataframe Args: files: datafram of all files Returns: result:",
"all files Returns: result: boolean to determine if all files completed \"\"\" #",
"count = count + 1 # else: # count = count r =",
"folders in given path Args: file_info: dictionary with individual file information Pin, Date,",
"count + 1 # else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info)",
"# logging.info(str(count)+\" new files.\") return True def check_input(file_info): \"\"\" Function finds all .BIN",
"} logging.info(file_info) msg = \"Data saved\" print(msg) return msg else: msg = \"Data",
"t = files['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() file_info =",
"= \"Pin number is not a number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\")",
"True: # if check_exist(file_check) is False: # count = count + 1 #",
"info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: hd, HeadData",
"\"Data is ok\" try: int(pin) except KeyError: msg = \"No pin number attached.\"",
"= logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return",
"fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN files to server",
"try: datetime.strptime(time, \"%H:%M:%S\") except ValueError: msg = \"Time entry is not Hour:Minute:Second\" print(msg)",
"already exists in database Args: file_info: file info dictionary Pin, Date, Time, Year,",
"Encoded .BIN file Returns: result: boolean to determine if file inputs were appropriate",
"# else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) #",
"= 0 for row in files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row,",
"\"Time\": time, \"Year\": year, \"Encoded .BIN file\": data } # file_check = {'Pin':",
"\"Year\": year, \"Encoded .BIN file\": data } # file_check = {'Pin': pin, #",
"{'Pin': pin, # 'Date': date, # 'Time': time # } # if check_input(file_info)",
"getattr(row, \"_5\") file_info = {\"Pin\": pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded",
"print(msg) return \"Data already exists\" else: msg = \"Data input not correct\" print(msg)",
"# file_check = {'Pin': pin, # 'Date': date, # 'Time': time # }",
"try: int(pin) except KeyError: msg = \"No pin number attached.\" print(msg) return False",
"return True def create_new(file_info): \"\"\" Non flask function to create new database file",
"return False return True def create_new(file_info): \"\"\" Non flask function to create new",
"msg = \"Season entry is not Year\" print(msg) return False print(msg) return True",
"file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN file'] t",
"season = fields.IntegerField() pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time",
"file_info['Encoded .BIN file'] t = file_info['Time'] hd = HeadData(szn, pin, date, data, t)",
"def check_exist(file_info): \"\"\" Function checks if file already exists in database Args: file_info:",
"format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) return if __name__ == \"__main__\": app.run(host=\"127.0.0.1\", port=5000)",
"not. \"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try: #",
"fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\", methods=[\"POST\"]) def download(): \"\"\" Function",
"False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry is not Year\"",
"pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\" Non flask function to create",
"not correct\" def download_all(files): \"\"\" Client Function downloads all .BIN folders in given",
"= file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\":",
"is ok\" try: int(pin) except KeyError: msg = \"No pin number attached.\" print(msg)",
"msg = \"Pin number is not a number\" print(msg) return False try: datetime.strptime(date,",
"of file download \"\"\" set_logging() files = request.get_json() if check_input(files) is True: if",
"Year\" print(msg) return False print(msg) return True def check_exist(file_info): \"\"\" Function checks if",
"msg else: msg = \"Data file already exists\" print(msg) return \"Data already exists\"",
"datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry is not Month-Day-Year\" print(msg) return",
"set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s',",
"create new database file not necessary for server to run Args: file_info: file",
"info dictionary Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean to",
"return hd def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled = True",
"t } logging.info(file_info) msg = \"Data saved\" print(msg) return msg else: msg =",
"row in files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row, \"Date\") time =",
"= count + 1 # else: # count = count r = requests.post(\"http://127.0.0.1:5000/api/download\",",
"Year, Encoded .BIN file Returns: result: boolean to determine if file inputs were",
"data = file_info['Encoded .BIN file'] t = file_info['Time'] hd = HeadData(szn, pin, date,",
"data, t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled = True log =",
"date, data, t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled = True log",
"t) hd.save() logging.info(file_info) return hd def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug')",
"set_logging() files = request.get_json() if check_input(files) is True: if check_exist(files) is False: pin",
".BIN file\": data } # file_check = {'Pin': pin, # 'Date': date, #",
"time = getattr(row, \"Time\") year = getattr(row, \"Year\") data = getattr(row, \"_5\") file_info",
"individual file information Pin, Date, Time, Year, Encoded .BIN file Returns: result: boolean",
"time = file_info['Time'] year = file_info['Year'] msg = \"Data is ok\" try: int(pin)",
"= file_info['Pin'] szn = file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN file']",
"= file_info['Year'] date = file_info['Date'] data = file_info['Encoded .BIN file'] t = file_info['Time']",
"new files.\") return True def check_input(file_info): \"\"\" Function finds all .BIN folders in",
"return \"Data input not correct\" def download_all(files): \"\"\" Client Function downloads all .BIN",
"Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry",
"is True: # if check_exist(file_check) is False: # count = count + 1",
"all .BIN folders in given path Args: file_info: dictionary with individual file information",
"file_info['Pin'] date = file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\":",
"msg = \"No pin number attached.\" print(msg) return False except ValueError: msg =",
"\"\"\" set_logging() files = request.get_json() if check_input(files) is True: if check_exist(files) is False:",
"True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',",
"\"Date entry is not Month-Day-Year\" print(msg) return False try: datetime.strptime(time, \"%H:%M:%S\") except ValueError:",
"False if not. \"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in = file_info['Time']",
"\"Pin\") date = getattr(row, \"Date\") time = getattr(row, \"Time\") year = getattr(row, \"Year\")",
"= files['Date'] data = files['Encoded .BIN file'] t = files['Time'] hd = HeadData(szn,",
"= \"Time entry is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except",
"Returns: result: boolean to determine if file was found. True is file was",
"from pymodm import MongoModel, fields, errors import pymodm import requests from datetime import",
"except ValueError: msg = \"Pin number is not a number\" print(msg) return False",
"in files.itertuples(): pin = getattr(row, \"Pin\") date = getattr(row, \"Date\") time = getattr(row,",
"time # } # if check_input(file_info) is True: # if check_exist(file_check) is False:",
"Args: file_info: dictionary with individual file information Pin, Date, Time, Year, Encoded .BIN",
"boolean to determine if file was found. True is file was found. False",
"check_input(file_info) is True: # if check_exist(file_check) is False: # count = count +",
"return True def check_input(file_info): \"\"\" Function finds all .BIN folders in given path",
"path Args: file_info: dictionary with individual file information Pin, Date, Time, Year, Encoded",
"print(msg) return False except ValueError: msg = \"Pin number is not a number\"",
"correct\" print(msg) return \"Data input not correct\" def download_all(files): \"\"\" Client Function downloads",
"type \"\"\" pin = file_info['Pin'] date = file_info['Date'] time = file_info['Time'] year =",
"= file_info['Year'] msg = \"Data is ok\" try: int(pin) except KeyError: msg =",
"\"%H:%M:%S\") except ValueError: msg = \"Time entry is not Hour:Minute:Second\" print(msg) return False",
"file_info['Date'] data = file_info['Encoded .BIN file'] t = file_info['Time'] hd = HeadData(szn, pin,",
"hd def set_logging(): app.logger.disabled = True log = logging.getLogger('werkzeug') log.disabled = True logging.basicConfig(filename='data_server.txt',",
"data = files['Encoded .BIN file'] t = files['Time'] hd = HeadData(szn, pin, date,",
"check_input(files) is True: if check_exist(files) is False: pin = files['Pin'] szn = files['Year']",
"hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t } logging.info(file_info)",
"methods=[\"POST\"]) def download(): \"\"\" Function downloads individual BIN files to server Returns: msg:",
"\"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\"",
"msg = \"Data file already exists\" print(msg) return \"Data already exists\" else: msg",
"= count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\" new",
"correct\" def download_all(files): \"\"\" Client Function downloads all .BIN folders in given Pandas",
"completed \"\"\" # count = 0 for row in files.itertuples(): pin = getattr(row,",
"'Time': t } logging.info(file_info) msg = \"Data saved\" print(msg) return msg else: msg",
"all files completed \"\"\" # count = 0 for row in files.itertuples(): pin",
"HeadData(szn, pin, date, data, t) hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date':",
"True def check_exist(file_info): \"\"\" Function checks if file already exists in database Args:",
"= file_info['Encoded .BIN file'] t = file_info['Time'] hd = HeadData(szn, pin, date, data,",
"pymodm import MongoModel, fields, errors import pymodm import requests from datetime import datetime",
"determine if file inputs were appropriate type \"\"\" pin = file_info['Pin'] date =",
"data, t) hd.save() file_info = {'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t",
"count = count r = requests.post(\"http://127.0.0.1:5000/api/download\", json=file_info) # print(count) # set_logging() # logging.info(str(count)+\"",
"print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry is",
"was found. False if not. \"\"\" pin = file_info['Pin'] date = file_info['Date'] time_in",
"to determine if file was found. True is file was found. False if",
"\"Time\") year = getattr(row, \"Year\") data = getattr(row, \"_5\") file_info = {\"Pin\": pin,",
"= \"Data saved\" print(msg) return msg else: msg = \"Data file already exists\"",
"# 'Date': date, # 'Time': time # } # if check_input(file_info) is True:",
"file_check = {'Pin': pin, # 'Date': date, # 'Time': time # } #",
"Function finds all .BIN folders in given path Args: file_info: dictionary with individual",
"try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season entry is not Year\" print(msg)",
"= files['Time'] hd = HeadData(szn, pin, date, data, t) hd.save() file_info = {'pin_number':",
"= request.get_json() if check_input(files) is True: if check_exist(files) is False: pin = files['Pin']",
"file_info: dictionary with individual file information Pin, Date, Time, Year, Encoded .BIN file",
"else: msg = \"Data input not correct\" print(msg) return \"Data input not correct\"",
"msg = \"Data input not correct\" print(msg) return \"Data input not correct\" def",
"request from pymodm import connect from pymodm import MongoModel, fields, errors import pymodm",
"number\" print(msg) return False try: datetime.strptime(date, \"%m-%d-%Y\") except ValueError: msg = \"Date entry",
"pin_number = fields.CharField() date_measured = fields.CharField() encoded_binary = fields.CharField() time = fields.CharField() @app.route(\"/api/download\",",
"logging.info(file_info) msg = \"Data saved\" print(msg) return msg else: msg = \"Data file",
"all .BIN folders in given Pandas dataframe Args: files: datafram of all files",
"in database Args: file_info: file info dictionary Pin, Date, Time, Year, Encoded .BIN",
"file_info = {'pin_number': pin, 'Year': szn, 'Date': date, 'Time': t } logging.info(file_info) msg",
"= files['Encoded .BIN file'] t = files['Time'] hd = HeadData(szn, pin, date, data,",
"not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg = \"Season",
"boolean to determine if file inputs were appropriate type \"\"\" pin = file_info['Pin']",
"app = Flask(__name__) class HeadData(MongoModel): season = fields.IntegerField() pin_number = fields.CharField() date_measured =",
"download \"\"\" set_logging() files = request.get_json() if check_input(files) is True: if check_exist(files) is",
"of all files Returns: result: boolean to determine if all files completed \"\"\"",
"\"Season entry is not Year\" print(msg) return False print(msg) return True def check_exist(file_info):",
"\"time\": time_in}).first() except pymodm.errors.DoesNotExist: return False return True def create_new(file_info): \"\"\" Non flask",
"\"\"\" Function checks if file already exists in database Args: file_info: file info",
"msg: status message of file download \"\"\" set_logging() files = request.get_json() if check_input(files)",
"to determine if all files completed \"\"\" # count = 0 for row",
"= file_info['Date'] time_in = file_info['Time'] try: # HeadData.objects.raw({\"date_measured\": date, # \"time\": time_in, #",
"files to server Returns: msg: status message of file download \"\"\" set_logging() files",
".BIN folders in given Pandas dataframe Args: files: datafram of all files Returns:",
"# 'Time': time # } # if check_input(file_info) is True: # if check_exist(file_check)",
"requests from datetime import datetime import logging connect(\"mongodb://almostdone:<EMAIL>:45148/bme590final\") app = Flask(__name__) class HeadData(MongoModel):",
"for server to run Args: file_info: file info dictionary Pin, Date, Time, Year,",
"# if check_exist(file_check) is False: # count = count + 1 # else:",
"datafram of all files Returns: result: boolean to determine if all files completed",
"if all files completed \"\"\" # count = 0 for row in files.itertuples():",
"\"\"\" Non flask function to create new database file not necessary for server",
"file_info['Year'] msg = \"Data is ok\" try: int(pin) except KeyError: msg = \"No",
"file already exists in database Args: file_info: file info dictionary Pin, Date, Time,",
"= getattr(row, \"Date\") time = getattr(row, \"Time\") year = getattr(row, \"Year\") data =",
"pin, \"Date\": date, \"Time\": time, \"Year\": year, \"Encoded .BIN file\": data } #",
"dictionary with individual file information Pin, Date, Time, Year, Encoded .BIN file Returns:",
"date, # \"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first()",
"entry is not Hour:Minute:Second\" print(msg) return False try: datetime.strptime(str(year), \"%Y\") except ValueError: msg",
"= files['Year'] date = files['Date'] data = files['Encoded .BIN file'] t = files['Time']",
"\"time\": time_in, # \"pin_number\": str(pin)}).first() HeadData.objects.raw({\"pin_number\": str(pin), \"date_measured\": date, \"time\": time_in}).first() except pymodm.errors.DoesNotExist:"
] |
[
"import config from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id,",
"import unittest import config from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection",
"unittest import config from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection =",
"from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region,",
"amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token)",
"def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token = connection.auto_refresh_token() print(token) self.assertIsNotNone(token[\"access_token\"])",
"test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token = connection.auto_refresh_token() print(token) self.assertIsNotNone(token[\"access_token\"]) self.assertIsNotNone(connection.token)",
"import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token",
"class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token = connection.auto_refresh_token()",
"config from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret,",
"<reponame>accuenmedia/amazonadapi import unittest import config from amazonadapi.connection import Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self):",
"Connection class ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token =",
"ConnectionTestCase(unittest.TestCase): def test_connection(self): connection = Connection(config.ad_client_id, config.ad_client_secret, config.region, config.refresh_token) token = connection.auto_refresh_token() print(token)"
] |
[
"import tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt",
"+ ' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store =",
"connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line + ' ' +",
"np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0])",
"!= '#VALUE!': dist_store = [] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng =",
"range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist <",
"numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons",
"= float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist",
"len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num",
"grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line + ' ' + str(connect_num)",
"< max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist = dist closest_connection =",
"off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1])",
"def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line + ' '",
"tqdm import tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy()",
"= [] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii",
"+ str(connect_num) + ' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!':",
"plt from tqdm import tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes",
"as plt from tqdm import tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy()",
"n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num =",
"= np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line +",
"= len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8]",
"= pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i):",
"as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons =",
"= 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat",
"pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection",
"dist_store = [] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for",
"pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object)",
"in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist",
"float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng =",
"float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] =",
"import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0])",
"if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist = dist",
"offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def",
"n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line =",
"str(connect_num) + ' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store",
"return grid_line + ' ' + str(connect_num) + ' Connection' for i in",
"[] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in",
"import pandas as pd import matplotlib.pyplot as plt from tqdm import tqdm import",
"off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0])",
"len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return",
"np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist =",
"pd import matplotlib.pyplot as plt from tqdm import tqdm import numpy as np",
"tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist = 1000 off_lat =",
"= float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng",
"for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2)",
"in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist = 1000 off_lat",
"from tqdm import tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes =",
"pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line",
"float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] =",
"np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line + '",
"max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons):",
"tqdm import numpy as np pipelines = pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt =",
"pipelines[i,3] connect_num = pipelines[i,8] return grid_line + ' ' + str(connect_num) + '",
"' ' + str(connect_num) + ' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2]",
"+ ' ' + str(connect_num) + ' Connection' for i in tqdm(range(n_offt)): if",
"matplotlib.pyplot as plt from tqdm import tqdm import numpy as np pipelines =",
"'#VALUE!': dist_store = [] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1])",
"con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist:",
"= float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0]",
"= float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1]",
"closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist = dist closest_connection = pd.DataFrame(closest_connection).to_csv('OntoGasGrid/grid_component_owl_generator/closest connection.csv',index=False,header=False)",
"' + str(connect_num) + ' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] !=",
"as pd import matplotlib.pyplot as plt from tqdm import tqdm import numpy as",
"dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist = dist closest_connection",
"for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist =",
"= len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3]",
"= np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist",
"ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if",
"' Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = []",
"Connection' for i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist",
"= pipelines[i,3] connect_num = pipelines[i,8] return grid_line + ' ' + str(connect_num) +",
"import matplotlib.pyplot as plt from tqdm import tqdm import numpy as np pipelines",
"connect_num = pipelines[i,8] return grid_line + ' ' + str(connect_num) + ' Connection'",
"if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist = 1000 off_lat = float(offtakes[i,2])",
"dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2]",
"1000 off_lat = float(offtakes[i,2]) off_lng = float(offtakes[i,1]) for ii in range(n_cons): con_lat =",
"closest_connection = np.zeros((n_offt,2),dtype=object) def connection_name_get(i): grid_line = pipelines[i,3] connect_num = pipelines[i,8] return grid_line",
"grid_line + ' ' + str(connect_num) + ' Connection' for i in tqdm(range(n_offt)):",
"max_dist: closest_connection[i,0] = connection_name_get(ii) closest_connection[i,1] = pipelines[ii,2] max_dist = dist closest_connection = pd.DataFrame(closest_connection).to_csv('OntoGasGrid/grid_component_owl_generator/closest",
"offtakes[i,2] != '#VALUE!': dist_store = [] max_dist = 1000 off_lat = float(offtakes[i,2]) off_lng",
"= pd.read_csv('OntoGasGrid/pipeline_owl_generator/pipeline_split.csv').to_numpy() offtakes = pd.read_csv('OntoGasGrid/grid_component_owl_generator/grid_component_data.csv').to_numpy() n_offt = len(offtakes[:,0]) n_cons = len(pipelines[:,0]) closest_connection =",
"con_lng = float(pipelines[ii,1]) dist = np.sqrt((off_lat-con_lat)**2+(off_lng-con_lng)**2) if dist < max_dist: closest_connection[i,0] = connection_name_get(ii)",
"i in tqdm(range(n_offt)): if offtakes[i,2] != '#VALUE!': dist_store = [] max_dist = 1000",
"= pipelines[i,8] return grid_line + ' ' + str(connect_num) + ' Connection' for",
"pandas as pd import matplotlib.pyplot as plt from tqdm import tqdm import numpy",
"pipelines[i,8] return grid_line + ' ' + str(connect_num) + ' Connection' for i",
"float(offtakes[i,1]) for ii in range(n_cons): con_lat = float(pipelines[ii,0]) con_lng = float(pipelines[ii,1]) dist ="
] |
[
"= self.psql.name def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR):",
"file) if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script: %s', file)",
"Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time =",
"script: %s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed to run init script:",
"logging.info('waiting on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error",
"data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def",
"Client as Etcd from governor.postgresql import Postgresql from governor.ha import Ha import etcd",
"force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first",
"= Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s', e)",
"True def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound:",
"is data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts()",
"config): while True: logging.info('waiting on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed)",
"value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive()",
"force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return True",
"None if cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return",
"init script: %s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed to run init",
"etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url",
"as e: logging.error('Error communicating with etcd: %s', e) else: return time.sleep(5) def keep_alive(self):",
"def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster",
"self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not",
"self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data directory empty?",
"try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self,",
"os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running",
"e: logging.error('Error communicating with etcd: %s', e) else: return time.sleep(5) def keep_alive(self): value",
"self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return",
"self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try: self.etcd.vacate_leadership(self.name) except (etcd.EtcdCompareFailed,",
"= Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): #",
"from governor.etcd import Client as Etcd from governor.postgresql import Postgresql from governor.ha import",
"initialize(self, force_leader=False): self.keep_alive() # is data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif",
"except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s', e) else: return",
"from governor.postgresql import Postgresql from governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR",
"try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first =",
"sp.call(['sh', file]) != 0: logging.warn('Failed to run init script: %s', file) def connect_to_etcd(self,",
"try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader:",
"cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self):",
"file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init",
"if sp.call(['sh', file]) != 0: logging.warn('Failed to run init script: %s', file) def",
"self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha =",
"self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster()",
"= config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql,",
"self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): # run all the",
"first = not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving",
"scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR,",
"while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None",
"Postgresql from governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def",
"psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha",
"= self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False)",
"import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url =",
"True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if",
"e) else: return time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl,",
"self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self):",
"logging.error('Error communicating with etcd: %s', e) else: return time.sleep(5) def keep_alive(self): value =",
"self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def",
"communicating with etcd: %s', e) else: return time.sleep(5) def keep_alive(self): value = self.advertise_url",
"def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name))",
"Etcd from governor.postgresql import Postgresql from governor.ha import Ha import etcd class Governor:",
"import logging import time import os import subprocess as sp from governor.etcd import",
"load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time)",
"def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql =",
"def initialize(self, force_leader=False): self.keep_alive() # is data directory empty? if not self.psql.data_directory_empty(): self.load_psql()",
"%s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed to run init script: %s',",
"elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if",
"def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots()",
"file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script: %s', file) if sp.call(['sh', file])",
"init script: %s', file) def connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try:",
"leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running():",
"%s', file) def connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try: self.etcd =",
"= Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): # run all the scripts",
"not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not",
"etcd: %s', e) else: return time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name,",
"self.keep_alive() # is data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader):",
"= self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader: logging.info('syncing with",
"run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR):",
"time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle())",
"config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd)",
"Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh",
"self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def",
"self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster =",
"not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return",
"return True def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except",
"self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader:",
"config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name",
"sync_from_leader(self): while True: logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster =",
"cluster = None if cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader)",
"os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh')",
"def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for",
"import os import subprocess as sp from governor.etcd import Client as Etcd from",
"self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except",
"prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is",
"subprocess as sp from governor.etcd import Client as Etcd from governor.postgresql import Postgresql",
"connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError,",
"logging import time import os import subprocess as sp from governor.etcd import Client",
"leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster and",
"if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if",
"True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive()",
"file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file):",
"import Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config):",
"config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config)",
"governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config,",
"self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name",
"self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False):",
"cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5)",
"import Postgresql from governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d'",
"ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() #",
"False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self):",
"on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating",
"return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True:",
"self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False",
"force_leader=False): self.keep_alive() # is data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not",
"INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time",
"return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or",
"ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data directory empty? if not",
"self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop()",
"empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False):",
"logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try: self.etcd.vacate_leadership(self.name) except (etcd.EtcdCompareFailed, etcd.EtcdKeyNotFound):",
"Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url",
"# run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in",
"not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script: %s', file) if sp.call(['sh',",
"return time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except",
"value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data directory empty? if",
"for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not",
"etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s', e) else: return time.sleep(5) def",
"not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not",
"if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try:",
"def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize()",
"logging.info('resolving leader') try: cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster",
"True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try: self.etcd.vacate_leadership(self.name) except",
"file) if sp.call(['sh', file]) != 0: logging.warn('Failed to run init script: %s', file)",
"os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script: %s',",
"!= 0: logging.warn('Failed to run init script: %s', file) def connect_to_etcd(self, config): while",
"if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script: %s', file) if",
"(ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s', e) else: return time.sleep(5)",
"/docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file)",
"while True: logging.info('waiting on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as",
"= os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file): continue logging.info('Running init script:",
"%s', e) else: return time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value,",
"keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value,",
"run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try:",
"with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if",
"self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try: self.etcd.vacate_leadership(self.name) except (etcd.EtcdCompareFailed, etcd.EtcdKeyNotFound): pass",
"= config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name =",
"in os.listdir(self.INIT_SCRIPT_DIR): file = os.path.join(self.INIT_SCRIPT_DIR, file) if not file.endswith('.sh') or not os.path.isfile(file): continue",
"self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist:",
"directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self,",
"= not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving leader')",
"else: return time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value)",
"not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader() self.run_init_scripts() def init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name)",
"all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file",
"True: logging.info('waiting on etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e:",
"time.sleep(5) def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound:",
"etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start()",
"self.name = self.psql.name def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if not",
"force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving leader') try: cluster",
"self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self):",
"0: logging.warn('Failed to run init script: %s', file) def connect_to_etcd(self, config): while True:",
"etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data directory",
"if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots()",
"'/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql",
"the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file in os.listdir(self.INIT_SCRIPT_DIR): file =",
"= None if cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start()",
"logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start()",
"run init script: %s', file) def connect_to_etcd(self, config): while True: logging.info('waiting on etcd')",
"from governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self,",
"or not os.path.isfile(file): continue logging.info('Running init script: %s', file) if sp.call(['sh', file]) !=",
"time import os import subprocess as sp from governor.etcd import Client as Etcd",
"self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope,",
"prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data directory empty? if not self.psql.data_directory_empty():",
"file]) != 0: logging.warn('Failed to run init script: %s', file) def connect_to_etcd(self, config):",
"self.psql.name def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return",
"class Governor: INIT_SCRIPT_DIR = '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time",
"not os.path.isfile(file): continue logging.info('Running init script: %s', file) if sp.call(['sh', file]) != 0:",
"Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): # run",
"def keep_alive(self): value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name,",
"self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s',",
"Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd: %s', e) else:",
"logging.info('Running init script: %s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed to run",
"and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True time.sleep(5) def",
"except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader)",
"logging.warn('Failed to run init script: %s', file) def connect_to_etcd(self, config): while True: logging.info('waiting",
"self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while",
"if cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader): self.psql.write_recovery_conf(cluster.leader) self.psql.start() return True",
"self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def",
"as sp from governor.etcd import Client as Etcd from governor.postgresql import Postgresql from",
"to run init script: %s', file) def connect_to_etcd(self, config): while True: logging.info('waiting on",
"os.path.isfile(file): continue logging.info('Running init script: %s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed",
"governor.etcd import Client as Etcd from governor.postgresql import Postgresql from governor.ha import Ha",
"init_cluster(self, force_leader=False): try: self.etcd.init_cluster(self.name) except etcd.EtcdAlreadyExist: if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name,",
"self.psql.start() return True time.sleep(5) def load_psql(self): self.psql.start() if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while",
"sp from governor.etcd import Client as Etcd from governor.postgresql import Postgresql from governor.ha",
"self.etcd) self.name = self.psql.name def run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if",
"with etcd: %s', e) else: return time.sleep(5) def keep_alive(self): value = self.advertise_url try:",
"etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader: logging.info('syncing with leader') if self.psql.sync_from_leader(cluster.leader):",
"script: %s', file) def connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try: self.etcd",
"import subprocess as sp from governor.etcd import Client as Etcd from governor.postgresql import",
"# is data directory empty? if not self.psql.data_directory_empty(): self.load_psql() elif not self.init_cluster(force_leader): self.sync_from_leader()",
"return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return True def",
"cluster = self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader: logging.info('syncing",
"psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def run_init_scripts(self): # run all",
"governor.postgresql import Postgresql from governor.ha import Ha import etcd class Governor: INIT_SCRIPT_DIR =",
"not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True: logging.info('resolving leader') try:",
"etcd') try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with",
"except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevExist=False) def initialize(self, force_leader=False): self.keep_alive() # is data",
"file) def connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try: self.etcd = Etcd(config)",
"os import subprocess as sp from governor.etcd import Client as Etcd from governor.postgresql",
"import time import os import subprocess as sp from governor.etcd import Client as",
"def connect_to_etcd(self, config): while True: logging.info('waiting on etcd') try: self.etcd = Etcd(config) except",
"continue logging.info('Running init script: %s', file) if sp.call(['sh', file]) != 0: logging.warn('Failed to",
"try: self.etcd = Etcd(config) except (ConnectionRefusedError, etcd.EtcdConnectionFailed) as e: logging.error('Error communicating with etcd:",
"as Etcd from governor.postgresql import Postgresql from governor.ha import Ha import etcd class",
"self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users() return True def sync_from_leader(self): while True:",
"if self.psql.is_running(): self.psql.load_replication_slots() def run(self): while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self):",
"while True: self.keep_alive() logging.info(self.ha.run_cycle()) self.ha.sync_replication_slots() time.sleep(self.loop_time) def cleanup(self): self.psql.stop() self.etcd.delete(os.path.join(self.etcd.scope, self.name)) try: self.etcd.vacate_leadership(self.name)",
"self.etcd.get_cluster() except etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader: logging.info('syncing with leader')",
"import Client as Etcd from governor.postgresql import Postgresql from governor.ha import Ha import",
"value = self.advertise_url try: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl, prevValue=value) except etcd.EtcdKeyNotFound: self.etcd.write_scoped(self.name, value, ttl=self.etcd.ttl,",
"= '/docker-entrypoint-initdb.d' def __init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config)",
"except etcd.EtcdKeyNotFound: cluster = None if cluster and cluster.leader: logging.info('syncing with leader') if",
"__init__(self, config, psql_config): self.advertise_url = config.advertise_url self.loop_time = config.loop_time self.connect_to_etcd(config) self.psql = Postgresql(config,",
"self.connect_to_etcd(config) self.psql = Postgresql(config, psql_config) self.ha = Ha(self.psql, self.etcd) self.name = self.psql.name def",
"run_init_scripts(self): # run all the scripts /docker-entrypoint-initdb.d/*.sh if not os.path.isdir(self.INIT_SCRIPT_DIR): return for file",
"if not force_leader: return False self.psql.initialize() self.etcd.take_leadership(self.name, first = not force_leader) self.psql.start() self.psql.create_users()"
] |
[
"import models class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text =",
"from django.db import models class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8)",
"token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text = models.CharField(max_length=30) def __str__(self): return",
"django.db import models class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text",
"User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text = models.CharField(max_length=30) def __str__(self):",
"<filename>emptytime/timetable/models.py from django.db import models class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text =",
"= models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text = models.CharField(max_length=30) def __str__(self): return self.username_text",
"class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text = models.CharField(max_length=30) def",
"models class User(models.Model): token_text = models.CharField(max_length=100, null=True) username_text = models.CharField(max_length=8) pw_text = models.CharField(max_length=30)"
] |
[
"from .component import * from .context import * from .core import * from",
"import Clock from .component import * from .context import * from .core import",
"from .clock import Clock from .component import * from .context import * from",
".clock import Clock from .component import * from .context import * from .core",
".component import * from .context import * from .core import * from .exceptions",
"Clock from .component import * from .context import * from .core import *",
"* from .context import * from .core import * from .exceptions import *",
"import * from .context import * from .core import * from .exceptions import"
] |
[
"g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self):",
"m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run()",
"for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw) if __name__ == \"__main__\": unittest.main()",
"= nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in",
"not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g)",
"return False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching()",
"self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e",
"doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g,",
"import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g",
"nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g,",
"nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g",
"m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching()",
"nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 =",
"return True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m",
"return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self,",
"testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def",
"nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if",
"e[1], random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g)",
"nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges():",
"self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if not",
"True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw) if",
"g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def",
"self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if not m.isMatched(e[0]) and",
"pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g):",
"= nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1",
"m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u))",
"for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g =",
"if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def",
"generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0],",
"def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self):",
"m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u),",
"nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw)",
"and not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm =",
"python3 import random import unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self,",
"class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e",
"runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g,",
"in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS)",
"TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in",
"g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw =",
"runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g))",
"pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True)",
"self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw) if __name__",
"def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1))",
"m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm",
"def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if not m.isMatched(e[0]) and not",
"= nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self):",
"g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw",
"True return False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m =",
"= nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g))",
"= self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if not m.isMatched(e[0])",
"unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted():",
"True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u",
"pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g,",
"e in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False",
"def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 =",
"False def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g)",
"runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def",
"m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching()",
"self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in",
"in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False def",
"= pgm.getMatching() runAlgo(self.g) runAlgo(self.gw) def testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g,",
"networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g =",
"not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return False def testPathGrowingMatcher(self): def runAlgo(g):",
"hasUnmatchedNeighbors(self, g, m): for e in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]):",
"m): for e in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True",
"import random import unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g):",
"m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw) if __name__ == \"__main__\":",
"def generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges():",
"nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for",
"for e in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return True return",
"= nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g)",
"self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes(): self.assertEqual(m1.mate(u), m2.mate(u)) doTest(self.g) doTest(self.gw) if __name__ ==",
"e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\",",
"random import unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if",
"random.random()) return g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def",
"g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1],",
"setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m): for",
"as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not g.isWeighted(): g = nk.graphtools.toWeighted(g)",
"not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return",
"def testPathGrowingMatcher(self): def runAlgo(g): pgm = nk.matching.PathGrowingMatcher(self.g) pgm.run() m = pgm.getMatching() runAlgo(self.g) runAlgo(self.gw)",
"#!/usr/bin/env python3 import random import unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def",
"import unittest import networkit as nk class TestMatchingAlgorithms(unittest.TestCase): def generateRandomWeights(self, g): if not",
"if not g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random())",
"def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g, m):",
"g.isWeighted(): g = nk.graphtools.toWeighted(g) for e in g.iterEdges(): g.setWeight(e[0], e[1], random.random()) return g",
"testSuitorMatcher(self): def doTest(g): m1 = nk.matching.SuitorMatcher(g, False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2",
"g, m): for e in g.iterEdges(): if not m.isMatched(e[0]) and not m.isMatched(e[1]): return",
"False).run().getMatching() nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2))",
"self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for u in g.iterNodes():",
"g def setUp(self): self.g = nk.readGraph(\"input/PGPgiantcompo.graph\", nk.Format.METIS) self.gw = self.generateRandomWeights(self.g) def hasUnmatchedNeighbors(self, g,",
"nk.graphtools.sortEdgesByWeight(g, True) self.assertTrue(m1.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m1)) m2 = nk.matching.SuitorMatcher(g, True).run().getMatching() self.assertTrue(m2.isProper(g)) self.assertFalse(self.hasUnmatchedNeighbors(g, m2)) for"
] |
[
"instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn twitter_api = oauth_login() print twitter_api",
"Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter",
"= ' ---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = ' ----",
"import twitter ''' oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn",
"' ---- ' # Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY,",
"-*- coding: utf-8 -*- import twitter ''' oauth_login into twitter ''' # Docs",
") # Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn twitter_api =",
"' # Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET )",
"oauth_login(): # credentials for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = '",
"= ' ---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = ' ----",
"OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN =",
"utf-8 -*- import twitter ''' oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth",
"' ---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = ' ---- '",
"credentials for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = ' ---- '",
"oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): #",
"# -*- coding: utf-8 -*- import twitter ''' oauth_login into twitter ''' #",
"= ' ---- ' OAUTH_TOKEN_SECRET = ' ---- ' # Creating the authentification",
"' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET =",
"# Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY",
"OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api",
"python # -*- coding: utf-8 -*- import twitter ''' oauth_login into twitter '''",
"# credentials for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = ' ----",
"Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn twitter_api = oauth_login() print",
"authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api",
"# LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY = ' ---- '",
"= ' ---- ' # Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET,",
"twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for",
"Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY =",
"CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn twitter_api",
"---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET",
"OAUTH_TOKEN_SECRET = ' ---- ' # Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN,",
"= twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth)",
"---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = ' ---- ' #",
"' ---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = ' ---- '",
"''' # Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for OAuth",
"https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY = ' ----",
"#!/usr/bin/env python # -*- coding: utf-8 -*- import twitter ''' oauth_login into twitter",
"LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET",
"the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance",
"CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn",
"CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = '",
"# https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials for OAuth CONSUMER_KEY = '",
"for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN",
"twitter ''' oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn def",
"''' oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn def oauth_login():",
"CONSUMER_SECRET = ' ---- ' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = '",
"coding: utf-8 -*- import twitter ''' oauth_login into twitter ''' # Docs #",
"-*- import twitter ''' oauth_login into twitter ''' # Docs # https://dev.twitter.com/oauth #",
"' ---- ' OAUTH_TOKEN_SECRET = ' ---- ' # Creating the authentification auth",
"---- ' OAUTH_TOKEN_SECRET = ' ---- ' # Creating the authentification auth =",
"# Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) #",
"auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api =",
"twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth) return",
"---- ' # Creating the authentification auth = twitter.oauth.OAuth( OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET",
"OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET ) # Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api #",
"into twitter ''' # Docs # https://dev.twitter.com/oauth # LogIn def oauth_login(): # credentials",
"<filename>scripts/oauth_login.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import twitter ''' oauth_login into",
"def oauth_login(): # credentials for OAuth CONSUMER_KEY = ' ---- ' CONSUMER_SECRET =",
"OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = ' ---- ' # Creating the",
"# Twitter instance twitter_api = twitter.Twitter(auth=auth) return twitter_api # LogIn twitter_api = oauth_login()",
"' OAUTH_TOKEN_SECRET = ' ---- ' # Creating the authentification auth = twitter.oauth.OAuth(",
"' OAUTH_TOKEN = ' ---- ' OAUTH_TOKEN_SECRET = ' ---- ' # Creating"
] |
[
"True pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid)",
"pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit",
"mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 # assert tfork1.stdin",
"be written as a function. # pylint: disable=R0201 # pylint: disable=C0111 # source:",
"test_fork = False # create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork,",
"os import re import signal import sys from _pytest.monkeypatch import MonkeyPatch import pytest",
"against signal 0 # sending the signal 0 to a given PID just",
"0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command =",
"action, kick off subprocess run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command))",
"tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock",
"== 2 assert tfork2.stdout == False assert tfork2.stderr == False assert mock_os_chdir.call_count ==",
"mock_emit: # # action, kick off subprocess run # tfork1.run() # # assert",
"# patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit)",
"tfork1.pid != 23241 # assert tfork1.stdin == None # assert tfork1.stdout == None",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork)",
"test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True # mock mock_logging_debug",
"s_test.forked assert s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\")",
"'int'>\" ) mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def",
"list in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command,",
"GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') #",
"# # action, kick off subprocess run # tfork1.run() # # assert #",
"mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() #",
"\"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True",
"kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__",
"\"test_who\" assert not s_test.forked assert s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command:",
"function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # #",
"# test_name = 'test_who' # test_fork = False # # mock # with",
"# spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init) # # #",
"s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert s_test.name ==",
"| GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all",
"GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators",
"an invalid cmd. Should be of type array test_command = [\"who\"] test_name =",
"mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert s_test.name == \"test_who\" assert not",
"mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error",
") # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not",
"process second time\") mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def",
"of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name = 'test_who'",
"that # method was not added until version 3.6. This is arguably what",
"run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) #",
"= scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit of duplication we have",
"@mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command",
"NOTE: Decorators get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall()",
"3.6 pass as we expect. But Python3.5 gives an error stating that #",
"[\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 0 # mock",
"is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert s_test.name == \"test_who\"",
"not s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout is True",
"@pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self,",
"instance, # and so could be written as a function. # pylint: disable=R0201",
"# and so could be written as a function. # pylint: disable=R0201 #",
"\"\"\" import builtins import os import re import signal import sys from _pytest.monkeypatch",
"# mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os,",
"of type array test_command = [\"who\"] test_name = \"test_who\" test_fork = False s_test",
"list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def",
"False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is",
"a given PID just checks if any # process with the given PID",
"assert not s_test.process assert not s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked",
"mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of",
"name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class",
"mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]]",
"mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command,",
"test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) #",
"# from scarlett_os.internal.gi import gi, GLib # # Save unpatched versions of the",
"scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: #",
"assert tfork1.forked == False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH",
"== None # assert tfork1.stderr == None # assert tfork1.forked == False #",
"# GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name,",
") mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ +",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable types should",
"tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout",
"mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off subprocess run #",
"False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once assert kill_mock.call_count",
"mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork",
"+ \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug",
"the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock",
"in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"# mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir",
"== 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ +",
"\"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME:",
"mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os,",
"= mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\")",
"# # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with",
"None), name='MockGLib.spawn_async') # # Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) #",
"from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os # R0201 = Method could",
"is an invalid cmd. Should be of type array test_command = [\"who\", \"-b\"]",
"doesn't use its bound instance, # and so could be written as a",
"# 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command =",
"= MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for",
"# with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as",
"\"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this is an",
"mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid =",
"mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\")",
"# When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill",
"# GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get applied BOTTOM",
"import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False",
"and so could be written as a function. # pylint: disable=R0201 # pylint:",
"mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import module locally for testing",
"GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real",
"unpatched versions of the following so we can reset everything after tests finish",
"import sys from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os # R0201 =",
"mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork",
"mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE:",
"# noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir',",
"child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, #",
"a function. # pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def",
"s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\")",
"mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result =",
"mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\")",
"the mock object, which is true since that # method was not added",
"test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable types should return",
"assert s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked:",
"assert not s_test.forked assert s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\")",
"return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock",
"Save unpatched versions of the following so we can reset everything after tests",
"tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as",
"Bit of duplication we have going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout",
"mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test",
"= mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') #",
"# action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid",
"before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # #",
"process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid",
"mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert",
"can reset everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async =",
"mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug =",
"to send a signal to it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall()",
"scarlett_os # R0201 = Method could be a function Used when a method",
"!= 23241 # assert tfork1.stdin == None # assert tfork1.stdout == None #",
"import builtins import os import re import signal import sys from _pytest.monkeypatch import",
"# mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123)",
"the # permission to send a signal to it. kill_mock.assert_called_once_with(123, 0) assert result",
"a signal to it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def test_subprocess_init(self,",
"occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert",
"# flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now",
"mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask =",
"mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid",
"mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"]",
"test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name",
"\"\"\"Test a full run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\",",
"once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock",
"mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\",",
"2 assert tfork1.stdout == False assert tfork1.stderr == False assert mock_os_chdir.call_count == 1",
"what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command)",
"test_fork = True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error =",
"test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__,",
"added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass",
"mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with",
"3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass as we",
"# patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os,",
"Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True",
"= mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\",",
"test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True",
"# method was not added until version 3.6. This is arguably what Python3.4",
"should return a list in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as",
"is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process:",
"pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch =",
"= mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess,",
"# @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall()",
"# noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import",
"test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close')",
"# now unpatch all of these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False",
"following so we can reset everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid",
"Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock =",
"assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value",
"mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name =",
"subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ +",
"not s_test.forked assert s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name:",
"# \"So Python 3.4 and 3.6 pass as we expect. But Python3.5 gives",
"['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self,",
"\"-b\"] test_name = \"test_who\" test_fork = False # create subprocess object s_test =",
"with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value)",
"tfork1.forked == False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH |",
"#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins",
"\"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() test_command =",
"test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall()",
") mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid)",
"mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 # assert tfork1.stdin == None #",
"assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch",
") assert ( str(excinfo.value) == \"Executables and arguments must be str objects. types:",
"= mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async,",
"so could be written as a function. # pylint: disable=R0201 # pylint: disable=C0111",
"scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal 0 # sending the signal",
"name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME: Re-enable these guys",
"= \"fake_command\" test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\",",
"( str(excinfo.value) == \"Executables and arguments must be str objects. types: <class 'int'>\"",
"mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command =",
"None, None, None), name='MockGLib.spawn_async') # # Mock call to child_watch # GLib.child_watch_add =",
"mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def",
"0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb)",
"mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command,",
"if any # process with the given PID is running and you have",
"GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all of these guys # gi._gi._glib.Pid",
"noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import module",
"# mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int,",
"assert result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__",
"coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os import re",
"process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True #",
"True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid)",
"patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623)",
"OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called",
"== 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork",
"it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type",
"# permission to send a signal to it. kill_mock.assert_called_once_with(123, 0) assert result is",
"# before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add #",
"\"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall()",
"False assert tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1",
"assert tfork1.pid != 23241 # assert tfork1.stdin == None # assert tfork1.stdout ==",
"method was not added until version 3.6. This is arguably what Python3.4 should",
"spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) # assert",
"'test_who' # test_fork = False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as",
"# def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__,",
"assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method",
"None # assert tfork1.stdout == None # assert tfork1.stderr == None # assert",
"\"-b\"] test_name = \"test_who\" test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") #",
"= False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa",
"\"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug =",
"assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog post, assert_called_once didn't get",
"of these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add",
"gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall()",
"we expect. But Python3.5 gives an error stating that # there is no",
"\"kill\", kill_mock) # When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify",
"mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\",",
"test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command)",
"mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count ==",
"name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit',",
"# noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask',",
"False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa #",
"3.6. This is arguably what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command)",
"+ \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type,",
"mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass",
"def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object):",
") assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert tfork1.stderr == False",
"the signal 0 to a given PID just checks if any # process",
"versions of the following so we can reset everything after tests finish #",
"mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert",
"mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker):",
"Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) #",
"return a list in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo:",
"== False assert tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count ==",
"checks if any # process with the given PID is running and you",
"mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to",
"= mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger,",
"to a given PID just checks if any # process with the given",
"= mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE:",
"\"Executables and arguments must be str objects. types: <class 'int'>\" ) mocker.stopall() ###############################",
"# Verify that os.kill only called once assert kill_mock.call_count == 1 mocker.stopall() def",
"function. # pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request):",
"This is arguably what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) #",
"( str(excinfo.value) == \"Variable types should return a list in python3. Got: <class",
"mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\")",
"# with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as",
"on the mock object, which is true since that # method was not",
"test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not",
"mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\",",
"def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"]",
"kick off subprocess run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) #",
"mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir =",
"# with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as",
"to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', #",
"mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE:",
"mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall()",
"assert tfork1.stdin == None # assert tfork1.stdout == None # assert tfork1.stderr ==",
"# -*- coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os",
"Used when a method doesn't use its bound instance, # and so could",
"as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables",
"False # create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False )",
"to this blog post, assert_called_once didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/",
"# mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 # assert",
"source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest",
"# NOTE: On purpose this is an invalid cmd. Should be of type",
"applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init =",
"its bound instance, # and so could be written as a function. #",
"not added until version 3.6. This is arguably what Python3.4 should have done.\"",
"assert tfork2.stdout == False assert tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert",
"@pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def",
"have going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert tfork2.stderr",
"\"-b\"] test_name = \"test_who\" test_fork = True pid = 7 # mock mock_logging_debug",
"2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command",
"mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: #",
"# mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) #",
"pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork =",
"off subprocess run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin:",
"# tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb))",
"test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect",
"mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the",
"mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process",
"None # assert tfork1.stderr == None # assert tfork1.forked == False # assert",
"scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) #",
"of duplication we have going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout ==",
"= 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async",
"test against signal 0 # sending the signal 0 to a given PID",
"== 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count ==",
"spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock",
"== \"Executables and arguments must be str objects. types: <class 'int'>\" ) mocker.stopall()",
"should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test",
"test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert",
"[\"who\", \"-b\"] # test_name = 'test_who' # test_fork = False # # mock",
"spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off subprocess run # tfork1.run() #",
"everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async #",
"test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function",
"assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None))",
"tfork1.stdin == None # assert tfork1.stdout == None # assert tfork1.stderr == None",
"mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa",
"and arguments must be str objects. types: <class 'int'>\" ) mocker.stopall() ############################### START",
"int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(",
"# with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import module locally",
"# GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all of these guys #",
"use its bound instance, # and so could be written as a function.",
"source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass as we expect. But",
"= mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask",
"def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd of Subprocess.run()\"\"\" # mocker.stopall()",
"pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) ==",
"# # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) #",
"# R0201 = Method could be a function Used when a method doesn't",
"you have the # permission to send a signal to it. kill_mock.assert_called_once_with(123, 0)",
"expect. But Python3.5 gives an error stating that # there is no assert_called_once",
"== \"Variable types should return a list in python3. Got: <class 'int'>\" )",
"# mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError])",
"MonkeyPatch import pytest import scarlett_os # R0201 = Method could be a function",
"MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett",
"\"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with",
"fork=test_fork ) # NOTE: Bit of duplication we have going here. assert mock_sys_exit.call_count",
"<class 'int'>\" ) mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2",
"mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: #",
"scarlett_os.internal.gi import gi, GLib # # Save unpatched versions of the following so",
"# # Save unpatched versions of the following so we can reset everything",
"mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value",
"= True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\",",
"@pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\"",
"mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock call to child_watch #",
"so we can reset everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid #",
"def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, #",
"= gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid =",
"mock_logging_debug ) # NOTE: On purpose this is an invalid cmd. Should be",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit of duplication we have going",
"mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command =",
"True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall()",
"create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy =",
"def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect =",
"mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1",
"isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog post, assert_called_once didn't get added",
"# action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb',",
"assert_called_once didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4",
"def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"]",
"test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 0",
"= mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\")",
"Verify that os.kill only called once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self,",
"the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__",
"mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert",
") # NOTE: On purpose this is an invalid cmd. Should be of",
"kill_mock) # When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that",
"mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) #",
"scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this is",
"1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\")",
"going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert tfork2.stderr ==",
"tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count",
"didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and",
"None, None), name='MockGLib.spawn_async') # # Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add)",
"mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command,",
"s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) #",
"(removes the need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name =",
"excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable types",
"we have going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert",
"# test_command = [\"who\", \"-b\"] # test_name = 'test_who' # test_fork = False",
") mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose",
"mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError #",
"patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os,",
"1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self,",
"mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir =",
"bound instance, # and so could be written as a function. # pylint:",
"test_command, name=test_name, fork=test_fork ) # NOTE: Bit of duplication we have going here.",
"== 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid,",
"TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # #",
"be a function Used when a method doesn't use its bound instance, #",
"True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock",
"test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit",
"mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second",
"scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir)",
"0) assert result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock(",
"as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick",
"mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall()",
"\"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert",
"Python 3.4 and 3.6 pass as we expect. But Python3.5 gives an error",
"# GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock call",
"mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(",
"# NOTE: Bit of duplication we have going here. assert mock_sys_exit.call_count == 2",
"fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork",
"# mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess,",
"the need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\"",
"array test_command = [\"who\"] test_name = \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess(",
"== 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall()",
"all of these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async #",
"1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class",
"this blog post, assert_called_once didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ #",
"spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init) # # # source:",
"mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch",
"NOTE: test against signal 0 # sending the signal 0 to a given",
"= \"test_who\" test_fork = True pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\")",
"test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name",
"(removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") #",
"= mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys,",
"test_name = \"test_who\" test_fork = False # create subprocess object s_test = scarlett_os.subprocess.Subprocess(",
"= scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command),",
"== False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD",
"mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result",
"mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__",
"mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger,",
"1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self,",
"pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit",
"# with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as",
"Should be of type array test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork",
"mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask)",
"name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug",
"import MonkeyPatch import pytest import scarlett_os # R0201 = Method could be a",
"# assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # )",
"def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\"",
"{}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 #",
"get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6",
"assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert tfork2.stderr == False assert",
"mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\",",
"True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert s_test.name == \"test_who\" assert",
"mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count",
"mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess(",
"mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator",
"side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask =",
"# mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose this is",
"arguments must be str objects. types: <class 'int'>\" ) mocker.stopall() ############################### START HERE",
"with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask:",
"# NOTE: Decorators get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): #",
"= s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert",
"# pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield",
"# process with the given PID is running and you have the #",
"mock_exited_cb) # # now unpatch all of these guys # gi._gi._glib.Pid = before_patch_gi_pid",
"\"fake_command\" test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError)",
"s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type(",
"noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask'))",
"OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\")",
"purposes # from scarlett_os.internal.gi import gi, GLib # # Save unpatched versions of",
"pass as we expect. But Python3.5 gives an error stating that # there",
"the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\",",
"test_name = \"test_who\" test_fork = True pid = 7 # mock mock_logging_debug =",
"assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker):",
"tfork1.stderr == None # assert tfork1.forked == False # assert mock_emit.call_count == 0",
"{}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid",
"here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert tfork2.stderr == False",
"s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert",
") assert ( str(excinfo.value) == \"Variable types should return a list in python3.",
"= mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os,",
"23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async #",
"scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork",
"[\"who\"] test_name = \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork",
"mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH,",
"TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall()",
"and 3.6 pass as we expect. But Python3.5 gives an error stating that",
"\"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess(",
"= \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) #",
"# with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as",
"and you have the # permission to send a signal to it. kill_mock.assert_called_once_with(123,",
"+ \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test",
"mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # mock",
"run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to",
"test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd of Subprocess.run()\"\"\" # mocker.stopall() #",
"R0201 = Method could be a function Used when a method doesn't use",
"return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\")",
"0 # sending the signal 0 to a given PID just checks if",
"def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"]",
"only called once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() #",
"= [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\",",
"need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork",
"mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit",
"fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork",
"until version 3.6. This is arguably what Python3.4 should have done.\" # assert",
"# mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None)",
"mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") #",
"s_test.stdout is True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\")",
"version 3.6. This is arguably what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command)",
"method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True",
"assert_called_once method on the mock object, which is true since that # method",
"stating that # there is no assert_called_once method on the mock object, which",
"= [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 0 #",
"assert tfork1.stdout == None # assert tfork1.stderr == None # assert tfork1.forked ==",
"\"test_who\" test_fork = True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork",
"there is no assert_called_once method on the mock object, which is true since",
"for testing purposes # from scarlett_os.internal.gi import gi, GLib # # Save unpatched",
"class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork =",
"@pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class",
"# source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass as we expect.",
"# name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with",
"guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd",
"= [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 7 #",
"action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert",
"mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert tfork1.stderr == False assert mock_os_chdir.call_count",
"now unpatch all of these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async =",
"== 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def",
"patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\",",
"# pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch",
"mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\",",
"\"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os,",
"mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def",
"# patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw False assert not",
"sending the signal 0 to a given PID just checks if any #",
"test_name = 'test_who' # test_fork = False # # mock # with mock.patch('scarlett_os.subprocess.os.fork',",
"gives an error stating that # there is no assert_called_once method on the",
"mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import module locally for testing purposes",
"assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list)",
"given PID is running and you have the # permission to send a",
"Python3.5 gives an error stating that # there is no assert_called_once method on",
"mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir",
"result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal 0 # sending",
"\"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug )",
"mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ +",
"= 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\",",
"# @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd of",
"= before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get applied BOTTOM to TOP",
"# GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) #",
"== \"test_who\" assert not s_test.forked assert s_test.stdout is True assert s_test.stderr is True",
"class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker):",
"fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method",
"= mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork)",
"test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 7",
"test_name = \"test_who\" test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value",
"str(excinfo.value) == \"Variable types should return a list in python3. Got: <class 'int'>\"",
"called once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock",
"-*- coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os import",
"kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called",
"str(excinfo.value) == \"Executables and arguments must be str objects. types: <class 'int'>\" )",
"fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert tfork1.stderr ==",
"mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit'))",
"mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa",
"\"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal 0",
"not s_test.process assert not s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked assert",
"noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid'))",
"https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass as we expect. But Python3.5",
"mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) #",
"python # -*- coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import",
"just checks if any # process with the given PID is running and",
"GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close",
"mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit)",
"mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test",
"= mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ +",
"signal 0 # sending the signal 0 to a given PID just checks",
"be of type array test_command = [\"who\"] test_name = \"test_who\" test_fork = False",
"is no assert_called_once method on the mock object, which is true since that",
"= True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\")",
"def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\",",
"fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable types should return a list",
"test_fork = True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork =",
"= mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid",
"method on the mock object, which is true since that # method was",
"run_check_command=True ) assert ( str(excinfo.value) == \"Variable types should return a list in",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables and arguments",
"BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init',",
"with the given PID is running and you have the # permission to",
"test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name",
"\"command\"] test_name = \"fake_command\" test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork",
"to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger,",
"= \"test_who\" test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value =",
"mocker.stopall() # # NOTE: Decorators get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self,",
"+ \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError",
"mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__',",
"flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch",
"# \"\"\"Test a full run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command =",
"# autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init) # # # source: http://stackoverflow.com/questions/28181867/how-do-a-mock-a-superclass-that-is-part-of-a-library",
"# assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self,",
"PID is running and you have the # permission to send a signal",
"mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa",
"signal to it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def test_subprocess_init(self, mocker):",
"True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\")",
"test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the",
"fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME: Re-enable these guys #",
"False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1",
"23241 # assert tfork1.stdin == None # assert tfork1.stdout == None # assert",
"a full run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"]",
"noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir'))",
"mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\",",
"mock_os_umask: # noqa # # Import module locally for testing purposes # from",
"# assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) ==",
"PID just checks if any # process with the given PID is running",
"import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\",",
"= True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") #",
"to it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall()",
"method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = True",
"= [\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True # mock mock_logging_debug =",
"mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid =",
"False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch",
"= mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\")",
"a method doesn't use its bound instance, # and so could be written",
"= GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 #",
"test_command = [\"who\"] test_name = \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command,",
"the given PID is running and you have the # permission to send",
"forking process second time\") mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') #",
"scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once assert kill_mock.call_count == 1 mocker.stopall()",
"import os import re import signal import sys from _pytest.monkeypatch import MonkeyPatch import",
"= OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw False",
"\"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 =",
"mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # #",
") mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name = 'test_who' # test_fork =",
"connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name =",
"mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker):",
"scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list)",
"re import signal import sys from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os",
"subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test,",
"== False assert tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count ==",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\",",
"assert ( str(excinfo.value) == \"Variable types should return a list in python3. Got:",
"== 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall()",
"mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork,",
"\"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\")",
"from scarlett_os.internal.gi import gi, GLib # # Save unpatched versions of the following",
"pytest import scarlett_os # R0201 = Method could be a function Used when",
"# mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 # assert tfork1.stdin == None",
"# test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes",
"mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger,",
"# mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit',",
"\"test_who\" test_fork = False # create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"# mocker.stopall() # # NOTE: Decorators get applied BOTTOM to TOP # def",
"disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo()",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork)",
"mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\",",
"def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"]",
"mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as",
"= mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error",
"as mock_os_umask: # noqa # # Import module locally for testing purposes #",
"# assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr:",
"Should be of type array test_command = [\"who\"] test_name = \"test_who\" test_fork =",
"mock_fork) # action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True )",
"True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" )",
"invalid cmd. Should be of type array test_command = [\"who\", \"-b\"] test_name =",
"before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241",
"mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name =",
"mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count",
"mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2",
"name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable types should return a",
"mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\"",
"\"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) #",
"= \"test_who\" test_fork = True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\")",
"7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\")",
"# assert tfork1.stderr == None # assert tfork1.forked == False # assert mock_emit.call_count",
"Mock function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None),",
"scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir)",
"name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables and arguments must be",
"of type array test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False",
"test_name = \"fake_command\" test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork =",
"= True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit =",
"0 to a given PID just checks if any # process with the",
"we can reset everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async",
"assert tfork1.stdout == False assert tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert",
"2 assert tfork2.stdout == False assert tfork2.stderr == False assert mock_os_chdir.call_count == 1",
"2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command",
"send a signal to it. kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def",
"\"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os import re import signal import",
"error stating that # there is no assert_called_once method on the mock object,",
"added until version 3.6. This is arguably what Python3.4 should have done.\" #",
"test_pid, mock_exited_cb) # # now unpatch all of these guys # gi._gi._glib.Pid =",
"# source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly",
"= False # create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False",
"mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to",
"[\"who\", \"-b\"] test_name = \"test_who\" test_fork = True pid = 7 # mock",
"_pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os # R0201 = Method could be",
"== mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the need",
"\"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit of",
"mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall()",
"full run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"] #",
"mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with",
"mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with",
"objects. types: <class 'int'>\" ) mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug')",
"= scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout ==",
"{}\".format(None)) # assert tfork1.pid != 23241 # assert tfork1.stdin == None # assert",
"mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # #",
"of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\")",
"https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest",
"# map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command)",
"duplication we have going here. assert mock_sys_exit.call_count == 2 assert tfork2.stdout == False",
"tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add =",
"mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork )",
"# NOTE: According to this blog post, assert_called_once didn't get added till 3.6??",
"test_subprocess ---------------------------------- \"\"\" import builtins import os import re import signal import sys",
"FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a",
"# noqa # # Import module locally for testing purposes # from scarlett_os.internal.gi",
"\"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count",
"test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # create subprocess",
"assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\"",
"assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert",
"\"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs,",
"is arguably what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output",
"mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork)",
"s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout is True assert s_test.stderr is",
"an invalid cmd. Should be of type array test_command = [\"who\", \"-b\"] test_name",
"\"test_who\" test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int",
"Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__",
"is running and you have the # permission to send a signal to",
"since that # method was not added until version 3.6. This is arguably",
"mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug",
"# assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the",
"pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch() yield mpatch",
"mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork)",
"could be a function Used when a method doesn't use its bound instance,",
") mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError)",
"mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object(",
"############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\"",
"---------------------------------- \"\"\" import builtins import os import re import signal import sys from",
"import scarlett_os # R0201 = Method could be a function Used when a",
"But Python3.5 gives an error stating that # there is no assert_called_once method",
"<class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True )",
"HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method",
"# def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd of Subprocess.run()\"\"\" #",
"HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class",
"# gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add #",
"assert tfork1.stderr == None # assert tfork1.forked == False # assert mock_emit.call_count ==",
"type array test_command = [\"who\"] test_name = \"test_who\" test_fork = False s_test =",
"invalid cmd. Should be of type array test_command = [\"who\"] test_name = \"test_who\"",
"mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import",
"+ \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose",
"array test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # create",
"scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action with pytest.raises(TypeError) as excinfo:",
"== 2 assert tfork1.stdout == False assert tfork1.stderr == False assert mock_os_chdir.call_count ==",
"\"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action",
"class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork =",
"signal 0 to a given PID just checks if any # process with",
"= scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal 0 # sending the",
"mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): #",
"need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object(",
"1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class",
"have the # permission to send a signal to it. kill_mock.assert_called_once_with(123, 0) assert",
"Method could be a function Used when a method doesn't use its bound",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork)",
"as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa #",
"test_command = [\"who\", \"-b\"] # test_name = 'test_who' # test_fork = False #",
"mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # #",
"{}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241 # assert tfork1.stdin ==",
"import pytest import scarlett_os # R0201 = Method could be a function Used",
"mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0",
"= mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) #",
"\"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against",
"run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name",
"subprocess run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None))",
"call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1 =",
"mock_fork) # NOTE: On purpose this is an invalid cmd. Should be of",
"# action, kick off subprocess run # tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command:",
"mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork )",
"action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb',",
"= Method could be a function Used when a method doesn't use its",
"# # Import module locally for testing purposes # from scarlett_os.internal.gi import gi,",
"mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When",
"Import module locally for testing purposes # from scarlett_os.internal.gi import gi, GLib #",
"\"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os,",
"module locally for testing purposes # from scarlett_os.internal.gi import gi, GLib # #",
"# action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert",
"test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall()",
"= mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid",
"type array test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False #",
"tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit of duplication we",
"test_name = \"test_who\" test_fork = True pid = 0 # mock mock_logging_debug =",
"as mock_emit: # # action, kick off subprocess run # tfork1.run() # #",
"mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\" mocker.stopall() test_command",
"second time\") mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self,",
"that os.kill only called once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker):",
"mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid != 23241",
"[\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\")",
"\"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name,",
") # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all of these guys",
") mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this is an invalid cmd.",
"# test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( #",
"\"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\"",
"\"So Python 3.4 and 3.6 pass as we expect. But Python3.5 gives an",
"= mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork =",
"Decorators get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() #",
"s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator",
"# FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test",
"assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method",
"this is an invalid cmd. Should be of type array test_command = [\"who\"]",
"fork=test_fork ) # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert",
"isinstance(map_output, list) # assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall()",
"test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # mock mock_map_type_to_command",
"excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables and",
"# there is no assert_called_once method on the mock object, which is true",
"object, which is true since that # method was not added until version",
"0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid,",
"# Mock function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None,",
"# tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout:",
"disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\") def monkeysession(request): mpatch = MonkeyPatch()",
"true since that # method was not added until version 3.6. This is",
"mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid,",
"guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add",
"# # NOTE: Decorators get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker):",
"\"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking",
"# mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir",
"NOTE: Bit of duplication we have going here. assert mock_sys_exit.call_count == 2 assert",
"time\") mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug):",
"# Save unpatched versions of the following so we can reset everything after",
"mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the",
"types should return a list in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError)",
"function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async')",
"utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os import re import",
"function Used when a method doesn't use its bound instance, # and so",
"before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid')",
"OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw False assert",
"spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog",
"# fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit',",
"assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid:",
"mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork =",
"test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async # GLib.spawn_async =",
"\"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose this",
"python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork,",
"get applied BOTTOM to TOP # def test_check_command_type_is_array_of_str(self, mocker): # mocker.stopall() # mock_init",
"# # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init) # #",
"cmd. Should be of type array test_command = [\"who\"] test_name = \"test_who\" test_fork",
"# mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug",
"mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit",
"mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test",
"# # Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action",
"mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\")",
"= mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock call to child_watch",
"must be str objects. types: <class 'int'>\" ) mocker.stopall() ############################### START HERE HERON",
"mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: #",
"decorator (removes the need to import builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\")",
"+ \"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug =",
"cmd. Should be of type array test_command = [\"who\", \"-b\"] test_name = \"test_who\"",
"tfork1.stdout == False assert tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count",
"as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa #",
"fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According",
"which is true since that # method was not added until version 3.6.",
"[int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug",
"None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes the need",
"mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME: Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug')",
"not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once assert kill_mock.call_count == 1",
"with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa # # Import module locally for",
"mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this is an invalid cmd. Should",
"mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\")",
"mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid =",
"sys from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os # R0201 = Method",
"Subprocess.run()\"\"\" # mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name = 'test_who' #",
"GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # #",
"= scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb:",
"s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is True",
"= mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch",
"gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid,",
"\"test_who\" test_fork = True pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork",
"mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this is an invalid",
"@mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run connamd of Subprocess.run()\"\"\"",
"builtins)\"\"\" mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug",
"\"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"[\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # create subprocess object s_test",
"tfork2.stdout == False assert tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count",
"any # process with the given PID is running and you have the",
"name=test_name, fork=test_fork ) # NOTE: Bit of duplication we have going here. assert",
"purpose this is an invalid cmd. Should be of type array test_command =",
"mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid =",
"# assert tfork1.stdout == None # assert tfork1.stderr == None # assert tfork1.forked",
"# before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241,",
"as a function. # pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363 @pytest.fixture(scope=\"session\")",
"\"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, )",
"assert tfork1.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert",
"None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using the mock.patch decorator (removes",
"os.kill only called once assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall()",
"False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD #",
"GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock call to",
"assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once assert kill_mock.call_count ==",
"as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa #",
"test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name",
"= before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() #",
"= [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # create subprocess object",
"True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork",
"GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get applied BOTTOM to",
"# create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy",
"mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) #",
"-*- \"\"\" test_subprocess ---------------------------------- \"\"\" import builtins import os import re import signal",
"fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables and arguments must be str",
"= True pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\",",
"noqa # # Import module locally for testing purposes # from scarlett_os.internal.gi import",
"According to this blog post, assert_called_once didn't get added till 3.6?? # source:",
"kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock)",
"mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug",
"gi, GLib # # Save unpatched versions of the following so we can",
"def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import builtins)\"\"\"",
"= int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\")",
"test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError",
"permission to send a signal to it. kill_mock.assert_called_once_with(123, 0) assert result is True",
"the following so we can reset everything after tests finish # before_patch_gi_pid =",
"assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, # flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) #",
"with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit:",
"= mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called #",
"assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert tfork1.stderr == False assert",
"# with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off subprocess",
"mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\",",
") spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this",
"test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Executables and arguments must",
"before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get applied",
"START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test fork",
"\"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker):",
"object s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\")",
"action with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert (",
"be str objects. types: <class 'int'>\" ) mocker.stopall() ############################### START HERE HERON ###############################################",
"GLib # # Save unpatched versions of the following so we can reset",
"finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add",
"running and you have the # permission to send a signal to it.",
"a function Used when a method doesn't use its bound instance, # and",
"# mocker.stopall() # test_command = [\"who\", \"-b\"] # test_name = 'test_who' # test_fork",
"mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\",",
"mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir =",
"these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full run",
"throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only called once assert",
"assert s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker):",
"with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: # noqa # with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit:",
"s_test.process assert not s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout",
"mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) #",
"no assert_called_once method on the mock object, which is true since that #",
"\"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2",
"[\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\")",
"mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert mock_sys_exit.call_count == 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self,",
"mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object(",
"str objects. types: <class 'int'>\" ) mocker.stopall() ############################### START HERE HERON ############################################### #",
"a list in python3. Got: <class 'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess(",
"\"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\"",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\",",
"NOTE: On purpose this is an invalid cmd. Should be of type array",
"kill_mock.called # NOTE: test against signal 0 # sending the signal 0 to",
"name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process",
"mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On",
"= mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object(",
"# test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib function spawn_async # GLib.spawn_async",
"name=test_name, fork=test_fork, run_check_command=False ) spy = mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE:",
"False assert tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1",
"as we expect. But Python3.5 gives an error stating that # there is",
"that # there is no assert_called_once method on the mock object, which is",
") with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert (",
"mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork",
") mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self,",
"# # Mock function GLib function spawn_async # GLib.spawn_async = mock.create_autospec(GLib.spawn_async, return_value=(test_pid, None,",
"kill_mock.assert_called_once_with(123, 0) assert result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type =",
"mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, )",
"# ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all of these",
"tfork1.stdout == None # assert tfork1.stderr == None # assert tfork1.forked == False",
"testing purposes # from scarlett_os.internal.gi import gi, GLib # # Save unpatched versions",
"= False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect =",
"2 def test_subprocess_fork(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"who\",",
"to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command,",
"= \"test_who\" test_fork = False # create subprocess object s_test = scarlett_os.subprocess.Subprocess( test_command,",
"GLib.SpawnFlags.DO_NOT_REAP_CHILD # ) # GLib.child_watch_add.assert_called_once_with(GLib.PRIORITY_HIGH, test_pid, mock_exited_cb) # # now unpatch all of",
"reset everything after tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async",
"monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units",
"assert s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout is True assert s_test.stderr",
"tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count",
"mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\")",
"is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\"",
"mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\")",
"GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect",
"builtins import os import re import signal import sys from _pytest.monkeypatch import MonkeyPatch",
"import gi, GLib # # Save unpatched versions of the following so we",
"# test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close =",
"'int'>\" ) with pytest.raises(TypeError) as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert",
"# noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid',",
"mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off",
"= scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"])",
"s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout is True assert",
"import signal import sys from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os #",
"till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python 3.4 and 3.6 pass as",
"mock_sys_exit.call_count == 2 assert tfork2.stdout == False assert tfork2.stderr == False assert mock_os_chdir.call_count",
"# NOTE: test against signal 0 # sending the signal 0 to a",
"[int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug )",
"mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger,",
"Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1",
"mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off subprocess run # tfork1.run()",
"mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal",
"1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2",
"= mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask",
"== 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork",
"scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME: Re-enable these",
"False # mock mock_map_type_to_command = mocker.MagicMock(name=\"mock_map_type_to_command\") # mock_map_type_to_command.return_value = int mock_map_type_to_command.side_effect = [int,",
"When OSError occurs, throw False assert not scarlett_os.subprocess.check_pid(4353634632623) # Verify that os.kill only",
"On purpose this is an invalid cmd. Should be of type array test_command",
"= [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False # mock mock_map_type_to_command =",
"mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: # noqa",
"mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose this is an invalid",
"\"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # action",
"mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask =",
"mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork",
"assert not s_test.pid assert s_test.name == \"test_who\" assert not s_test.forked assert s_test.stdout is",
"int mock_map_type_to_command.side_effect = [int, [int, int]] mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object(",
"# GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE:",
"arguably what Python3.4 should have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output =",
"= mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init)",
"test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert",
"mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock_OSError\") kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\",",
"mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose this is an",
"s_test.check_command_type(test_command) # assert s_test.check_command_type( # test_command) == mock_check_command_type.return_value mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using",
"name=test_name, fork=test_fork ) assert mock_sys_exit.call_count == 2 assert tfork1.stdout == False assert tfork1.stderr",
"with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action, kick off subprocess run",
"assert kill_mock.call_count == 1 mocker.stopall() def test_check_pid(self, mocker): mocker.stopall() # mock kill_mock =",
"written as a function. # pylint: disable=R0201 # pylint: disable=C0111 # source: https://github.com/pytest-dev/pytest/issues/363",
"mock_logging_debug ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\",",
"test_fork = False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork: #",
"method doesn't use its bound instance, # and so could be written as",
"with mock.patch('scarlett_os.subprocess.sys.exit', mocker.Mock(name='mock_sys_exit')) as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir:",
"test_check_pid(self, mocker): mocker.stopall() # mock kill_mock = mocker.MagicMock(name=__name__ + \"_kill_mock\") mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock)",
"mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: #",
"assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker):",
"mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command,",
"\"Variable types should return a list in python3. Got: <class 'int'>\" ) with",
") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os,",
"when a method doesn't use its bound instance, # and so could be",
"assert kill_mock.called # NOTE: test against signal 0 # sending the signal 0",
"given PID just checks if any # process with the given PID is",
"# mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stderr: {}\".format(None)) # assert tfork1.pid !=",
"= [\"who\"] test_name = \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name,",
"# sending the signal 0 to a given PID just checks if any",
"mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error = mocker.MagicMock(name=\"mock_logging_error\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit =",
"kill_mock) result = scarlett_os.subprocess.check_pid(123) assert kill_mock.called # NOTE: test against signal 0 #",
"blog post, assert_called_once didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So",
"was not added until version 3.6. This is arguably what Python3.4 should have",
"\"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\",",
"mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) assert",
"\"debug\", mock_logging_debug ) # NOTE: On purpose this is an invalid cmd. Should",
"mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid: # noqa # with mock.patch('scarlett_os.subprocess.os.umask', mocker.Mock(name='mock_os_umask')) as mock_os_umask: #",
"after tests finish # before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add",
"this is an invalid cmd. Should be of type array test_command = [\"who\",",
"decorator (removes the need to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name",
"def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ + \"_mock_check_command_type\" ) mock_check_command_type.return_value =",
"mock_os_umask) scarlett_os.subprocess.Subprocess(test_command, name=test_name, fork=test_fork) mock_logging_error.assert_any_call(\"Error forking process second time\") mocker.stopall() # FIXME: Re-enable",
"import re import signal import sys from _pytest.monkeypatch import MonkeyPatch import pytest import",
"list) # NOTE: According to this blog post, assert_called_once didn't get added till",
"############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # 2 def test_subprocess_fork(self, mocker): \"\"\"Test",
"kill_mock.side_effect = OSError # patch mocker.patch.object(scarlett_os.subprocess.os, \"kill\", kill_mock) # When OSError occurs, throw",
"\"\"\"Units tests for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() #",
"an error stating that # there is no assert_called_once method on the mock",
"mock_fork = mocker.MagicMock(name=\"mock_fork\") mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess,",
"of the following so we can reset everything after tests finish # before_patch_gi_pid",
"run_check_command=True ) assert ( str(excinfo.value) == \"Executables and arguments must be str objects.",
"mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On purpose this",
"is an invalid cmd. Should be of type array test_command = [\"who\"] test_name",
"= False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # action assert s_test.check_command_type(test_command)",
"spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit)) as mock_emit: # # action,",
"mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests",
"True assert s_test.stderr is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\")",
"fork=test_fork) # with mock.patch('scarlett_os.subprocess.Subprocess.exited_cb', mocker.Mock(name='mock_exited_cb', spec=scarlett_os.subprocess.Subprocess.exited_cb)) as mock_exited_cb: # with mock.patch('scarlett_os.subprocess.Subprocess.emit', mocker.Mock(name='mock_emit', spec=scarlett_os.subprocess.Subprocess.emit))",
"NOTE: According to this blog post, assert_called_once didn't get added till 3.6?? #",
"# assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output,",
"= 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit =",
"mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\") mocker.stopall() def test_subprocess_fork_pid0(self, mocker): \"\"\"Test fork class method process.\"\"\"",
"mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) assert mock_sys_exit.call_count ==",
"\"-b\"] # test_name = 'test_who' # test_fork = False # # mock #",
"mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, # return_value=None) # mocker.patch.object(scarlett_os.subprocess.Subprocess, '__init__', mock_init) #",
"mocker.stopall() mock_logging_debug = mocker.MagicMock(name=__name__ + \"_mock_logging_debug\") # mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug )",
") # NOTE: Bit of duplication we have going here. assert mock_sys_exit.call_count ==",
"# Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action #",
"mocker.stopall() test_command = [\"fake\", \"command\"] test_name = \"fake_command\" test_fork = True # mock",
"scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) #",
"for Scarlett Subprocess, subclass of GObject.Gobject.\"\"\" def test_check_pid_os_error(self, mocker): mocker.stopall() # mock kill_mock",
"Re-enable these guys # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') # def test_subprocess_fork_and_spawn_command(self, mock_logging_debug): # \"\"\"Test a full",
"# mock mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess,",
"scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys,",
"# test_fork = False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork')) as mock_os_fork:",
"tfork1.run() # # assert # mock_logging_debug.assert_any_call(\"command: {}\".format(test_command)) # mock_logging_debug.assert_any_call(\"stdin: {}\".format(None)) # mock_logging_debug.assert_any_call(\"stdout: {}\".format(None))",
"result is True mocker.stopall() def test_subprocess_init(self, mocker): mocker.stopall() mock_check_command_type = mocker.MagicMock( name=__name__ +",
"\"fork\", mock_fork) # NOTE: On purpose this is an invalid cmd. Should be",
"assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count == 1 assert mock_os_fork.call_count == 2 mock_os_chdir.assert_called_once_with(\"/\")",
"mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os,",
"mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\",",
"# Import module locally for testing purposes # from scarlett_os.internal.gi import gi, GLib",
"= GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') #",
"before_patch_gi_pid = gi._gi._glib.Pid # before_path_glib_spawn_async = GLib.spawn_async # before_path_child_watch_add = GLib.child_watch_add # test_pid",
"before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get applied BOTTOM to TOP #",
"== 0 mocker.stopall() def test_subprocess_fork_pid0_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command",
"\"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error ) mocker.patch.object(scarlett_os.subprocess.os, \"fork\", mock_os_fork) mocker.patch.object(scarlett_os.subprocess.sys, \"exit\",",
"mock_logging_debug): # \"\"\"Test a full run connamd of Subprocess.run()\"\"\" # mocker.stopall() # test_command",
"could be written as a function. # pylint: disable=R0201 # pylint: disable=C0111 #",
"= mocker.MagicMock(name=\"mock_logging_debug\") mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"map_type_to_command\", mock_map_type_to_command, ) mocker.patch.object(scarlett_os.subprocess.Subprocess,",
"mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog post, assert_called_once",
"is true since that # method was not added until version 3.6. This",
"map_output = s_test.map_type_to_command(test_command) # test # assert isinstance(map_output, list) # assert s_test.check_command_type(test_command) #",
"== False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert mock_os_umask.call_count ==",
"as mock_sys_exit: # noqa # with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa #",
"# before_path_child_watch_add = GLib.child_watch_add # test_pid = mocker.Mock(spec=gi._gi._glib.Pid, return_value=23241, name='Mockgi._gi._glib.Pid') # test_pid.real =",
"== None # assert tfork1.forked == False # assert mock_emit.call_count == 0 #",
"= 'test_who' # test_fork = False # # mock # with mock.patch('scarlett_os.subprocess.os.fork', mocker.Mock(name='mock_os_fork'))",
"= mocker.spy(s_test, \"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog post,",
"\"exit\", mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 =",
"builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork = False #",
"assert s_test.check_command_type(test_command) is True mock_check_command_type.assert_called_with([\"who\"]) assert not s_test.process assert not s_test.pid assert s_test.name",
"types: <class 'int'>\" ) mocker.stopall() ############################### START HERE HERON ############################################### # @mock.patch('scarlett_os.subprocess.logging.Logger.debug') #",
"assert tfork2.stderr == False assert mock_os_chdir.call_count == 1 assert mock_os_setsid.call_count == 1 assert",
"with mock.patch('scarlett_os.subprocess.os.chdir', mocker.Mock(name='mock_os_chdir')) as mock_os_chdir: # noqa # with mock.patch('scarlett_os.subprocess.os.setsid', mocker.Mock(name='mock_os_setsid')) as mock_os_setsid:",
"3.4 and 3.6 pass as we expect. But Python3.5 gives an error stating",
"mocker.stopall() def test_subprocess_fork_exception(self, mocker): \"\"\"Test fork class method process.\"\"\" mocker.stopall() test_command = [\"fake\",",
"# assert tfork1.pid != 23241 # assert tfork1.stdin == None # assert tfork1.stdout",
"= before_path_glib_spawn_async # GLib.child_watch_add = before_path_child_watch_add # mocker.stopall() # # NOTE: Decorators get",
"unpatch all of these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async",
"\"_mock_check_command_type\" ) mock_check_command_type.return_value = True mock_fork = mocker.MagicMock(name=__name__ + \"_mock_fork\") mock_logging_debug = mocker.MagicMock(name=__name__",
"test_name = \"test_who\" test_fork = False s_test = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork )",
"= mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\",",
"return_value=(test_pid, None, None, None), name='MockGLib.spawn_async') # # Mock call to child_watch # GLib.child_watch_add",
"side_effect=OSError) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\")",
"these guys # gi._gi._glib.Pid = before_patch_gi_pid # GLib.spawn_async = before_path_glib_spawn_async # GLib.child_watch_add =",
"mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE: On",
"post, assert_called_once didn't get added till 3.6?? # source: https://allanderek.github.io/posts/unittestmock-small-gotcha/ # \"So Python",
"= [\"who\", \"-b\"] # test_name = 'test_who' # test_fork = False # #",
"have done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test #",
"<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" test_subprocess ---------------------------------- \"\"\" import",
"0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\")",
"mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command,",
"mocker): # mocker.stopall() # mock_init = mocker.MagicMock(name='mock_init', # # spec=scarlett_os.subprocess.Subprocess.__init__, # autospec=scarlett_os.subprocess.Subprocess.__init__, #",
"\"map_type_to_command\") assert isinstance(s_test.map_type_to_command(test_command), list) # NOTE: According to this blog post, assert_called_once didn't",
"to import builtins)\"\"\" mocker.stopall() test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork =",
"mock_os_umask) tfork2 = scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork ) # NOTE: Bit of duplication",
"process with the given PID is running and you have the # permission",
"== None # assert tfork1.stdout == None # assert tfork1.stderr == None #",
"is True mock_logging_debug.assert_any_call(\"command: ['who']\") mock_logging_debug.assert_any_call(\"name: test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called()",
"locally for testing purposes # from scarlett_os.internal.gi import gi, GLib # # Save",
"= 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork = mocker.MagicMock(name=\"mock_os_fork\", return_value=pid) mock_sys_exit =",
"# assert tfork1.forked == False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command, #",
"# # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, # fork=test_fork) # with",
"\"test_who\" test_fork = True pid = 0 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_logging_error",
"# test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function GLib",
"done.\" # assert s_test.map_type_to_command.assert_called_once_with(test_command) spy.assert_called_once_with(test_command) # map_output = s_test.map_type_to_command(test_command) # test # assert",
"test_who\") mock_logging_debug.assert_any_call(\"forked: False\") mock_logging_debug.assert_any_call(\"process: None\") mock_logging_debug.assert_any_call(\"pid: None\") mock_fork.assert_not_called() mocker.stopall() def test_subprocess_map_type_to_command(self, mocker): \"\"\"Using",
"name='MockGLib.spawn_async') # # Mock call to child_watch # GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # #",
"\"-b\"] test_name = \"test_who\" test_fork = True pid = 0 # mock mock_logging_debug",
"scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) # NOTE: On purpose this is an invalid cmd.",
"mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"error\", mock_logging_error )",
"signal import sys from _pytest.monkeypatch import MonkeyPatch import pytest import scarlett_os # R0201",
"as excinfo: scarlett_os.subprocess.Subprocess( test_command, name=test_name, fork=test_fork, run_check_command=True ) assert ( str(excinfo.value) == \"Variable",
"test_fork = True pid = 7 # mock mock_logging_debug = mocker.MagicMock(name=\"mock_logging_debug\") mock_os_fork =",
"# # now unpatch all of these guys # gi._gi._glib.Pid = before_patch_gi_pid #",
"# assert tfork1.stdin == None # assert tfork1.stdout == None # assert tfork1.stderr",
"yield mpatch mpatch.undo() @pytest.mark.scarlettonly @pytest.mark.unittest @pytest.mark.scarlettonlyunittest class TestScarlettSubprocess(object): \"\"\"Units tests for Scarlett Subprocess,",
"name='Mockgi._gi._glib.Pid') # test_pid.real = 23241 # test_pid.close = mocker.Mock(name='Mockgi._gi._glib.Pid.close') # # Mock function",
"None # assert tfork1.forked == False # assert mock_emit.call_count == 0 # GLib.spawn_async.assert_called_once_with(test_command,",
"\"debug\", mock_logging_debug ) mocker.patch.object( scarlett_os.subprocess.Subprocess, \"check_command_type\", mock_check_command_type, ) mocker.patch.object(scarlett_os.subprocess.Subprocess, \"fork\", mock_fork) # NOTE:",
"mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask = mocker.MagicMock(name=\"mock_os_umask\") # patch mocker.patch.object( scarlett_os.subprocess.logging.Logger, \"debug\", mock_logging_debug )",
"mock_sys_exit) mocker.patch.object(scarlett_os.subprocess.os, \"chdir\", mock_os_chdir) mocker.patch.object(scarlett_os.subprocess.os, \"setsid\", mock_os_setsid) mocker.patch.object(scarlett_os.subprocess.os, \"umask\", mock_os_umask) tfork1 = scarlett_os.subprocess.Subprocess(",
"GLib.child_watch_add = mock.create_autospec(GLib.child_watch_add) # # action # tfork1 = scarlett_os.subprocess.Subprocess(test_command, # name=test_name, #",
"mocker.MagicMock(name=\"mock_os_fork\", side_effect=[pid, OSError]) mock_sys_exit = mocker.MagicMock(name=\"mock_sys_exit\") mock_os_chdir = mocker.MagicMock(name=\"mock_os_chdir\") mock_os_setsid = mocker.MagicMock(name=\"mock_os_setsid\") mock_os_umask",
"be of type array test_command = [\"who\", \"-b\"] test_name = \"test_who\" test_fork =",
"assert ( str(excinfo.value) == \"Executables and arguments must be str objects. types: <class",
"mock object, which is true since that # method was not added until",
"mocker.stopall() def test_subprocess_check_command_type(self, mocker): \"\"\"Using the mock.patch decorator (removes the need to import"
] |
[
"smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo = 'Olá, {}!\\n",
"Previsão -> {}.\\n Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora,",
"#print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 =",
"f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar",
"-> sql lista = c.fetchall() #busca todos os resultados e cria uma lista",
"item in previsao: z = 0 while z < len(diasuniq): if item[0] ==",
"mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir",
"interagir com os emails #pegar nome, contato, dia, hora e interagir com mandarEmail",
"#Para abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json') as g: data2 =",
"climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email,",
"print (pessoas) ''' ######################################### #Parte que lê o bd em sqlite3: import sqlite3",
"interagir com mandarEmail #conn.commit() # comete as alterações na tabela c.close() # fecha",
"{}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos que tenha uma boa",
"[] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1",
"' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4],",
"prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o",
"in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' + (num2[1]",
"#climanow() #Para abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json') as g: data2",
"json.load(g) #Lendo o arquivo e criando uma lista numheader = 0 previsao =",
"prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 prevfinal = '' numx",
"mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\")",
"os # print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só",
"\"agora2\") #Para mudar de pasta import os # print(os.path.abspath(os.curdir)) #só pra checar o",
"emails #pegar nome, contato, dia, hora e interagir com mandarEmail #conn.commit() # comete",
"' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta:",
"#Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para",
"while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando",
"#print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g)",
"climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD PELO ID DO OBJETO!!!!",
"#id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] +",
"# organizando tudo prevorganizada = [] for x in diasuniq: prevorganizada.append([]) y =",
"#nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] + ' '",
"import meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email = meuemail",
"if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O",
"<reponame>Daniel-H-C-P/APIClima-parqueDasDunas import datetime ###################### 1 ##################### #leitura dos arquivos json import json #Para",
"numheader = 0 previsao = [] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split(",
"'Alerta climático' corpo = 'Olá, {}!\\n Esta é a previsão para o Parque",
"mudar de pasta import os # print(os.path.abspath(os.curdir)) #só pra checar o dir base",
"climaatual #climanow() #Para abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json') as g:",
"os emails #pegar nome, contato, dia, hora e interagir com mandarEmail #conn.commit() #",
"id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com os emails #pegar",
"minhasenha #climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo()",
"dias dias = [] separador = 0 while separador < 40: daynum =",
"= [] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader",
"= sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite fazer operações no banco",
"############################## ESTAS DUAS LINHAS MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente",
"dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += ' '",
"trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email,",
"########################################## ''' Para ler diretamente dos modelos: from cadastro.models import EmailCliente pessoas =",
"pra checar o dir acima ########################################## ''' Para ler diretamente dos modelos: from",
"prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE",
"LINHAS MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado =",
"climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de dias dias = [] separador",
"in diasuniq: prevorganizada.append([]) y = 0 for item in previsao: z = 0",
"with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando uma",
"pasta import os # print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') #",
"previsao.append(climaprint) numheader +=1 #Criando uma lista de dias dias = [] separador =",
"#prevhoje() #################### 2 #################### # Mandar email climatual = climanow() prevclima = prevhoje()",
"#Criando uma lista de dias dias = [] separador = 0 while separador",
"numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje():",
"hora, climatual, prevclima): meu_email = meuemail minha_s = minhasenha #climatual = climanow() #prevclima",
"z +=1 continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in",
"import os # print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir))",
"lê o bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão",
"conn.cursor() #permite fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \")",
"arquivo clima5dias def climaprev(): with open('clima5dias.json') as g: data2 = json.load(g) #Lendo o",
"'.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += ' ' + (num1[1] + \":",
"dia, hora e interagir com mandarEmail #conn.commit() # comete as alterações na tabela",
"com mandarEmail #conn.commit() # comete as alterações na tabela c.close() # fecha a",
"Parque das Dunas após seu alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão",
"uma lista numheader = 0 previsao = [] while numheader < 40: climaprint",
"(num2[1] + \": \" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2])",
"in previsao: z = 0 while z < len(diasuniq): if item[0] == diasuniq[z]:",
"todos os resultados e cria uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0])",
"+ pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual,",
"\") #execute -> sql lista = c.fetchall() #busca todos os resultados e cria",
"acima ########################################## ''' Para ler diretamente dos modelos: from cadastro.models import EmailCliente pessoas",
"mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import os # print(os.path.abspath(os.curdir)) #só",
"climaprev(): with open('clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando",
"numheader +=1 #Criando uma lista de dias dias = [] separador = 0",
"def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o arquivo climaatual",
"e criando uma lista numheader = 0 previsao = [] while numheader <",
"dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada =",
"0 previsao = [] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description']))",
"print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar",
"- {}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos que tenha uma",
"climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o arquivo climaatual =",
"sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite",
"cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista = c.fetchall() #busca todos os",
"for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n'",
"smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo = 'Olá, {}!\\n Esta",
"Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos que tenha uma boa trilha!\\n",
"continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje",
"meuemail minha_s = minhasenha #climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587)",
"{assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de",
"#climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo",
"email climatual = climanow() prevclima = prevhoje() import smtplib from minhachaveOW import meuemail,",
"587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo",
"climanow() prevclima = prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome,",
"with open('clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando uma",
"-> {}.\\n Previsão -> {}.\\n Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome,",
"minha_s) assunto = 'Alerta climático' corpo = 'Olá, {}!\\n Esta é a previsão",
"for num1 in prevorganizada[0]: dia_hoje += ' ' + (num1[1] + \": \"",
"#print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json')",
"#dia #print(pessoa[4]) #hora alerta = pessoa[3] + ' ' + pessoa[4] alerta =",
"o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir acima ##########################################",
"num2 in num1: prevfinal+= '\\n' + (num2[1] + \": \" + num2[2]) numx",
"\" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada",
"%H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM",
"= str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo",
"-> {}.\\n Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual,",
"smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático'",
"sql lista = c.fetchall() #busca todos os resultados e cria uma lista for",
"de dias dias = [] separador = 0 while separador < 40: daynum",
"prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando",
"ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8'))",
"diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = [] for x",
"cadastro_emailcliente SET mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop",
"BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id",
"open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando uma lista",
"contato, dia, hora, climatual, prevclima): meu_email = meuemail minha_s = minhasenha #climatual =",
"smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo = 'Olá, {}!\\n Esta é a",
"import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê o",
"lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta",
"daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando",
"é a previsão para o Parque das Dunas após seu alerta({} - {}):\\n",
"prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 dia_hoje = 'Dia {}:",
"prevclima = prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato,",
"+ num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev()",
"os resultados e cria uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id",
"meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email = meuemail minha_s",
"= climanow() prevclima = prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha def",
"loop para interagir com os emails #pegar nome, contato, dia, hora e interagir",
"numx = 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in",
"\" + num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### #",
"40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) #",
"para interagir com os emails #pegar nome, contato, dia, hora e interagir com",
"lista = c.fetchall() #busca todos os resultados e cria uma lista for pessoa",
"o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir",
"os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir acima ########################################## ''' Para ler",
"= pessoa[3] + ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if",
"MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1",
"in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora",
"atual:') #print(climaatual) return climaatual #climanow() #Para abrir o arquivo clima5dias def climaprev(): with",
"prevfinal+= '\\n' + (num2[1] + \": \" + num2[2]) numx +=1 #print(\"\\nExemplo de",
"lista numheader = 0 previsao = [] while numheader < 40: climaprint =",
"separador = 0 while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1",
"FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista = c.fetchall() #busca todos",
"alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos que tenha",
"que lê o bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a",
"= EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê o bd em sqlite3:",
"= (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de dias dias",
"criando uma lista numheader = 0 previsao = [] while numheader < 40:",
"+ num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### # Mandar",
"mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD PELO ID DO",
"#contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] + ' ' + pessoa[4]",
"json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow()",
"uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}'",
"cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê",
"+ (num1[1] + \": \" + num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje()",
"checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir acima",
"prevfinal = '' numx = 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0]))",
"#################### # Mandar email climatual = climanow() prevclima = prevhoje() import smtplib from",
"EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê o bd em sqlite3: import",
"''' ######################################### #Parte que lê o bd em sqlite3: import sqlite3 conn =",
"alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD PELO ID",
"z +=1 else: z +=1 continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0])",
"dias = [] separador = 0 while separador < 40: daynum = str(previsao[int(separador)][0])",
"#conn.commit() # comete as alterações na tabela c.close() # fecha a coneção 1",
"sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite fazer operações",
"ESTAS DUAS LINHAS MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET",
"meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import",
"= {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com os emails #pegar nome,",
"+ \": \" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal)",
"{}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += ' ' + (num1[1] +",
"assunto = 'Alerta climático' corpo = 'Olá, {}!\\n Esta é a previsão para",
"json import json #Para abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as",
"return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo",
"prevorganizada = [] for x in diasuniq: prevorganizada.append([]) y = 0 for item",
"\"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS",
"conn = sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite fazer operações no",
"#Lendo o arquivo e criando uma lista numheader = 0 previsao = []",
"y = 0 for item in previsao: z = 0 while z <",
"uma lista de dias dias = [] separador = 0 while separador <",
"separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq)",
"for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia",
"import json #Para abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f:",
"z +=1 continue y +=1 prevfinal = '' numx = 0 for num1",
"contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import os",
"''' Para ler diretamente dos modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all()",
"+ ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >=",
"climatual, prevclima): meu_email = meuemail minha_s = minhasenha #climatual = climanow() #prevclima =",
"com os emails #pegar nome, contato, dia, hora e interagir com mandarEmail #conn.commit()",
"[] for x in diasuniq: prevorganizada.append([]) y = 0 for item in previsao:",
"\"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import os # print(os.path.abspath(os.curdir)) #só pra",
"prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto =",
"for x in diasuniq: prevorganizada.append([]) y = 0 for item in previsao: z",
"tabela c.close() # fecha a coneção 1 conn.close() # fecha a coneção 2",
"smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta",
">= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD PELO",
"import smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual,",
"alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ##############################",
"climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o arquivo",
"== diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 prevfinal =",
"data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir o arquivo clima5dias def",
"< len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue",
"z +=1 else: z +=1 continue y +=1 prevfinal = '' numx =",
"num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def",
"hora e interagir com mandarEmail #conn.commit() # comete as alterações na tabela c.close()",
"#comando loop para interagir com os emails #pegar nome, contato, dia, hora e",
"[] separador = 0 while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador",
"lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3])",
"def climaprev(): with open('clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e",
"pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê o bd em",
"= '' numx = 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for",
"#Parte que lê o bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria",
"das Dunas após seu alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão ->",
"import datetime ###################### 1 ##################### #leitura dos arquivos json import json #Para abrir",
"diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 prevfinal = ''",
"#################### 2 #################### # Mandar email climatual = climanow() prevclima = prevhoje() import",
"PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id =",
"#print(len(diasuniq)) # organizando tudo prevorganizada = [] for x in diasuniq: prevorganizada.append([]) y",
"#print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta =",
"in prevorganizada[0]: dia_hoje += ' ' + (num1[1] + \": \" + num1[2]",
"minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email = meuemail minha_s =",
"for num2 in num1: prevfinal+= '\\n' + (num2[1] + \": \" + num2[2])",
"item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 prevfinal",
"' + (num1[1] + \": \" + num1[2] +',') #print (dia_hoje) return dia_hoje",
"#só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o",
"#só pra checar o dir acima ########################################## ''' Para ler diretamente dos modelos:",
"from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que",
"str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada",
"< 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista",
"while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort()",
"que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem =",
"else: z +=1 continue y +=1 prevfinal = '' numx = 0 for",
"pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima)",
"###################### 1 ##################### #leitura dos arquivos json import json #Para abrir o arquivo",
"#print(climaatual) return climaatual #climanow() #Para abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json')",
"dir acima ########################################## ''' Para ler diretamente dos modelos: from cadastro.models import EmailCliente",
"= f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para",
"+=1 else: z +=1 continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for",
"= 'Olá, {}!\\n Esta é a previsão para o Parque das Dunas após",
"ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id = {}'.format(int(pessoa[0])))",
"prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia, hora,",
"as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo =",
"+=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with",
"minha_s = minhasenha #climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as",
"y +=1 prevfinal = '' numx = 0 for num1 in prevorganizada: prevfinal+=",
"('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' + (num2[1] + \": \"",
"list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = [] for x in",
"resultados e cria uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1])",
"c.fetchall() #busca todos os resultados e cria uma lista for pessoa in lista:",
"while z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z",
"+ \": \" + num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2",
"específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2",
"lista de dias dias = [] separador = 0 while separador < 40:",
"conexão c = conn.cursor() #permite fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente",
"DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit()",
"pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir",
"g: data2 = json.load(g) #Lendo o arquivo e criando uma lista numheader =",
"# comete as alterações na tabela c.close() # fecha a coneção 1 conn.close()",
"datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS LINHAS MUDAM O BD",
"#print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] + ' ' + pessoa[4] alerta",
"dia_hoje #prevhoje() #################### 2 #################### # Mandar email climatual = climanow() prevclima =",
"EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte que lê o bd",
"= 0 previsao = [] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( ))",
"climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\",",
"a conexão c = conn.cursor() #permite fazer operações no banco c.execute(\"SELECT * FROM",
"diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 dia_hoje = 'Dia",
"climatual = climanow() prevclima = prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha",
"= 'Alerta climático' corpo = 'Olá, {}!\\n Esta é a previsão para o",
"previsao: z = 0 while z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item)",
"+=1 #Criando uma lista de dias dias = [] separador = 0 while",
"arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir o",
"climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir o arquivo",
"import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite fazer",
"as g: data2 = json.load(g) #Lendo o arquivo e criando uma lista numheader",
"= minhasenha #climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp:",
"alerta = pessoa[3] + ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\")",
"contato, dia, hora e interagir com mandarEmail #conn.commit() # comete as alterações na",
"no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista",
"arquivo e criando uma lista numheader = 0 previsao = [] while numheader",
"x in diasuniq: prevorganizada.append([]) y = 0 for item in previsao: z =",
"base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir acima ########################################## ''' Para",
"= [] separador = 0 while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum)",
"data = json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return",
"previsao = [] while numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint)",
"sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor() #permite fazer operações no banco c.execute(\"SELECT",
"WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com os emails",
"= 0 while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq=",
"datetime ###################### 1 ##################### #leitura dos arquivos json import json #Para abrir o",
"mandado=0 \") #execute -> sql lista = c.fetchall() #busca todos os resultados e",
"'\\n' + (num2[1] + \": \" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição",
"num1 in prevorganizada[0]: dia_hoje += ' ' + (num1[1] + \": \" +",
"dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) #",
"#leitura dos arquivos json import json #Para abrir o arquivo climaAgora def climanow():",
"#hora alerta = pessoa[3] + ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d",
"o bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c",
"##################### #leitura dos arquivos json import json #Para abrir o arquivo climaAgora def",
"+=1 prevfinal = '' numx = 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia",
"2 #################### # Mandar email climatual = climanow() prevclima = prevhoje() import smtplib",
"for item in previsao: z = 0 while z < len(diasuniq): if item[0]",
"#climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls()",
"f: data = json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual)",
"else: z +=1 continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1",
"cria uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2])",
"return climaatual #climanow() #Para abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json') as",
"from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email",
"#print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] + ' ' +",
"#busca todos os resultados e cria uma lista for pessoa in lista: #print(pessoa)",
"O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE",
"print(os.path.abspath(os.curdir)) #só pra checar o dir acima ########################################## ''' Para ler diretamente dos",
"dos arquivos json import json #Para abrir o arquivo climaAgora def climanow(): with",
"0 for item in previsao: z = 0 while z < len(diasuniq): if",
"num1: prevfinal+= '\\n' + (num2[1] + \": \" + num2[2]) numx +=1 #print(\"\\nExemplo",
"Dunas após seu alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n",
"fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute ->",
"boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail(",
"'' numx = 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2",
"############################## #comando loop para interagir com os emails #pegar nome, contato, dia, hora",
"corpo = 'Olá, {}!\\n Esta é a previsão para o Parque das Dunas",
"< 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq))",
"dia_hoje += ' ' + (num1[1] + \": \" + num1[2] +',') #print",
"tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject:",
"+=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = [] for",
"WHERE mandado=0 \") #execute -> sql lista = c.fetchall() #busca todos os resultados",
"(str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de dias dias =",
"= prevhoje() import smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia,",
"num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### # Mandar email",
"prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' + (num2[1] + \":",
"1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com os",
"json #Para abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data",
"= c.fetchall() #busca todos os resultados e cria uma lista for pessoa in",
"continue y +=1 prevfinal = '' numx = 0 for num1 in prevorganizada:",
"SET mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para",
"diasuniq: prevorganizada.append([]) y = 0 for item in previsao: z = 0 while",
"0 while separador < 40: daynum = str(previsao[int(separador)][0]) dias.append(daynum) separador +=1 diasuniq= list(set(dias))",
"{}!\\n Esta é a previsão para o Parque das Dunas após seu alerta({}",
"#Para abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data =",
"+=1 else: z +=1 continue y +=1 prevfinal = '' numx = 0",
"0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+=",
"Esta é a previsão para o Parque das Dunas após seu alerta({} -",
"= prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto",
"#print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir o arquivo clima5dias def climaprev():",
"para o Parque das Dunas após seu alerta({} - {}):\\n Clima Atual ->",
"def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e",
"######################################### #Parte que lê o bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3')",
"de pasta import os # print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/')",
"prevorganizada.append([]) y = 0 for item in previsao: z = 0 while z",
"prevorganizada[0]: dia_hoje += ' ' + (num1[1] + \": \" + num1[2] +',')",
"def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email = meuemail minha_s = minhasenha",
"Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato,",
"climático' corpo = 'Olá, {}!\\n Esta é a previsão para o Parque das",
"item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 dia_hoje",
"#Para mudar de pasta import os # print(os.path.abspath(os.curdir)) #só pra checar o dir",
"Atual -> {}.\\n Previsão -> {}.\\n Esperamos que tenha uma boa trilha!\\n Equipe",
")) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de dias dias = []",
"with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta",
"separador +=1 diasuniq= list(set(dias)) diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = []",
"previsão para o Parque das Dunas após seu alerta({} - {}):\\n Clima Atual",
"abrir o arquivo clima5dias def climaprev(): with open('clima5dias.json') as g: data2 = json.load(g)",
"o arquivo e criando uma lista numheader = 0 previsao = [] while",
"smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo = 'Olá, {}!\\n Esta é",
"arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o",
"open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima",
"dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra checar o dir acima ########################################## '''",
"prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\",",
"{}.\\n Previsão -> {}.\\n Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia,",
"prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' + (num2[1] +",
"operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql",
"meu_email = meuemail minha_s = minhasenha #climatual = climanow() #prevclima = prevhoje() with",
"mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email = meuemail minha_s = minhasenha #climatual",
"\"hoje2\", \"agora2\") #Para mudar de pasta import os # print(os.path.abspath(os.curdir)) #só pra checar",
"dos modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' #########################################",
"= conn.cursor() #permite fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0",
"em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c = conn.cursor()",
"z = 0 while z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z",
"clima5dias def climaprev(): with open('clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo",
"with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description']",
"OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ##############################",
"= data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual #climanow() #Para abrir o arquivo clima5dias",
"= [] for x in diasuniq: prevorganizada.append([]) y = 0 for item in",
"na tabela c.close() # fecha a coneção 1 conn.close() # fecha a coneção",
"modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) ''' ######################################### #Parte",
"40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de",
"após seu alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos",
"== diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1 dia_hoje =",
"+=1 continue y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]:",
"= 0 for num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1:",
"(dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### # Mandar email climatual = climanow()",
"diretamente dos modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas) '''",
"numheader < 40: climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma",
"{}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' + (num2[1] + \": \" +",
"dia, hora, climatual, prevclima): meu_email = meuemail minha_s = minhasenha #climatual = climanow()",
"as f: data = json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:')",
"#permite fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute",
"nome, contato, dia, hora e interagir com mandarEmail #conn.commit() # comete as alterações",
"DUAS LINHAS MUDAM O BD PELO ID DO OBJETO!!!! c.execute('UPDATE cadastro_emailcliente SET mandado",
"#pegar nome, contato, dia, hora e interagir com mandarEmail #conn.commit() # comete as",
"smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s) assunto = 'Alerta climático' corpo = 'Olá,",
"z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1",
"c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista = c.fetchall()",
"'Olá, {}!\\n Esta é a previsão para o Parque das Dunas após seu",
"o Parque das Dunas após seu alerta({} - {}):\\n Clima Atual -> {}.\\n",
"open('clima5dias.json') as g: data2 = json.load(g) #Lendo o arquivo e criando uma lista",
"= 0 for item in previsao: z = 0 while z < len(diasuniq):",
"len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y",
"# mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import os # print(os.path.abspath(os.curdir))",
"pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4])",
"#execute -> sql lista = c.fetchall() #busca todos os resultados e cria uma",
"= 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com",
"organizando tudo prevorganizada = [] for x in diasuniq: prevorganizada.append([]) y = 0",
"data2 = json.load(g) #Lendo o arquivo e criando uma lista numheader = 0",
"{}'.format(int(pessoa[0]))) conn.commit() ############################## #comando loop para interagir com os emails #pegar nome, contato,",
"# print(os.path.abspath(os.curdir)) #só pra checar o dir acima ########################################## ''' Para ler diretamente",
"c = conn.cursor() #permite fazer operações no banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE",
"a previsão para o Parque das Dunas após seu alerta({} - {}):\\n Clima",
"checar o dir acima ########################################## ''' Para ler diretamente dos modelos: from cadastro.models",
"#print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3]",
"+',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### # Mandar email climatual",
"#print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = [] for x in diasuniq: prevorganizada.append([])",
"c.execute('UPDATE cadastro_emailcliente SET mandado = 1 WHERE id = {}'.format(int(pessoa[0]))) conn.commit() ############################## #comando",
"e cria uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome",
"comete as alterações na tabela c.close() # fecha a coneção 1 conn.close() #",
"= json.load(f) #Lendo o arquivo climaatual = data['weather'][0]['description'] #print('Clima atual:') #print(climaatual) return climaatual",
"+ (num2[1] + \": \" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\")",
"o arquivo clima5dias def climaprev(): with open('clima5dias.json') as g: data2 = json.load(g) #Lendo",
"#cria a conexão c = conn.cursor() #permite fazer operações no banco c.execute(\"SELECT *",
"\": \" + num2[2]) numx +=1 #print(\"\\nExemplo de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return",
"'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += ' ' + (num1[1]",
"* FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista = c.fetchall() #busca",
"ler diretamente dos modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print (pessoas)",
"if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else: z +=1 continue y +=1",
"exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as g:",
"smtplib from minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima):",
"# print(os.path.abspath(os.curdir)) #só pra checar o dir base os.chdir('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/') # print(os.path.abspath(os.curdir)) #só pra",
"de exibição específica:\") #print(prevorganizada[2][0][2]) #print(prevfinal) return prevorganizada #climaprev() def prevhoje(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/clima5dias.json') as",
"= meuemail minha_s = minhasenha #climatual = climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com',",
"seu alerta({} - {}):\\n Clima Atual -> {}.\\n Previsão -> {}.\\n Esperamos que",
"(pessoas) ''' ######################################### #Parte que lê o bd em sqlite3: import sqlite3 conn",
"= 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += ' ' +",
"pessoa[3] + ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now()",
"+= ' ' + (num1[1] + \": \" + num1[2] +',') #print (dia_hoje)",
"climaprint = (str(data2['list'][numheader]['dt_txt']).split( )) climaprint.append(str(data2['list'][numheader]['weather'][0]['description'])) previsao.append(climaprint) numheader +=1 #Criando uma lista de dias",
"hora, climatual, prevclima) mensagem = f'Subject: {assunto}\\n\\n{corpo}' smtp.sendmail( meu_email, contato, mensagem.encode('utf-8')) # mandaremail(\"Daniel\",",
"abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f)",
"arquivos json import json #Para abrir o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json')",
"Mandar email climatual = climanow() prevclima = prevhoje() import smtplib from minhachaveOW import",
"= datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS",
"return dia_hoje #prevhoje() #################### 2 #################### # Mandar email climatual = climanow() prevclima",
"mensagem.encode('utf-8')) # mandaremail(\"Daniel\", \"<EMAIL>\", \"hoje2\", \"agora2\") #Para mudar de pasta import os #",
"as alterações na tabela c.close() # fecha a coneção 1 conn.close() # fecha",
"Para ler diretamente dos modelos: from cadastro.models import EmailCliente pessoas = EmailCliente.objects.all() print",
"#print (dia_hoje) return dia_hoje #prevhoje() #################### 2 #################### # Mandar email climatual =",
"y +=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje +=",
"{}.\\n Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima)",
"alterações na tabela c.close() # fecha a coneção 1 conn.close() # fecha a",
"banco c.execute(\"SELECT * FROM cadastro_emailcliente WHERE mandado=0 \") #execute -> sql lista =",
"tudo prevorganizada = [] for x in diasuniq: prevorganizada.append([]) y = 0 for",
"= climanow() #prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo()",
"o arquivo climaAgora def climanow(): with open('/home/daniel/webdev/tcc2019/APIClima-parqueDasDunas/ClimaTempo/climaAgora.json') as f: data = json.load(f) #Lendo",
"(num1[1] + \": \" + num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() ####################",
"#print(pessoa[1]) #nome #print(pessoa[2]) #contato #print(pessoa[3]) #dia #print(pessoa[4]) #hora alerta = pessoa[3] + '",
"e interagir com mandarEmail #conn.commit() # comete as alterações na tabela c.close() #",
"' ' + (num1[1] + \": \" + num1[2] +',') #print (dia_hoje) return",
"0 while z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1 else:",
"Esperamos que tenha uma boa trilha!\\n Equipe ClimaTempo'.format(nome, dia, hora, climatual, prevclima) mensagem",
"\": \" + num1[2] +',') #print (dia_hoje) return dia_hoje #prevhoje() #################### 2 ####################",
"bd em sqlite3: import sqlite3 conn = sqlite3.connect('db.sqlite3') #cria a conexão c =",
"= json.load(g) #Lendo o arquivo e criando uma lista numheader = 0 previsao",
"+=1 continue y +=1 prevfinal = '' numx = 0 for num1 in",
"datetime.datetime.strptime(alerta, \"%Y-%m-%d %H:%M:%S\") if datetime.datetime.now() >= alerta: mandaemail(pessoa[1],pessoa[2],pessoa[3],pessoa[4], climatual, prevclima) ############################## ESTAS DUAS",
"minhachaveOW import meuemail, minhasenha def mandaemail(nome, contato, dia, hora, climatual, prevclima): meu_email =",
"diasuniq.sort() #print(diasuniq) #print(len(diasuniq)) # organizando tudo prevorganizada = [] for x in diasuniq:",
"#print(pessoa[4]) #hora alerta = pessoa[3] + ' ' + pessoa[4] alerta = datetime.datetime.strptime(alerta,",
"conn.commit() ############################## #comando loop para interagir com os emails #pegar nome, contato, dia,",
"+=1 dia_hoje = 'Dia {}: '.format(prevorganizada[0][0][0]) for num1 in prevorganizada[0]: dia_hoje += '",
"mandarEmail #conn.commit() # comete as alterações na tabela c.close() # fecha a coneção",
"# Mandar email climatual = climanow() prevclima = prevhoje() import smtplib from minhachaveOW",
"in num1: prevfinal+= '\\n' + (num2[1] + \": \" + num2[2]) numx +=1",
"num1 in prevorganizada: prevfinal+= ('\\n\\nDia {}:'.format(prevorganizada[numx][0][0])) for num2 in num1: prevfinal+= '\\n' +",
"1 ##################### #leitura dos arquivos json import json #Para abrir o arquivo climaAgora",
"uma lista for pessoa in lista: #print(pessoa) #print(pessoa[0]) #id #print(pessoa[1]) #nome #print(pessoa[2]) #contato",
"o dir acima ########################################## ''' Para ler diretamente dos modelos: from cadastro.models import",
"#prevclima = prevhoje() with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(meu_email, minha_s)",
"= 0 while z < len(diasuniq): if item[0] == diasuniq[z]: prevorganizada[z].append(item) z +=1",
"prevclima): meu_email = meuemail minha_s = minhasenha #climatual = climanow() #prevclima = prevhoje()"
] |
[
"class GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports =",
"(name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1] != b'\\x2B': continue if len(response)",
"(回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK if",
"{\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39",
"not ok: print(gravity) continue else: results[name] = gravity break return {\"success\": True, \"data\":",
"binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return",
"results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位",
"serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1',",
"if not ok: print(gravity) continue else: results[name] = gravity break return {\"success\": True,",
"binary): result = '' for data in binary: result = result + chr(data)",
"result = result + chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end =",
"= self.convert_gravity(response) if not ok: print(gravity) continue else: results[name] = gravity break return",
"is %s' % (name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1] != b'\\x2B':",
"\"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D",
"time import binascii from enum import Enum class GravityUtils: Code = Enum('Code', 'MARK",
"20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def",
"return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6])",
"39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = '' for data in binary:",
"0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B':",
"# \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) }",
"port in self.ports.items(): while True: port.flush() response = port.read(8) print('read data from %s,",
"# \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) #",
"__init__(self): # 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B',",
"serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2',",
"def __init__(self): # 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\":",
"\"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary):",
"serial import time import binascii from enum import Enum class GravityUtils: Code =",
"b'\\x2B': continue if len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity =",
"for name, port in self.ports.items(): while True: port.flush() response = port.read(8) print('read data",
"convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A':",
"else: results[name] = gravity break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为:",
"= { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C',",
"self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克",
"def read_gravity(self): results = {} for name, port in self.ports.items(): while True: port.flush()",
"= self.convert_binary(binary[1:6]) result = raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为:",
"33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary):",
"raw = self.convert_binary(binary[1:6]) result = raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值",
"= bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok: print(gravity) continue else:",
"import serial import time import binascii from enum import Enum class GravityUtils: Code",
"raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34",
"CHECK') def __init__(self): # 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), #",
"# \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), #",
"} self.offset = 100 # 原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\"",
"timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 -> 20 33 33 30 34",
"binascii.b2a_hex(response))) if len(response) == 0 or response[:1] != b'\\x2B': continue if len(response) <",
"False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result",
"False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw - self.offset return True, result",
"self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\":",
"\"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\":",
"# 原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self):",
"# \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), #",
"GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports = {",
"# coding:utf-8 import serial import time import binascii from enum import Enum class",
"serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0',",
"self.convert_gravity(response) if not ok: print(gravity) continue else: results[name] = gravity break return {\"success\":",
"\"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\":",
"return int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time() print('调用耗时:%f\\n\\n' % (end -",
"把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result",
"continue if len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response)",
"\"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\":",
"- self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39",
"-> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results =",
"\"\"\" def convert_binary(self, binary): result = '' for data in binary: result =",
"# \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 -> 20 33",
"!= b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw",
"# \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), #",
"self.convert_binary(binary[1:6]) result = raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20",
"from enum import Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self):",
"= Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports = { # \"g_sensor_1\":",
"serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 ->",
"100 # 原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def",
"timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03)",
"int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time() print('调用耗时:%f\\n\\n' % (end - begin))",
"result + chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time() print('调用耗时:%f\\n\\n'",
"30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for name, port",
"# 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04),",
"timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03),",
"len(response) == 0 or response[:1] != b'\\x2B': continue if len(response) < 8: response",
"bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok: print(gravity) continue else: results[name]",
"in self.ports.items(): while True: port.flush() response = port.read(8) print('read data from %s, result",
"33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self,",
"2B 20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\"",
"if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw",
"\"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39 0D 0A",
"return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\"",
"print('read data from %s, result is %s' % (name, binascii.b2a_hex(response))) if len(response) ==",
"!= b'\\x2B': continue if len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity",
"% (name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1] != b'\\x2B': continue if",
"Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A',",
"return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34",
"port.flush() response = port.read(8) print('read data from %s, result is %s' % (name,",
"从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = '' for data in binary: result",
"Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports",
"binary: result = result + chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end",
"# \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 #",
"timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04)",
"result is %s' % (name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1] !=",
"'MARK CHECK') def __init__(self): # 打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04),",
"response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok: print(gravity) continue else: results[name] =",
"convert_binary(self, binary): result = '' for data in binary: result = result +",
"import Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口",
"= '' for data in binary: result = result + chr(data) return int(result)",
"read_gravity(self): results = {} for name, port in self.ports.items(): while True: port.flush() response",
"response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok: print(gravity) continue",
"from %s, result is %s' % (name, binascii.b2a_hex(response))) if len(response) == 0 or",
"33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for",
"def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8] !=",
"原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results",
"timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03),",
"if len(response) == 0 or response[:1] != b'\\x2B': continue if len(response) < 8:",
"response[:1] != b'\\x2B': continue if len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok,",
"\"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\":",
"len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not",
"True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def",
"serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset =",
"\"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset",
"data in binary: result = result + chr(data) return int(result) begin = time.time()",
"self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw - self.offset return True, result \"\"\"",
"result = raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33",
"Code = Enum('Code', 'MARK CHECK') def __init__(self): # 打开端口 self.ports = { #",
"把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A",
"if len(response) < 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if",
"print(gravity) continue else: results[name] = gravity break return {\"success\": True, \"data\": results} \"\"\"",
"True: port.flush() response = port.read(8) print('read data from %s, result is %s' %",
"== 0 or response[:1] != b'\\x2B': continue if len(response) < 8: response =",
"b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw =",
"binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw -",
"self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result =",
"= port.read(8) print('read data from %s, result is %s' % (name, binascii.b2a_hex(response))) if",
"timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 -> 20",
"39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1]",
"33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for name,",
"%s, result is %s' % (name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1]",
"enum import Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK') def __init__(self): #",
"gravity = self.convert_gravity(response) if not ok: print(gravity) continue else: results[name] = gravity break",
"\"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for name, port in self.ports.items():",
"results = {} for name, port in self.ports.items(): while True: port.flush() response =",
"34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = '' for data in",
"= raw - self.offset return True, result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33",
"34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for name, port in",
"= gravity break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20",
"!= b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw - self.offset",
"results[name] = gravity break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B",
"binascii from enum import Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK') def",
"\"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8]",
"result = '' for data in binary: result = result + chr(data) return",
"self.ports.items(): while True: port.flush() response = port.read(8) print('read data from %s, result is",
"8: response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok: print(gravity)",
"import binascii from enum import Enum class GravityUtils: Code = Enum('Code', 'MARK CHECK')",
"\"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量",
"def convert_binary(self, binary): result = '' for data in binary: result = result",
"name, port in self.ports.items(): while True: port.flush() response = port.read(8) print('read data from",
"其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return",
"for data in binary: result = result + chr(data) return int(result) begin =",
"ok: print(gravity) continue else: results[name] = gravity break return {\"success\": True, \"data\": results}",
"b'\\x0D\\x0A': return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw - self.offset return",
"import time import binascii from enum import Enum class GravityUtils: Code = Enum('Code',",
"33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = '' for",
"gravity break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33",
"< 8: response = bytearray(response) response.extend(port.read(8)) ok, gravity = self.convert_gravity(response) if not ok:",
"response = port.read(8) print('read data from %s, result is %s' % (name, binascii.b2a_hex(response)))",
"= result + chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time()",
"if binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False,",
"0 or response[:1] != b'\\x2B': continue if len(response) < 8: response = bytearray(response)",
"continue else: results[name] = gravity break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据",
"{ # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04),",
"34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if",
"timeout=0.03), # \"g_sensor_3\": serial.Serial(port='/dev/ttyUSB0', timeout=0.03), # \"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100",
"数据样例为: 2B 20 33 33 34 39 0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符)",
"0D 0A 其中,第一位是标示位2B,第2-6位为重力数据,最后两位是校验位 0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] !=",
"in binary: result = result + chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity())",
"serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 -> 20 33 33 30",
"chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time() print('调用耗时:%f\\n\\n' % (end",
"打开端口 self.ports = { # \"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), #",
"= 100 # 原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\"",
"result \"\"\" 把原始二进制数据,转换为对应的十进制数值 数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self,",
"33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = '' for data",
"'' for data in binary: result = result + chr(data) return int(result) begin",
"or response[:1] != b'\\x2B': continue if len(response) < 8: response = bytearray(response) response.extend(port.read(8))",
"serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D',",
"20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {}",
"= {} for name, port in self.ports.items(): while True: port.flush() response = port.read(8)",
"\"g_sensor_4\": serial.Serial(port='/dev/ttyUSB2', timeout=0.03) } self.offset = 100 # 原始重力值读数的位移差量 -> 20 33 33",
"coding:utf-8 import serial import time import binascii from enum import Enum class GravityUtils:",
"ok, gravity = self.convert_gravity(response) if not ok: print(gravity) continue else: results[name] = gravity",
"0D 0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False,",
"通过USB转串口,读取重力感应器重力值数据 \"\"\" def read_gravity(self): results = {} for name, port in self.ports.items(): while",
"port.read(8) print('read data from %s, result is %s' % (name, binascii.b2a_hex(response))) if len(response)",
"\"\"\" def read_gravity(self): results = {} for name, port in self.ports.items(): while True:",
"+ chr(data) return int(result) begin = time.time() print(GravityUtils().read_gravity()) end = time.time() print('调用耗时:%f\\n\\n' %",
"timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03),",
"0A (回车换行符) \"\"\" def convert_gravity(self, binary): if binary[:1] != b'\\x2B': return False, self.Code.MARK",
"20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result = ''",
"data from %s, result is %s' % (name, binascii.b2a_hex(response))) if len(response) == 0",
"\"g_sensor_1\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3A', timeout=0.04), # \"g_sensor_2\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3B', timeout=0.04), # \"g_sensor_3\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\":",
"self.offset = 100 # 原始重力值读数的位移差量 -> 20 33 33 30 34 \"\"\" 通过USB转串口,读取重力感应器重力值数据",
"while True: port.flush() response = port.read(8) print('read data from %s, result is %s'",
"数据样例为: 20 33 33 34 39 从右到左依次为\"个十百千万\",单位是克 \"\"\" def convert_binary(self, binary): result =",
"%s' % (name, binascii.b2a_hex(response))) if len(response) == 0 or response[:1] != b'\\x2B': continue",
"serial.Serial(port='/dev/tty.usbserial-FT2J03F3C', timeout=0.04), # \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3',",
"break return {\"success\": True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33",
"return False, self.Code.CHECK raw = self.convert_binary(binary[1:6]) result = raw - self.offset return True,",
"True, \"data\": results} \"\"\" 把串口读到的原始二进制数据,转换为实际的重力值数据 数据样例为: 2B 20 33 33 34 39 0D",
"{} for name, port in self.ports.items(): while True: port.flush() response = port.read(8) print('read",
"# \"g_sensor_4\": serial.Serial(port='/dev/tty.usbserial-FT2J03F3D', timeout=0.04) # \"g_sensor_1\": serial.Serial(port='/dev/ttyUSB1', timeout=0.03), # \"g_sensor_2\": serial.Serial(port='/dev/ttyUSB3', timeout=0.03), #",
"binary[:1] != b'\\x2B': return False, self.Code.MARK if binary[6:8] != b'\\x0D\\x0A': return False, self.Code.CHECK",
"<reponame>zcjl/python-works<gh_stars>0 # coding:utf-8 import serial import time import binascii from enum import Enum"
] |
[
"!= '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool = True): pass",
"= None): if identity is None: self._identity = self.NAME else: self._identity = identity",
"True while replaced: replaced = False for subgraph in self.match_function(G): replacement = self.replace_function(G,",
"def _match(self, G, node, edge): del G, edge return isinstance(node, self.__node_class) class Matcher(ABC):",
"set_identity: bool = True): replaced = True while replaced: replaced = False for",
"str = None): super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match) def",
"self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str",
"set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) ->",
"match(self, G: GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self,",
"from typing import Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph import GraphView,",
"match(self, G: GraphView, set_identity: bool = True): for match_instance in self.matches: match_instance.match(G, False)",
"Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def",
"can be inherited to group matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher],",
"False for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph)",
"def match(self, G: GraphView, set_identity: bool = True): for match_instance in self.matches: match_instance.match(G,",
"replacement) else: raise TypeError(\"unexcepted return value from replace_function\") replaced = True break if",
"'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool",
"self._identity = identity def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__':",
"subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement,",
"BSD license. See the LICENSE file for details. from abc import ABC, abstractmethod",
"self.__node_class = node_class def _match(self, G, node, edge): del G, edge return isinstance(node,",
"replaced = False for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if not",
"= '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str = None): if identity",
"= self.NAME else: self._identity = identity def set_identity(self, G): if hasattr(G, 'graph_identity') and",
"for details. from abc import ABC, abstractmethod from typing import Generator, Sequence from",
"typing import Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node,",
"from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name)",
"Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) -> Node:",
"replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement)",
"G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from replace_function\")",
"Node: pass def match(self, G: GraphView, set_identity: bool = True): replaced = True",
"# This can be used to define groups of matches to be selected",
"self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool = True):",
"True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None, None]:",
"This can be used to define groups of matches to be selected #",
"super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView,",
"ABC, abstractmethod from typing import Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph",
"match(self, G: GraphView, set_identity: bool = True): replaced = True while replaced: replaced",
"under the terms # of the BSD license. See the LICENSE file for",
"import GraphIdentity from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name,",
"matches to be selected # from the command line # It also can",
"from abc import ABC, abstractmethod from typing import Generator, Sequence from graph.graph_identity import",
"graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self,",
"replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass def match(self, G: GraphView, set_identity:",
"if set_identity: self.set_identity(G) # This can be used to define groups of matches",
"hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity:",
"matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity)",
"name, node_class): super().__init__(name) self.__node_class = node_class def _match(self, G, node, edge): del G,",
"self.NAME else: self._identity = identity def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity",
"used to define groups of matches to be selected # from the command",
"None): super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self, G:",
"MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def _match(self,",
"GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView)",
"match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G: GraphView,",
"modified and distributed under the terms # of the BSD license. See the",
"bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView,",
"Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str = None):",
"to group matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str =",
"node_class def _match(self, G, node, edge): del G, edge return isinstance(node, self.__node_class) class",
"@abstractmethod def match(self, G: GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod",
"if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView,",
"to be selected # from the command line # It also can be",
"bool = True): replaced = True while replaced: replaced = False for subgraph",
"utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class",
"Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool = True): for match_instance in",
"together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches",
"node, edge): del G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__'",
"GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView)",
"license. See the LICENSE file for details. from abc import ABC, abstractmethod from",
"DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str = None): if identity is None:",
"can be used to define groups of matches to be selected # from",
"See the LICENSE file for details. from abc import ABC, abstractmethod from typing",
"__init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def _match(self, G, node, edge): del",
"rights reserved. # This software may be modified and distributed under the terms",
"terms # of the BSD license. See the LICENSE file for details. from",
"G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph:",
"# All rights reserved. # This software may be modified and distributed under",
"# This software may be modified and distributed under the terms # of",
"inherited to group matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str",
"and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool =",
"G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from replace_function\") replaced = True break",
"node_class): super().__init__(name) self.__node_class = node_class def _match(self, G, node, edge): del G, edge",
"def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def _match(self, G, node, edge):",
"= True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None,",
"if identity is None: self._identity = self.NAME else: self._identity = identity def set_identity(self,",
"GraphView, set_identity: bool = True): for match_instance in self.matches: match_instance.match(G, False) if set_identity:",
"G: GraphView, set_identity: bool = True): replaced = True while replaced: replaced =",
"_match(self, G, node, edge): del G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME",
"True): replaced = True while replaced: replaced = False for subgraph in self.match_function(G):",
"pass def match(self, G: GraphView, set_identity: bool = True): replaced = True while",
"'__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool = True): pass class",
"del G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION =",
"to define groups of matches to be selected # from the command line",
"reserved. # This software may be modified and distributed under the terms #",
"command line # It also can be inherited to group matches together class",
"return value from replace_function\") replaced = True break if set_identity: self.set_identity(G) # This",
"self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity:",
"is None: self._identity = self.NAME else: self._identity = identity def set_identity(self, G): if",
"NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str = None): if",
"@abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass def match(self, G:",
"edge): del G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION",
"replace_function\") replaced = True break if set_identity: self.set_identity(G) # This can be used",
"not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value",
"also can be inherited to group matches together class MatchGroup(Matcher): def __init__(self, *args:",
"Sequence from graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode):",
"None, None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass",
"def match(self, G: GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def",
"def match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G:",
"distributed under the terms # of the BSD license. See the LICENSE file",
"if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return",
"GraphIdentity from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class):",
"line # It also can be inherited to group matches together class MatchGroup(Matcher):",
"identity: str = None): if identity is None: self._identity = self.NAME else: self._identity",
"import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class =",
"G: GraphView, subgraph: GraphView) -> Node: pass def match(self, G: GraphView, set_identity: bool",
"isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from replace_function\") replaced =",
"class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str =",
"pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass",
"'__NOT_SET__' def __init__(self, identity: str = None): if identity is None: self._identity =",
"TypeError(\"unexcepted return value from replace_function\") replaced = True break if set_identity: self.set_identity(G) #",
"file for details. from abc import ABC, abstractmethod from typing import Generator, Sequence",
"class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod",
"match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool = True): for match_instance",
"class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def _match(self, G,",
"Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from replace_function\") replaced = True",
"= '__NOT_SET__' def __init__(self, identity: str = None): if identity is None: self._identity",
"def replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass def match(self, G: GraphView,",
"self.matches.append(match) def match(self, G: GraphView, set_identity: bool = True): for match_instance in self.matches:",
"from the command line # It also can be inherited to group matches",
"abc import ABC, abstractmethod from typing import Generator, Sequence from graph.graph_identity import GraphIdentity",
"return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self,",
"This software may be modified and distributed under the terms # of the",
"be inherited to group matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity:",
"'__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity: str = None): if identity is",
"from graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node, MatchNode class MatchNodeType(MatchNode): def",
"= list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool",
"pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass def match(self,",
"and distributed under the terms # of the BSD license. See the LICENSE",
"# of the BSD license. See the LICENSE file for details. from abc",
"= False for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement:",
"def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def",
"else: raise TypeError(\"unexcepted return value from replace_function\") replaced = True break if set_identity:",
"self.set_identity(G) # This can be used to define groups of matches to be",
"MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class def _match(self, G, node,",
"details. from abc import ABC, abstractmethod from typing import Generator, Sequence from graph.graph_identity",
"while replaced: replaced = False for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph)",
"group matches together class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str = None):",
"of matches to be selected # from the command line # It also",
"def match(self, G: GraphView, set_identity: bool = True): replaced = True while replaced:",
"replaced = True while replaced: replaced = False for subgraph in self.match_function(G): replacement",
"class MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches =",
"the LICENSE file for details. from abc import ABC, abstractmethod from typing import",
"self._identity = self.NAME else: self._identity = identity def set_identity(self, G): if hasattr(G, 'graph_identity')",
"Copyright (C) 2019 GreenWaves Technologies # All rights reserved. # This software may",
"Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node, MatchNode class",
"G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G: GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher):",
"for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif",
"elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from replace_function\") replaced",
"GraphView) -> Node: pass def match(self, G: GraphView, set_identity: bool = True): replaced",
"self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise",
"set_identity: bool = True): for match_instance in self.matches: match_instance.match(G, False) if set_identity: self.set_identity(G)",
"# It also can be inherited to group matches together class MatchGroup(Matcher): def",
"__init__(self, identity: str = None): if identity is None: self._identity = self.NAME else:",
"GreenWaves Technologies # All rights reserved. # This software may be modified and",
"identity def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod",
"G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self, G:",
"DefaultMatcher(Matcher): @abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def",
"subgraph: GraphView) -> Node: pass def match(self, G: GraphView, set_identity: bool = True):",
"LICENSE file for details. from abc import ABC, abstractmethod from typing import Generator,",
"identity is None: self._identity = self.NAME else: self._identity = identity def set_identity(self, G):",
"selected # from the command line # It also can be inherited to",
"None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) -> Node: pass def",
"None): if identity is None: self._identity = self.NAME else: self._identity = identity def",
"= True): replaced = True while replaced: replaced = False for subgraph in",
"may be modified and distributed under the terms # of the BSD license.",
"else: self._identity = identity def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity !=",
"G: GraphView, set_identity: bool = True): pass class DefaultMatcher(Matcher): @abstractmethod def match_function(self, G:",
"define groups of matches to be selected # from the command line #",
"# Copyright (C) 2019 GreenWaves Technologies # All rights reserved. # This software",
"= None): super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self,",
"def __init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches = list(args) def",
"2019 GreenWaves Technologies # All rights reserved. # This software may be modified",
"add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool = True): for",
"abstractmethod from typing import Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph import",
"= node_class def _match(self, G, node, edge): del G, edge return isinstance(node, self.__node_class)",
"the terms # of the BSD license. See the LICENSE file for details.",
"GraphView, Node, MatchNode class MatchNodeType(MatchNode): def __init__(self, name, node_class): super().__init__(name) self.__node_class = node_class",
"str = None): if identity is None: self._identity = self.NAME else: self._identity =",
"raise TypeError(\"unexcepted return value from replace_function\") replaced = True break if set_identity: self.set_identity(G)",
"# from the command line # It also can be inherited to group",
"the command line # It also can be inherited to group matches together",
"def __init__(self, identity: str = None): if identity is None: self._identity = self.NAME",
"isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def __init__(self, identity:",
"= identity def set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity)",
"subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted",
"break if set_identity: self.set_identity(G) # This can be used to define groups of",
"@abstractmethod def match_function(self, G: GraphView) -> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self,",
"(C) 2019 GreenWaves Technologies # All rights reserved. # This software may be",
"None: self._identity = self.NAME else: self._identity = identity def set_identity(self, G): if hasattr(G,",
"GraphView, set_identity: bool = True): replaced = True while replaced: replaced = False",
"replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else: raise TypeError(\"unexcepted return value from",
"value from replace_function\") replaced = True break if set_identity: self.set_identity(G) # This can",
"software may be modified and distributed under the terms # of the BSD",
"from replace_function\") replaced = True break if set_identity: self.set_identity(G) # This can be",
"super().__init__(name) self.__node_class = node_class def _match(self, G, node, edge): del G, edge return",
"*args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches = list(args) def add_match(self, match:",
"set_identity(self, G): if hasattr(G, 'graph_identity') and self._identity != '__NOT_SET__': G.graph_identity.fusions.append(self._identity) @abstractmethod def match(self,",
"-> Generator[GraphView, None, None]: pass @abstractmethod def replace_function(self, G: GraphView, subgraph: GraphView) ->",
"Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher):",
"= True while replaced: replaced = False for subgraph in self.match_function(G): replacement =",
"MatchGroup(Matcher): def __init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches = list(args)",
"edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__' def",
"of the BSD license. See the LICENSE file for details. from abc import",
"list(args) def add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool =",
"be used to define groups of matches to be selected # from the",
"G, node, edge): del G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME =",
"be modified and distributed under the terms # of the BSD license. See",
"= self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph, replacement) else:",
"Technologies # All rights reserved. # This software may be modified and distributed",
"-> Node: pass def match(self, G: GraphView, set_identity: bool = True): replaced =",
"replaced = True break if set_identity: self.set_identity(G) # This can be used to",
"identity: str = None): super().__init__(identity) self.matches = list(args) def add_match(self, match: Matcher): self.matches.append(match)",
"self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node): G.replace_fragment(subgraph,",
"It also can be inherited to group matches together class MatchGroup(Matcher): def __init__(self,",
"import Generator, Sequence from graph.graph_identity import GraphIdentity from utils.graph import GraphView, Node, MatchNode",
"def add_match(self, match: Matcher): self.matches.append(match) def match(self, G: GraphView, set_identity: bool = True):",
"G: GraphView, set_identity: bool = True): for match_instance in self.matches: match_instance.match(G, False) if",
"= True break if set_identity: self.set_identity(G) # This can be used to define",
"the BSD license. See the LICENSE file for details. from abc import ABC,",
"All rights reserved. # This software may be modified and distributed under the",
"replaced: replaced = False for subgraph in self.match_function(G): replacement = self.replace_function(G, subgraph) if",
"in self.match_function(G): replacement = self.replace_function(G, subgraph) if not replacement: G.remove_fragment(subgraph) elif isinstance(replacement, Node):",
"import ABC, abstractmethod from typing import Generator, Sequence from graph.graph_identity import GraphIdentity from",
"__init__(self, *args: Sequence[Matcher], identity: str = None): super().__init__(identity) self.matches = list(args) def add_match(self,",
"be selected # from the command line # It also can be inherited",
"GraphView, subgraph: GraphView) -> Node: pass def match(self, G: GraphView, set_identity: bool =",
"groups of matches to be selected # from the command line # It",
"set_identity: self.set_identity(G) # This can be used to define groups of matches to",
"True break if set_identity: self.set_identity(G) # This can be used to define groups",
"G, edge return isinstance(node, self.__node_class) class Matcher(ABC): NAME = '__NOT_SET__' DESCRIPTION = '__NOT_SET__'"
] |
[
"load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension}",
"#--------- Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents =",
"ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded') for",
"{extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified cog. async def",
"settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified",
"tools.logging import ABLog from discord.ext import commands #--------- Variables ---------# INTENTS = discord.Intents.all()",
"help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog. async def load(ctx, extension):",
"async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to",
"loaded') @client.command() #Reloads specified cog. async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID:",
"reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension}",
"Code ---------# @client.command() #Loads specified cog. async def load(ctx, extension): if ctx.message.author.id ==",
"discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code",
"if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded')",
"#The heart of the bot. #--------- Libaries ---------# import discord, os, settings from",
"heart of the bot. #--------- Libaries ---------# import discord, os, settings from tools.logging",
"@client.command() #Unloads specified cog. async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}')",
"settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog.",
"---------# import discord, os, settings from tools.logging import ABLog from discord.ext import commands",
"ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity) client.run(settings.Token) #Gets the bot",
"#--------- Libaries ---------# import discord, os, settings from tools.logging import ABLog from discord.ext",
"{extension} was reloaded') @client.command() #Unloads specified cog. async def unload(ctx, extension): if ctx.message.author.id",
"if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded')",
"activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity)",
"= discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity) client.run(settings.Token)",
"= settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified",
"custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has",
"in os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event",
"os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes",
"ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified cog. async def reload(ctx, extension):",
"the custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user}",
"async def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The",
"cog. async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await",
"discord, os, settings from tools.logging import ABLog from discord.ext import commands #--------- Variables",
"cog {extension} was unloaded') for filename in os.listdir('./cogs'): #Initial load of all cogs.",
"import commands #--------- Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes,",
"client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified cog.",
"def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog",
"specified cog. async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\")",
"extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was",
"if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status. async def on_ready():",
"import discord, os, settings from tools.logging import ABLog from discord.ext import commands #---------",
"of the bot. #--------- Libaries ---------# import discord, os, settings from tools.logging import",
"#Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the",
"settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified",
"cog. async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await",
"---------# @client.command() #Loads specified cog. async def load(ctx, extension): if ctx.message.author.id == settings.AdminID:",
"async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The",
"specified cog. async def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\")",
"commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads",
"unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension}",
"ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified cog. async",
"on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await",
"filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status. async def on_ready(): activity",
"def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog",
"await ctx.send(f'The cog {extension} was unloaded') for filename in os.listdir('./cogs'): #Initial load of",
"== settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded') for filename",
"#--------- Code ---------# @client.command() #Loads specified cog. async def load(ctx, extension): if ctx.message.author.id",
"@client.command() #Reloads specified cog. async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}')",
"client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog. async def load(ctx, extension): if",
"await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified cog. async def unload(ctx,",
"{filename}\") @client.event #Changes the custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing)",
"---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None)",
"bot. #--------- Libaries ---------# import discord, os, settings from tools.logging import ABLog from",
"specified cog. async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\")",
"ctx.send(f'The cog {extension} was unloaded') for filename in os.listdir('./cogs'): #Initial load of all",
"commands #--------- Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents",
"{extension} was unloaded') for filename in os.listdir('./cogs'): #Initial load of all cogs. if",
"ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command()",
"unloaded') for filename in os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}')",
"import ABLog from discord.ext import commands #--------- Variables ---------# INTENTS = discord.Intents.all() client",
"settings from tools.logging import ABLog from discord.ext import commands #--------- Variables ---------# INTENTS",
"was reloaded') @client.command() #Unloads specified cog. async def unload(ctx, extension): if ctx.message.author.id ==",
"discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity) client.run(settings.Token) #Gets",
"= INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog. async def",
"{extension} was loaded') @client.command() #Reloads specified cog. async def reload(ctx, extension): if ctx.message.author.id",
"was unloaded') for filename in os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'):",
"type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity) client.run(settings.Token) #Gets the",
"os, settings from tools.logging import ABLog from discord.ext import commands #--------- Variables ---------#",
"INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help')",
"#Reloads specified cog. async def reload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading",
"{extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified cog. async def",
"{extension}\") await ctx.send(f'The cog {extension} was unloaded') for filename in os.listdir('./cogs'): #Initial load",
"#Changes the custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\")",
"cog. async def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await",
"client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified cog.",
"cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status. async def",
"client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status. async def on_ready(): activity =",
"the bot. #--------- Libaries ---------# import discord, os, settings from tools.logging import ABLog",
"@client.event #Changes the custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot",
"== settings.AdminID: client.reload_extension(f'cogs.{extension}') ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads",
"Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS,",
"ABLog from discord.ext import commands #--------- Variables ---------# INTENTS = discord.Intents.all() client =",
"ABLog(f\"Reloading {extension}\") await ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified cog. async",
"extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was",
"all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status. async",
"#Unloads specified cog. async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading",
"= discord.Intents.all() client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #---------",
"cog {extension} was loaded') @client.command() #Reloads specified cog. async def reload(ctx, extension): if",
"intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog. async",
"extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was",
"ctx.send(f'The cog {extension} was reloaded') @client.command() #Unloads specified cog. async def unload(ctx, extension):",
"#Loads specified cog. async def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading",
"was loaded') @client.command() #Reloads specified cog. async def reload(ctx, extension): if ctx.message.author.id ==",
"async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The",
"status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected",
"ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded') for filename in os.listdir('./cogs'): #Initial",
"client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded') for filename in os.listdir('./cogs'):",
"filename in os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\")",
"from discord.ext import commands #--------- Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix",
"def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog",
"settings.AdminID: client.unload_extension(f'cogs.{extension}') ABLog(f\"Unloading {extension}\") await ctx.send(f'The cog {extension} was unloaded') for filename in",
"Libaries ---------# import discord, os, settings from tools.logging import ABLog from discord.ext import",
"cog {extension} was reloaded') @client.command() #Unloads specified cog. async def unload(ctx, extension): if",
"of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom status.",
"if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded')",
"from tools.logging import ABLog from discord.ext import commands #--------- Variables ---------# INTENTS =",
"client = commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------#",
"ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command()",
"await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads specified cog. async def reload(ctx,",
"@client.command() #Loads specified cog. async def load(ctx, extension): if ctx.message.author.id == settings.AdminID: client.load_extension(f'cogs.{extension}')",
"= commands.Bot(command_prefix = settings.ABPrefixes, intents = INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command()",
"discord.ext import commands #--------- Variables ---------# INTENTS = discord.Intents.all() client = commands.Bot(command_prefix =",
"loaded.\") print(f'{client.user} has connected to Discord!') await client.change_presence(activity=activity) client.run(settings.Token) #Gets the bot online!",
"reloaded') @client.command() #Unloads specified cog. async def unload(ctx, extension): if ctx.message.author.id == settings.AdminID:",
"== settings.AdminID: client.load_extension(f'cogs.{extension}') ABLog(f\"Loading {extension}\") await ctx.send(f'The cog {extension} was loaded') @client.command() #Reloads",
"INTENTS, help_command=None) client.remove_command('help') #--------- Code ---------# @client.command() #Loads specified cog. async def load(ctx,",
"print(f\"Loaded {filename}\") @client.event #Changes the custom status. async def on_ready(): activity = discord.Activity(name=settings.Custom_Status,",
"def on_ready(): activity = discord.Activity(name=settings.Custom_Status, type=discord.ActivityType.playing) ABLog(\"Bot loaded.\") print(f'{client.user} has connected to Discord!')",
"load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded {filename}\") @client.event #Changes the custom",
"for filename in os.listdir('./cogs'): #Initial load of all cogs. if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') print(f\"Loaded"
] |
[
"that supports edit diffs and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__",
"import EditTypes __title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a package that supports",
"= \"mwedittypes is a package that supports edit diffs and action detection for",
".mwedittypes import EditTypes __title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a package that",
"detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ = \"MIT License\"",
"a package that supports edit diffs and action detection for Wikipedia\" __url__ =",
"__title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a package that supports edit diffs",
"is a package that supports edit diffs and action detection for Wikipedia\" __url__",
"diffs and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__",
"from .mwedittypes import EditTypes __title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a package",
"for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ = \"MIT License\" __all__",
"action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ = \"MIT",
"\"mwedittypes\" __summary__ = \"mwedittypes is a package that supports edit diffs and action",
"\"mwedittypes is a package that supports edit diffs and action detection for Wikipedia\"",
"package that supports edit diffs and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\"",
"supports edit diffs and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ =",
"<reponame>geohci/edit-types from .mwedittypes import EditTypes __title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a",
"and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ =",
"EditTypes __title__ = \"mwedittypes\" __summary__ = \"mwedittypes is a package that supports edit",
"__summary__ = \"mwedittypes is a package that supports edit diffs and action detection",
"Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ = \"MIT License\" __all__ =",
"= \"mwedittypes\" __summary__ = \"mwedittypes is a package that supports edit diffs and",
"__url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\" __license__ = \"MIT License\" __all__ = [\"EditTypes\"]",
"edit diffs and action detection for Wikipedia\" __url__ = \"https://github.com/geohci/edit-types\" __version__ = \"1.1.5\""
] |
[
"\"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air'",
"'oxygen': 0.21 } # using standard temperature and pressure TEMPERATURE = 273.15 #",
"CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1",
"= 1.0 * 100000 # Pa or kg/(ms^2) # %% reaction # (4",
"6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen']",
"of isobutane needs 6.5 mols of oxygen to burn completly # or 1",
"of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume)",
"get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for",
"1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10",
"constants AVOGARDRO = 6.02214076 * 10 ** 23 # 1/mol BOLTZMANN = 1.380649",
"%% atomic masses in kg/mol or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR",
"OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\"",
"= get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does",
"air' ) def main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME =",
"mols of oxygen to burn completly # or 1 mol of oxygen can",
"* 10 ** 23 # 1/mol BOLTZMANN = 1.380649 * 10 ** -23",
"def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air):",
"10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21",
"mol of isobutane needs 6.5 mols of oxygen to burn completly # or",
"/ OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume =",
"* 1000:.3f} liters of air' f' are needed for a stoichiometric reaction of'",
"/ 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR",
"get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not",
"meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume",
"to be cubic meters m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS *",
"1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR =",
"calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V: V = NRT/p returns in",
"isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns",
"masses in kg/mol or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16",
"** 23 # 1/mol BOLTZMANN = 1.380649 * 10 ** -23 # J/K",
"of' f' {air_volume * 1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME =",
"needed for a stoichiometric reaction of' f' {air_volume * 1000:.3f} liters of air'",
"(UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V: V",
"needs 6.5 mols of oxygen to burn completly # or 1 mol of",
"liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print(",
"get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume):",
"gas law and - a simple chemical reaction But still, no warranty. \"\"\"",
"meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\"",
"ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME = 3.095 / 1000 #",
"* PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved",
"1.0 * 100000 # Pa or kg/(ms^2) # %% reaction # (4 *",
"10 * H) + 6.5 * O_2 --react--> 5 * H_2O + 4",
"= 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen /",
"not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f'",
"H) + 6.5 * O_2 --react--> 5 * H_2O + 4 * CO2",
"and pressure TEMPERATURE = 273.15 # K PRESSURE = 1.0 * 100000 #",
"/ 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR",
"a stoichiometric reaction of' f' {air_volume * 1000:.3f} liters of air' ) def",
"K PRESSURE = 1.0 * 100000 # Pa or kg/(ms^2) # %% reaction",
"a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters of isobutane' ) def",
"get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return",
"for N: N = PV/(RT) expects `volume` to be cubic meters m^3 \"\"\"",
"# %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 } # using",
"returns in `V` in cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS *",
"0.79, 'oxygen': 0.21 } # using standard temperature and pressure TEMPERATURE = 273.15",
"kg/mol or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16 / 1000",
"def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def",
"mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen =",
"= get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane)",
"= isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print(",
"burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return",
"= NRT solved for V: V = NRT/p returns in `V` in cubic",
"`V` in cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) /",
"# (4 * C + 10 * H) + 6.5 * O_2 --react-->",
"cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return",
"1 mol of isobutane needs 6.5 mols of oxygen to burn completly #",
"* H) + 6.5 * O_2 --react--> 5 * H_2O + 4 *",
"* O_2 --react--> 5 * H_2O + 4 * CO2 # 1 mol",
"\"\"\" # %% constants AVOGARDRO = 6.02214076 * 10 ** 23 # 1/mol",
"meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane)",
"kg/(ms^2) # %% reaction # (4 * C + 10 * H) +",
"= NRT solved for N: N = PV/(RT) expects `volume` to be cubic",
"N: N = PV/(RT) expects `volume` to be cubic meters m^3 \"\"\" return",
"100000 # Pa or kg/(ms^2) # %% reaction # (4 * C +",
"for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are needed",
"PV/(RT) expects `volume` to be cubic meters m^3 \"\"\" return (volume * PRESSURE)",
"16 / 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14 / 1000",
"oxygen can completely burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5",
"PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO",
"= 0.1 / 1000 # m^3 AIR_VOLUME = 3.095 / 1000 # m^3",
"air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane =",
"5 * H_2O + 4 * CO2 # 1 mol of isobutane needs",
"* OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters",
"isobutane needs 6.5 mols of oxygen to burn completly # or 1 mol",
"a combination of the - ideal gas law and - a simple chemical",
"mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume",
"for V: V = NRT/p returns in `V` in cubic meters m^3 \"\"\"",
"# or 1 mol of oxygen can completely burn (1 / 6.5) mols",
"# using standard temperature and pressure TEMPERATURE = 273.15 # K PRESSURE =",
"1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\"",
"CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79,",
"of' f' {isobutane_volume * 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not",
"* TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V: V =",
"def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N: N = PV/(RT) expects",
"} # using standard temperature and pressure TEMPERATURE = 273.15 # K PRESSURE",
"1000:.3f} liters of air' f' are needed for a stoichiometric reaction of' f'",
"NRT solved for V: V = NRT/p returns in `V` in cubic meters",
"1000:.3f} liters of isobutane' f' are needed for a stoichiometric reaction of' f'",
"# %% atomic masses in kg/mol or units/atom CARBON_MOLAR = 12 / 1000",
"AVOGARDRO = 6.02214076 * 10 ** 23 # 1/mol BOLTZMANN = 1.380649 *",
"def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane",
"return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns",
"= 1.380649 * 10 ** -23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS",
"1/mol BOLTZMANN = 1.380649 * 10 ** -23 # J/K or Nm/K or",
"no warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076 * 10 ** 23",
"for a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters of isobutane' )",
"liters of air' ) def main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3",
"12 / 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1 / 1000",
"environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 } # using standard temperature",
"+ 4 * CO2 # 1 mol of isobutane needs 6.5 mols of",
"\"\"\" pV = NRT solved for N: N = PV/(RT) expects `volume` to",
"or kg/(ms^2) # %% reaction # (4 * C + 10 * H)",
"standard temperature and pressure TEMPERATURE = 273.15 # K PRESSURE = 1.0 *",
"def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def",
"(kgm^2)/(molKs^2) # %% atomic masses in kg/mol or units/atom CARBON_MOLAR = 12 /",
"= NRT/p returns in `V` in cubic meters m^3 \"\"\" return (mols *",
"# 1 mol of isobutane needs 6.5 mols of oxygen to burn completly",
"container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are needed for",
"meters m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols):",
"--react--> 5 * H_2O + 4 * CO2 # 1 mol of isobutane",
"BOLTZMANN = 1.380649 * 10 ** -23 # J/K or Nm/K or (kgm^2)/(Ks^2)",
"be cubic meters m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE)",
"isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols =",
"return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N:",
"the - ideal gas law and - a simple chemical reaction But still,",
"- a simple chemical reaction But still, no warranty. \"\"\" # %% constants",
"solved for N: N = PV/(RT) expects `volume` to be cubic meters m^3",
"1000 # m^3 AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME) if",
"stoichiometric reaction of' f' {air_volume * 1000:.3f} liters of air' ) def main():",
"pV = NRT solved for N: N = PV/(RT) expects `volume` to be",
"m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen",
"NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 *",
"OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen",
"for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are needed",
"mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic",
"of oxygen can completely burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO =",
"return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) *",
"# K PRESSURE = 1.0 * 100000 # Pa or kg/(ms^2) # %%",
"volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume):",
"print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of",
"expects `volume` to be cubic meters m^3 \"\"\" return (volume * PRESSURE) /",
"(4 * C + 10 * H) + 6.5 * O_2 --react--> 5",
"Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) #",
"print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of",
"air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV",
"(kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic",
"But still, no warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076 * 10",
"calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container",
"completely burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air):",
"= 273.15 # K PRESSURE = 1.0 * 100000 # Pa or kg/(ms^2)",
"meters m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols):",
"pV = NRT solved for V: V = NRT/p returns in `V` in",
"Pa or kg/(ms^2) # %% reaction # (4 * C + 10 *",
"UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses",
"m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def",
"of air' ) def main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME",
"C + 10 * H) + 6.5 * O_2 --react--> 5 * H_2O",
"= AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in",
"OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols)",
"or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol or units/atom CARBON_MOLAR = 12",
"completly # or 1 mol of oxygen can completely burn (1 / 6.5)",
"mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account",
"f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are needed for a stoichiometric reaction",
"can completely burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def",
"return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols *",
"return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols)",
"or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2)",
"m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def",
"%% constants AVOGARDRO = 6.02214076 * 10 ** 23 # 1/mol BOLTZMANN =",
"cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def",
"isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) *",
"1.380649 * 10 ** -23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS =",
"temperature and pressure TEMPERATURE = 273.15 # K PRESSURE = 1.0 * 100000",
"def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved",
"needed for a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters of isobutane'",
"TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols",
"not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f'",
"\"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols",
"0.21 } # using standard temperature and pressure TEMPERATURE = 273.15 # K",
"= calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air)",
"{ 'nitrogen': 0.79, 'oxygen': 0.21 } # using standard temperature and pressure TEMPERATURE",
"NRT/p returns in `V` in cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS",
"\"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume)",
"= 1 / 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4 *",
"ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME",
"isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume)",
"volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are needed for a",
"def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols",
"calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N: N = PV/(RT) expects `volume`",
"for a stoichiometric reaction of' f' {air_volume * 1000:.3f} liters of air' )",
"f' {isobutane_volume * 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account",
"volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are needed for a",
"CO2 # 1 mol of isobutane needs 6.5 mols of oxygen to burn",
"isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return",
"still, no warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076 * 10 **",
"UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols):",
"/ PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols /",
"isobutane' f' are needed for a stoichiometric reaction of' f' {air_volume * 1000:.3f}",
"10 ** -23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO *",
"oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters",
"+ 6.5 * O_2 --react--> 5 * H_2O + 4 * CO2 #",
"{air_volume * 1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME = 0.1 /",
"or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %%",
"to burn completly # or 1 mol of oxygen can completely burn (1",
"return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV =",
"air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume =",
"'nitrogen': 0.79, 'oxygen': 0.21 } # using standard temperature and pressure TEMPERATURE =",
"6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen']",
"chemical reaction But still, no warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076",
"# Pa or kg/(ms^2) # %% reaction # (4 * C + 10",
"air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen)",
"= calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\"",
"print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are needed for a stoichiometric",
"= PV/(RT) expects `volume` to be cubic meters m^3 \"\"\" return (volume *",
"= oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns",
"m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\"",
"mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\"",
"AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT",
"in cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE",
"= { 'nitrogen': 0.79, 'oxygen': 0.21 } # using standard temperature and pressure",
"= 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME) if __name__ == '__main__': main()",
"liters of air' f' are needed for a stoichiometric reaction of' f' {isobutane_volume",
"def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters",
"of oxygen to burn completly # or 1 mol of oxygen can completely",
"a simple chemical reaction But still, no warranty. \"\"\" # %% constants AVOGARDRO",
"* BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol or",
"f' are needed for a stoichiometric reaction of' f' {air_volume * 1000:.3f} liters",
"of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen):",
"oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic",
"cubic meters m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def",
"V = NRT/p returns in `V` in cubic meters m^3 \"\"\" return (mols",
"f' are needed for a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters",
"are needed for a stoichiometric reaction of' f' {air_volume * 1000:.3f} liters of",
"1 mol of oxygen can completely burn (1 / 6.5) mols of isobutane",
"or 1 mol of oxygen can completely burn (1 / 6.5) mols of",
") def main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME = 3.095",
"BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol or units/atom",
"* UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def",
"calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane",
"# m^3 AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME) if __name__",
"oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume = get_air_volume_of_oxygen(oxygen_volume) return air_volume def isobutane_vol_to_air_vol(volume_isobutane):",
"* 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for container",
"\"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane'",
"= 16 / 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14 /",
"PRESSURE = 1.0 * 100000 # Pa or kg/(ms^2) # %% reaction #",
"units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR =",
"AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N: N = PV/(RT)",
"# %% constants AVOGARDRO = 6.02214076 * 10 ** 23 # 1/mol BOLTZMANN",
") def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f}",
"* 100000 # Pa or kg/(ms^2) # %% reaction # (4 * C",
"H_2O + 4 * CO2 # 1 mol of isobutane needs 6.5 mols",
"J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK) or",
"* AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV =",
"main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME = 3.095 / 1000",
"1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR =",
"oxygen to burn completly # or 1 mol of oxygen can completely burn",
"= 14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR",
"pressure TEMPERATURE = 273.15 # K PRESSURE = 1.0 * 100000 # Pa",
"* CO2 # 1 mol of isobutane needs 6.5 mols of oxygen to",
"are needed for a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters of",
"= 12 / 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1 /",
"reaction of' f' {air_volume * 1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME",
"m^3 AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME) if __name__ ==",
"14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR #",
"4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = {",
"of the - ideal gas law and - a simple chemical reaction But",
"print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are needed for a stoichiometric",
"\"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV",
"* TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return",
"J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol or units/atom CARBON_MOLAR =",
"0.1 / 1000 # m^3 AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME)",
"+ 10 * H) + 6.5 * O_2 --react--> 5 * H_2O +",
"def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V: V = NRT/p returns",
"m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return",
"calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f}",
"+ 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen':",
"air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane =",
"def print_needed_isobutane(air_volume): \"\"\"does not account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters",
"def air_volume_for_isobutane_mols(mols): \"\"\"returns cubic meters m^3\"\"\" oxygen_mols = oxygen_needed_for_isobutane(mols) oxygen_volume = calc_mol_to_volume(oxygen_mols) air_volume",
"<gh_stars>0 \"\"\" a combination of the - ideal gas law and - a",
"V: V = NRT/p returns in `V` in cubic meters m^3 \"\"\" return",
"(1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air",
"TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V: V = NRT/p",
"\"\"\" pV = NRT solved for V: V = NRT/p returns in `V`",
"NRT solved for N: N = PV/(RT) expects `volume` to be cubic meters",
"combination of the - ideal gas law and - a simple chemical reaction",
"or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR",
"air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def",
"# J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN # J/(molK)",
"6.5 mols of oxygen to burn completly # or 1 mol of oxygen",
"HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4",
"def main(): ISOBUTANE_VOLUME = 0.1 / 1000 # m^3 AIR_VOLUME = 3.095 /",
"/ 1000 # m^3 AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME)",
"= 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME =",
"N = PV/(RT) expects `volume` to be cubic meters m^3 \"\"\" return (volume",
"in `V` in cubic meters m^3 \"\"\" return (mols * UNIVERSAL_GAS * TEMPERATURE)",
"account for container volume\"\"\" print( f'{air_vol_to_isobutane_vol(air_volume) * 1000:.3f} liters of isobutane' f' are",
"* 10 ** -23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO",
"1 / 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR",
"atomic masses in kg/mol or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR =",
"%% reaction # (4 * C + 10 * H) + 6.5 *",
"reaction of' f' {isobutane_volume * 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does",
"/ 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air *",
"\"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen)",
"* 1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME = 0.1 / 1000",
"f' {air_volume * 1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME = 0.1",
"stoichiometric reaction of' f' {isobutane_volume * 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume):",
"1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment",
"* C + 10 * H) + 6.5 * O_2 --react--> 5 *",
"reaction # (4 * C + 10 * H) + 6.5 * O_2",
"air' f' are needed for a stoichiometric reaction of' f' {isobutane_volume * 1000:.3f}",
"- ideal gas law and - a simple chemical reaction But still, no",
"(mols * UNIVERSAL_GAS * TEMPERATURE) / PRESSURE def oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO",
"/ AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N: N =",
"{isobutane_volume * 1000:.3f} liters of isobutane' ) def print_needed_isobutane(air_volume): \"\"\"does not account for",
"AIR_VOLUME = 3.095 / 1000 # m^3 print_needed_air(ISOBUTANE_VOLUME) print_needed_isobutane(AIR_VOLUME) if __name__ == '__main__':",
"and - a simple chemical reaction But still, no warranty. \"\"\" # %%",
"simple chemical reaction But still, no warranty. \"\"\" # %% constants AVOGARDRO =",
"return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen =",
"of air' f' are needed for a stoichiometric reaction of' f' {isobutane_volume *",
"ideal gas law and - a simple chemical reaction But still, no warranty.",
"oxygen_needed_for_isobutane(mols): return mols * OXYGEN_TO_ISOBUTANE_RATIO def isobutane_needed_for_oxygen(mols): return mols / OXYGEN_TO_ISOBUTANE_RATIO def air_volume_for_isobutane_mols(mols):",
"4 * CO2 # 1 mol of isobutane needs 6.5 mols of oxygen",
"/ 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %%",
"reaction But still, no warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076 *",
"cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen = calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return",
"-23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN #",
"account for container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are",
"23 # 1/mol BOLTZMANN = 1.380649 * 10 ** -23 # J/K or",
"liters of isobutane' f' are needed for a stoichiometric reaction of' f' {air_volume",
"O_2 --react--> 5 * H_2O + 4 * CO2 # 1 mol of",
"\"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic",
"* HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 }",
"/ 1000 NITROGEN_MOLAR = 14 / 1000 ISOBUTANE_MOLAR = 4 * CARBON_MOLAR +",
"calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters m^3\"\"\" volume_oxygen = get_oxygen_volume_of_air(volume_air) mols_oxygen",
"warranty. \"\"\" # %% constants AVOGARDRO = 6.02214076 * 10 ** 23 #",
"* CARBON_MOLAR + 10 * HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen':",
"= 6.02214076 * 10 ** 23 # 1/mol BOLTZMANN = 1.380649 * 10",
"** -23 # J/K or Nm/K or (kgm^2)/(Ks^2) UNIVERSAL_GAS = AVOGARDRO * BOLTZMANN",
"return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def get_air_volume_of_oxygen(oxygen): return oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\"",
"* H_2O + 4 * CO2 # 1 mol of isobutane needs 6.5",
"AVOGARDRO * BOLTZMANN # J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol",
"return air_volume def isobutane_vol_to_air_vol(volume_isobutane): \"\"\"returns cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane)",
"using standard temperature and pressure TEMPERATURE = 273.15 # K PRESSURE = 1.0",
"273.15 # K PRESSURE = 1.0 * 100000 # Pa or kg/(ms^2) #",
"10 ** 23 # 1/mol BOLTZMANN = 1.380649 * 10 ** -23 #",
"1000:.3f} liters of air' ) def main(): ISOBUTANE_VOLUME = 0.1 / 1000 #",
"law and - a simple chemical reaction But still, no warranty. \"\"\" #",
"\"\"\" a combination of the - ideal gas law and - a simple",
"AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 } # using standard temperature and",
"OXYGEN_MOLAR = 16 / 1000 HYDROGEN_MOLAR = 1 / 1000 NITROGEN_MOLAR = 14",
"mol of oxygen can completely burn (1 / 6.5) mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO",
"TEMPERATURE = 273.15 # K PRESSURE = 1.0 * 100000 # Pa or",
"# J/(molK) or (kgm^2)/(molKs^2) # %% atomic masses in kg/mol or units/atom CARBON_MOLAR",
"= calc_volume_to_mol(volume_oxygen) mols_isobutane = isobutane_needed_for_oxygen(mols_oxygen) return calc_mol_to_volume(mols_isobutane) def print_needed_air(isobutane_volume): \"\"\"does not account for",
"6.5 * O_2 --react--> 5 * H_2O + 4 * CO2 # 1",
"# 1/mol BOLTZMANN = 1.380649 * 10 ** -23 # J/K or Nm/K",
"in kg/mol or units/atom CARBON_MOLAR = 12 / 1000 OXYGEN_MOLAR = 16 /",
"f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are needed for a stoichiometric reaction",
"solved for V: V = NRT/p returns in `V` in cubic meters m^3",
"`volume` to be cubic meters m^3 \"\"\" return (volume * PRESSURE) / (UNIVERSAL_GAS",
"* 1000:.3f} liters of isobutane' f' are needed for a stoichiometric reaction of'",
"burn completly # or 1 mol of oxygen can completely burn (1 /",
"# %% reaction # (4 * C + 10 * H) + 6.5",
"%% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 } # using standard",
"(volume * PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT",
"mols of isobutane OXYGEN_TO_ISOBUTANE_RATIO = 6.5 def get_oxygen_volume_of_air(air): return air * AIR_COMPOSITION_BY_VOLUME['oxygen'] def",
"of isobutane' f' are needed for a stoichiometric reaction of' f' {air_volume *",
"/ (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for V:",
"PRESSURE) / (UNIVERSAL_GAS * TEMPERATURE) def calc_mol_to_volume(mols): \"\"\" pV = NRT solved for",
"6.02214076 * 10 ** 23 # 1/mol BOLTZMANN = 1.380649 * 10 **",
"HYDROGEN_MOLAR # %% environment AIR_COMPOSITION_BY_VOLUME = { 'nitrogen': 0.79, 'oxygen': 0.21 } #",
"oxygen / AIR_COMPOSITION_BY_VOLUME['oxygen'] def calc_volume_to_mol(volume): \"\"\" pV = NRT solved for N: N",
"container volume\"\"\" print( f'{isobutane_vol_to_air_vol(isobutane_volume) * 1000:.3f} liters of air' f' are needed for",
"cubic meters m^3\"\"\" mols_isobutane = calc_volume_to_mol(volume_isobutane) return air_volume_for_isobutane_mols(mols_isobutane) def air_vol_to_isobutane_vol(volume_air): \"\"\"returns cubic meters"
] |
[
"out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of extinction",
"Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter)",
"self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51",
"0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02",
"extinction within a small disk as samples INPUT: lcen, bcen - Galactic longitude",
"Orion parts of the Drimmel map to other data INPUT: l,b- Galactic longitude",
"0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d",
"self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2=",
"Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75)",
"0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2.",
"cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find",
"et al. 2003 2003A&A...409..205D # ############################################################################### import copy import numpy from scipy.ndimage import",
"of the different components OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy (IAS)",
"mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke & Lebovksy",
"coordinates X= X+self._xsun #Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y)",
"maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions of COBE",
"filter to return the extinction in sf10= (True) if True, use the Schlafly",
"samples INPUT: lcen, bcen - Galactic longitude and latitude of the center of",
"Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj =",
"tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun",
"Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.)",
"Drimmel03 dust map INPUT: filter= filter to return the extinction in sf10= (True)",
"A #b) relative amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext))",
"disk, spiral, and Orion parts and a 'distance stretch' applied to the model",
"to other data INPUT: l,b- Galactic longitude and latitude in degree dist -",
"consists of #a) overall amplitude A #b) relative amplitude fd/A, fs/A #c) distance",
"nearest pixel in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi,",
"zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi",
"b- Galactic latitude (deg) d- distance (kpc) can be array norescale= (False) if",
"self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk=",
"Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD)",
"INPUT: lcen, bcen - Galactic longitude and latitude of the center of the",
"# Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD #",
"numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]=",
"optimize try: import healpy except ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util",
"self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of",
"#Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE",
"out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the",
"distribution of extinction within a small disk as samples INPUT: lcen, bcen -",
"_fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch= numpy.exp(pars[3]) model_ext= drim(l,b,dist*dist_stretch,_fd=fd,_fs=fs,_fo=fo)",
"# Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit",
"parts and a 'distance stretch' applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY:",
"<reponame>jan-rybizki/mwdust ############################################################################### # # Drimmel03: extinction model from Drimmel et al. 2003 2003A&A...409..205D",
"self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2=",
"mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180.",
"for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir,",
"import healpy except ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel",
"fit PURPOSE: fit the amplitudes of the disk, spiral, and Orion parts of",
"yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) <",
"Drimmel map to other data INPUT: l,b- Galactic longitude and latitude in degree",
"+ float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj",
"map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars beyond the local",
"return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of",
"small disk as samples INPUT: lcen, bcen - Galactic longitude and latitude of",
"True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion grid is different",
"self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2,",
"self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) -",
"a HEALPIX grid with nside=256, to somewhat # oversample the Drimmel resolution nside=",
"tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if sl != 0.:",
"from Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import copy import numpy from",
"that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map",
"if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl))",
"the Drimmel map to other data INPUT: l,b- Galactic longitude and latitude in",
"X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y)",
"d- distance (kpc) can be array norescale= (False) if True, don't apply re-scalings",
"+ float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk &",
"amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd=",
"Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X=",
"def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic",
"self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2,",
"avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map for",
"numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d)",
"amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs)",
"healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction)",
"pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def",
"NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map INPUT: filter= filter to return",
"numpy from scipy.ndimage import map_coordinates from scipy import optimize try: import healpy except",
"self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk=",
"ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\"",
"- Bovy (IAS) \"\"\" #Fit consists of #a) overall amplitude A #b) relative",
"Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the",
"map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk,",
"to somewhat # oversample the Drimmel resolution nside= 256 # Find the pixels",
"self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] ==",
"zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y)",
"tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun",
"to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS)",
"from other global grids, so has its own dmax dmax= 100. if b",
"INPUT: filter= filter to return the extinction in sf10= (True) if True, use",
"dmax dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl",
"scipy.ndimage import map_coordinates from scipy import optimize try: import healpy except ImportError: pass",
"the different components OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\"",
"Lebovksy (1985); if sf10, first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else:",
"different from other global grids, so has its own dmax dmax= 100. if",
"xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.)",
"import aebv from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import",
"optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext):",
"dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl",
"self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori,",
"map_coordinates from scipy import optimize try: import healpy except ImportError: pass from mwdust.util.extCurves",
"Galactocentric coordinates X= X+self._xsun #Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) <",
"tdmax < dmax: dmax= tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if",
"fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes of the disk, spiral, and",
"zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75)",
"- Written - Bovy (IAS) \"\"\" #Fit consists of #a) overall amplitude A",
"and extinction value HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\" # Convert",
"tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax=",
"self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc,",
"INPUT: l,b- Galactic longitude and latitude in degree dist - distance in kpc",
"if self._filter is None: # From Rieke & Lebovksy (1985); if sf10, first",
"self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME:",
"b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax =",
"Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll()",
"_DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME:",
"Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps",
"Galactic longitude (deg) b- Galactic latitude (deg) d- distance (kpc) can be array",
"numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015",
"model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE:",
"(IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b",
"radius - radius of the disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area",
"dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1)",
"l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\"",
"0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if sl != 0.:",
"sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD)",
"within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for pixels",
"#Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05,",
"- distance in kpc radius - radius of the disk (deg) OUTPUT: (pixarea,extinction)",
"isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b for Drimmel dust",
"> 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None:",
"0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc=",
"for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb=",
"nside= 256 # Find the pixels at this resolution that fall within the",
"#Go to Galactocentric coordinates X= X+self._xsun #Stars beyond the local grid #Orion globIndx=",
"0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate",
"elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax=",
"if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2.",
"= Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X)",
"We pixelize the map with a HEALPIX grid with nside=256, to somewhat #",
"COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl))",
"numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in",
"extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes",
"try: import healpy except ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util import",
"healpy except ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from",
"== 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not",
"fit the amplitudes of the disk, spiral, and Orion parts of the Drimmel",
"0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05,",
"self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx]",
"Query the HEALPIX map for pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs))",
"this resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the",
"copy import numpy from scipy.ndimage import map_coordinates from scipy import optimize try: import",
"if numpy.sum(globIndx) > 0: #Orion grid is different from other global grids, so",
"from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from",
"to return the extinction in sf10= (True) if True, use the Schlafly &",
"(deg) b- Galactic latitude (deg) d- distance (kpc) can be array norescale= (False)",
"fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd=",
"# oversample the Drimmel resolution nside= 256 # Find the pixels at this",
"Bovy (IAS) \"\"\" # Convert the disk center to a HEALPIX vector vec=",
"copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun",
"of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi=",
"\"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and",
"self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk,",
"Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) <",
"== 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if",
"Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2.",
"(deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq rad and extinction value",
"tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if cl < 0.:",
"< dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori=",
"kpc radius - radius of the disk (deg) OUTPUT: (pixarea,extinction) - arrays of",
"self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax",
"as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit consists of",
"tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates",
"is different from other global grids, so has its own dmax dmax= 100.",
"< 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj =",
"al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust",
"to Galactocentric coordinates X= X+self._xsun #Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun)",
"True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant',",
"2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map INPUT:",
"0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return",
"(1985); if sf10, first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return",
"numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and",
"amplitude A #b) relative amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\",
"of the center of the disk (deg) dist - distance in kpc radius",
"map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx)",
"local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0:",
"disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs): # Get glon",
"locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2.",
"self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local",
"sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel",
"extinction HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray):",
"SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk",
"longitude and latitude of the center of the disk (deg) dist - distance",
"in sq rad and extinction value HISTORY: 2015-03-07 - Written - Bovy (IAS)",
"overall amplitude A #b) relative amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.])",
"if True, don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes of the different",
"self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD)",
"self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None",
"import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class",
"implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d)",
"if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax=",
"dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax <",
"kpc ext - extinction at dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch)",
"xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.)",
"#disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir=",
"for ii, ipix in enumerate(ipixs): # Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False)",
"and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b !=",
"within a small disk as samples INPUT: lcen, bcen - Galactic longitude and",
"for pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii,",
"locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2.",
"and a 'distance stretch' applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16",
"healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs): # Get glon and glat",
"Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk",
"numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch= numpy.exp(pars[3]) model_ext= drim(l,b,dist*dist_stretch,_fd=fd,_fs=fs,_fo=fo) return 0.5*numpy.sum((model_ext-ext)**2./e_ext**2.)",
"et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03",
"#Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2,",
"X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun)",
"and cosines of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi=",
"be array norescale= (False) if True, don't apply re-scalings _fd, _fs, _fo= (1.)",
"Bovy (IAS) \"\"\" #Fit consists of #a) overall amplitude A #b) relative amplitude",
"NAME: dust_vals_disk PURPOSE: return the distribution of extinction within a small disk as",
"fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1])",
"import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from",
"(fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts and a 'distance stretch' applied",
"__init__ PURPOSE: Initialize the Drimmel03 dust map INPUT: filter= filter to return the",
"dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of extinction within a small",
"rad and extinction value HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\" #",
"rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk=",
"of the disk (deg) dist - distance in kpc radius - radius of",
"al. 2003 2003A&A...409..205D # ############################################################################### import copy import numpy from scipy.ndimage import map_coordinates",
"# Find the pixels at this resolution that fall within the disk ipixs=",
"[xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) >",
"0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk],",
"out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke & Lebovksy (1985); if sf10,",
"Rieke & Lebovksy (1985); if sf10, first put ebv on SFD scale return",
"resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX",
"< dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X=",
"nside=256, to somewhat # oversample the Drimmel resolution nside= 256 # Find the",
"dmax: dmax= tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax <",
"the map with a HEALPIX grid with nside=256, to somewhat # oversample the",
"0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02,",
"Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx)",
"#Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke & Lebovksy (1985); if",
"< 2.) if numpy.sum(globIndx) > 0: #Orion grid is different from other global",
"return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return",
"b for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD)",
"dust_vals_disk PURPOSE: return the distribution of extinction within a small disk as samples",
"if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b for Drimmel",
"- Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l",
"True, don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes of the different components",
"xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori",
"0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05,",
"arrays of pixel-area in sq rad and extinction value HISTORY: 2015-03-07 - Written",
"else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution",
"cosines of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD)",
"self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate",
"- Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input",
"d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) >",
"[xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars beyond the local grid",
"dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj",
"From Rieke & Lebovksy (1985); if sf10, first put ebv on SFD scale",
"spiral, and Orion parts of the Drimmel map to other data INPUT: l,b-",
"d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z=",
"positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various",
"enumerate(ipixs): # Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD",
"(numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj",
"< 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx]",
"dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi",
"2015-03-07 - Written - Bovy (IAS) \"\"\" # Convert the disk center to",
"fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for",
"- arrays of pixel-area in sq rad and extinction value HISTORY: 2015-03-07 -",
"dmax= tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax:",
"if tdmax < dmax: dmax= tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl))",
"the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions of",
"DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\"",
"not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx]",
"lcen, bcen - Galactic longitude and latitude of the center of the disk",
"dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2.",
"data INPUT: l,b- Galactic longitude and latitude in degree dist - distance in",
"_DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def",
"31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101,",
"numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global grids",
"(True) if True, use the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10",
"if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax",
"!= 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if sl !=",
"sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d=",
"mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al.",
"if True, use the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 -",
"or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b for Drimmel dust map",
".49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax <",
"re-scalings _fd, _fs, _fo= (1.) amplitudes of the different components OUTPUT: extinction HISTORY:",
"!= 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori= copy.copy(d)",
"disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi =",
"the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori=",
"HEALPIX map for pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= []",
"return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT:",
"(deg) dist - distance in kpc radius - radius of the disk (deg)",
"Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import copy import numpy from scipy.ndimage",
"# Convert the disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We",
"distance in kpc radius - radius of the disk (deg) OUTPUT: (pixarea,extinction) -",
"avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From",
"#Various setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151,",
"map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke",
"calibrations OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10=",
"numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk,",
"map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk",
"self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2,",
"tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori >",
"and Orion parts of the Drimmel map to other data INPUT: l,b- Galactic",
"_fo= (1.) amplitudes of the different components OUTPUT: extinction HISTORY: 2013-12-10 - Started",
"if tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular",
"0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax",
"extinction value HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\" # Convert the",
"dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori",
"Drimmel03: extinction model from Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import copy",
"DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines",
"rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum",
"center of the disk (deg) dist - distance in kpc radius - radius",
"from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction",
"first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def",
"!= 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl))",
"PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude (deg) b- Galactic latitude (deg)",
"0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if sl !=",
"distance dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl",
"applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy",
"tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax=",
"healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for pixels that lie within the",
"2.) if numpy.sum(globIndx) > 0: #Orion grid is different from other global grids,",
"if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax",
"Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx)",
"1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion grid is different from other",
"xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.)",
"0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map",
"dust map INPUT: filter= filter to return the extinction in sf10= (True) if",
"map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays",
"avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta,",
"self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori=",
"& spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'],",
"lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs):",
"resolution nside= 256 # Find the pixels at this resolution that fall within",
"51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\"",
"#Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi =",
"amplitudes of the disk, spiral, and Orion parts of the Drimmel map to",
"not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b != 0.:",
"pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix",
"< dmax: dmax= tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax",
"stretch' applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written -",
"cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if",
"from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD=",
"< 2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk",
"Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE:",
"100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.:",
"pixels at this resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) #",
"disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for pixels that lie",
"= Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.)",
"self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global",
"self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100.",
"other global grids, so has its own dmax dmax= 100. if b !=",
"90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext):",
"HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the",
"disk, spiral, and Orion parts of the Drimmel map to other data INPUT:",
"== 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not",
"numpy.sum(globIndx) > 0: #Orion grid is different from other global grids, so has",
"globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion grid is",
"grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02",
"> 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'],",
"> 0: #Orion grid is different from other global grids, so has its",
"in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts and a",
"############################################################################### # # Drimmel03: extinction model from Drimmel et al. 2003 2003A&A...409..205D #",
"the extinction in sf10= (True) if True, use the Schlafly & Finkbeiner calibrations",
"_fd, _fs, _fo= (1.) amplitudes of the different components OUTPUT: extinction HISTORY: 2013-12-10",
"sf10= (True) if True, use the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY:",
"dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk =",
"d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) <",
"def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch= numpy.exp(pars[3]) model_ext=",
"2003A&A...409..205D # ############################################################################### import copy import numpy from scipy.ndimage import map_coordinates from scipy",
"the disk (deg) dist - distance in kpc radius - radius of the",
"amplitudes of disk, spiral, and Orion parts and a 'distance stretch' applied to",
"76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc,",
"of the disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq rad",
"distance in kpc ext - extinction at dist e_ext - error in extinction",
"= Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars",
"dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl",
"of pixel-area in sq rad and extinction value HISTORY: 2015-03-07 - Written -",
"as samples INPUT: lcen, bcen - Galactic longitude and latitude of the center",
"2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk =",
"avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2.",
"ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from mwdust.util.tools import",
"0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc,",
"\"\"\" #Fit consists of #a) overall amplitude A #b) relative amplitude fd/A, fs/A",
"< 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj =",
"return the extinction in sf10= (True) if True, use the Schlafly & Finkbeiner",
"mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D",
"256 # Find the pixels at this resolution that fall within the disk",
"[] for ii, ipix in enumerate(ipixs): # Get glon and glat b9, l=",
"NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude (deg) b- Galactic",
"on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME:",
"extinction model from Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import copy import",
"dist - distance in kpc radius - radius of the disk (deg) OUTPUT:",
"raise NotImplementedError(\"array input for l and b for Drimmel dust map not implemented\")",
"beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx)",
"> dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori +",
"dmax= tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax:",
"glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction=",
"1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale:",
"*aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of extinction within",
"ext - extinction at dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes",
"isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b for Drimmel dust map not",
"float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj =",
"l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return",
"a 'distance stretch' applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 -",
"X+self._xsun #Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.)",
"Drimmel resolution nside= 256 # Find the pixels at this resolution that fall",
"2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit consists of #a) overall amplitude",
"X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk",
"0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk =",
"latitude (deg) d- distance (kpc) can be array norescale= (False) if True, don't",
"extinction at dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk,",
"pixel in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD),",
"1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx]",
"parts of the Drimmel map to other data INPUT: l,b- Galactic longitude and",
"map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0:",
"(14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax =",
"> dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid",
"grid with nside=256, to somewhat # oversample the Drimmel resolution nside= 256 #",
"if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter",
"evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit",
"1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] ==",
"model from Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import copy import numpy",
"0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if",
"def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes of the disk, spiral,",
"zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun",
"its own dmax dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb",
"avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if",
"#c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2])",
"_fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude (deg)",
"!= 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d= copy.copy(d)",
"dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori",
"_evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude (deg) b- Galactic latitude",
"of #a) overall amplitude A #b) relative amplitude fd/A, fs/A #c) distance stretch",
"> 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'],",
"b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl)",
"< 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion grid is different from",
"#a) overall amplitude A #b) relative amplitude fd/A, fs/A #c) distance stretch pars=",
"Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and",
"within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs): #",
"that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in",
"read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D):",
"the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs): # Get",
"the Drimmel03 dust map INPUT: filter= filter to return the extinction in sf10=",
"1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif",
"of extinction within a small disk as samples INPUT: lcen, bcen - Galactic",
"Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME:",
"self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids",
"self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE:",
"the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\"",
"norescale= (False) if True, don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes of",
"= X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go",
"mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2.",
"- radius of the disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in",
"if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax",
"relative amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0])",
"tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d >",
".49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax:",
"Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy (IAS)",
"import map_coordinates from scipy import optimize try: import healpy except ImportError: pass from",
"ipix in enumerate(ipixs): # Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD",
"self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori,",
"X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to",
"0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: #",
"degree dist - distance in kpc ext - extinction at dist e_ext -",
"numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True):",
"extinction in sf10= (True) if True, use the Schlafly & Finkbeiner calibrations OUTPUT:",
"3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b",
"# Query the HEALPIX map for pixels that lie within the disk pixarea=",
"of the Drimmel map to other data INPUT: l,b- Galactic longitude and latitude",
"# We pixelize the map with a HEALPIX grid with nside=256, to somewhat",
"has its own dmax dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) -",
"(pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes of the disk,",
"- Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps=",
"Galactic latitude (deg) d- distance (kpc) can be array norescale= (False) if True,",
"healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a HEALPIX grid with nside=256, to",
"sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori=",
"self._filter is None: # From Rieke & Lebovksy (1985); if sf10, first put",
"from scipy import optimize try: import healpy except ImportError: pass from mwdust.util.extCurves import",
"array norescale= (False) if True, don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes",
"(2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if cl < 0.: tdmax =",
"cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke & Lebovksy (1985);",
"dmax= tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax:",
"self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit consists of #a)",
"self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax=",
"151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc=",
"numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest",
"scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE:",
"2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale:",
"2003 2003A&A...409..205D # ############################################################################### import copy import numpy from scipy.ndimage import map_coordinates from",
"dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl >",
"# ############################################################################### import copy import numpy from scipy.ndimage import map_coordinates from scipy import",
"cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if sl",
"0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk],",
"X= X+self._xsun #Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) <",
"#Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion grid",
"self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk,",
"grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02",
"(deg) d- distance (kpc) can be array norescale= (False) if True, don't apply",
"Orion parts and a 'distance stretch' applied to the model (applied as self(l,b,dist*dist_stretch))",
"- Galactic longitude and latitude of the center of the disk (deg) dist",
"longitude (deg) b- Galactic latitude (deg) d- distance (kpc) can be array norescale=",
"[xi,yj,zk], mode='constant',cval=0.) #disk & spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk =",
"OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10",
"the disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq rad and",
"151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76,",
"= Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori +",
"= Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates",
"to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a",
"the HEALPIX map for pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction=",
"copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori= dori*sb+self._zsun xi =",
"numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map for the",
"101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False,",
"a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a HEALPIX",
"input for l and b for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD)",
"#Sines and cosines of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD)",
"e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion",
"dmax: dmax= tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax <",
"import optimize try: import healpy except ImportError: pass from mwdust.util.extCurves import aebv from",
"cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if",
"numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151,",
"sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk=",
"avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map for the re-scaling",
"rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1.,",
"< dmax: dmax= tdmax if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax",
"(applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit consists",
"dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl !=",
"bcen - Galactic longitude and latitude of the center of the disk (deg)",
"stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs)",
"# Drimmel03: extinction model from Drimmel et al. 2003 2003A&A...409..205D # ############################################################################### import",
"ii, ipix in enumerate(ipixs): # Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b=",
"amplitudes of the different components OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy",
"__init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map INPUT: filter= filter",
"self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def",
"numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d)",
"#Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X)",
"the distribution of extinction within a small disk as samples INPUT: lcen, bcen",
"0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the",
"d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if",
"return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch=",
"0: #Orion grid is different from other global grids, so has its own",
"dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and",
"use the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started -",
"if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax",
"can be array norescale= (False) if True, don't apply re-scalings _fd, _fs, _fo=",
"object HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read",
"\"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__",
"numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1",
"numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map for the re-scaling rfIndx=",
"100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.:",
"numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3]))",
"yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx=",
"self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31,",
"self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] ==",
"in degree dist - distance in kpc ext - extinction at dist e_ext",
"pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for ii, ipix in enumerate(ipixs): # Get glon and",
"Written - Bovy (IAS) \"\"\" # Convert the disk center to a HEALPIX",
"in kpc radius - radius of the disk (deg) OUTPUT: (pixarea,extinction) - arrays",
"= X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx=",
"not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori=",
"distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo=",
"is None: # From Rieke & Lebovksy (1985); if sf10, first put ebv",
"pixelize the map with a HEALPIX grid with nside=256, to somewhat # oversample",
"dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax",
"b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction)",
"the disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the",
"HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise",
"cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup arrays avori= numpy.zeros_like(d) avspir=",
"\"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for l and b for",
"map with a HEALPIX grid with nside=256, to somewhat # oversample the Drimmel",
"= X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local",
"at dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral,",
"not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx]",
"#Local grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0:",
"0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02",
"0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2,",
"avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars beyond the",
"dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion",
"disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq rad and extinction",
"HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a HEALPIX grid",
"[xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is None: # From Rieke &",
"yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric",
"read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions of COBE pixels self._rf_sintheta=",
"pixel-area in sq rad and extinction value HISTORY: 2015-03-07 - Written - Bovy",
"Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now",
"numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0])",
"2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'],",
"#Find nearest pixel in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi,",
"2013-12-10 - Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps",
"0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05,",
"dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl Y=",
"put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10) def dust_vals_disk(self,lcen,bcen,dist,radius):",
"amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp=",
"re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1.,",
"spiral, and Orion parts and a 'distance stretch' applied to the model (applied",
"(kpc) can be array norescale= (False) if True, don't apply re-scalings _fd, _fs,",
"pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8.",
"HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\" # Convert the disk center",
"- Bovy (IAS) \"\"\" # Convert the disk center to a HEALPIX vector",
"global grids, so has its own dmax dmax= 100. if b != 0.:",
"cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel",
"error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts and",
"numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes of",
"grids, so has its own dmax dmax= 100. if b != 0.: dmax=",
"def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map INPUT: filter=",
"from scipy.ndimage import map_coordinates from scipy import optimize try: import healpy except ImportError:",
"None: # From Rieke & Lebovksy (1985); if sf10, first put ebv on",
"dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx=",
"- error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts",
"so has its own dmax dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb)",
"avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) >",
"the dust-map INPUT: l- Galactic longitude (deg) b- Galactic latitude (deg) d- distance",
"a small disk as samples INPUT: lcen, bcen - Galactic longitude and latitude",
"- self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax=",
"latitude in degree dist - distance in kpc ext - extinction at dist",
"_fs, _fo= (1.) amplitudes of the different components OUTPUT: extinction HISTORY: 2013-12-10 -",
"self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori,",
"map INPUT: filter= filter to return the extinction in sf10= (True) if True,",
"b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def",
"the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for pixels that",
"coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local grid #Orion locIndx= (numpy.fabs(X) <",
"l and b for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD)",
"\"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude (deg) b-",
"< dmax: dmax= tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax",
"\"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map INPUT: filter= filter to",
"l- Galactic longitude (deg) b- Galactic latitude (deg) d- distance (kpc) can be",
"with nside=256, to somewhat # oversample the Drimmel resolution nside= 256 # Find",
"mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0:",
"for l and b for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl=",
"PURPOSE: return the distribution of extinction within a small disk as samples INPUT:",
"filter= filter to return the extinction in sf10= (True) if True, use the",
"and Orion parts and a 'distance stretch' applied to the model (applied as",
"except ImportError: pass from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from mwdust.util.tools",
"NAME: fit PURPOSE: fit the amplitudes of the disk, spiral, and Orion parts",
"aebv from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D",
"different components OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" if",
"#Orion grid is different from other global grids, so has its own dmax",
"of the disk, spiral, and Orion parts of the Drimmel map to other",
"the amplitudes of the disk, spiral, and Orion parts of the Drimmel map",
"14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]= dmax",
"< 0.75) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk",
"numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1,",
"############################################################################### import copy import numpy from scipy.ndimage import map_coordinates from scipy import optimize",
"- Started - Bovy (IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps=",
"apply re-scalings _fd, _fs, _fo= (1.) amplitudes of the different components OUTPUT: extinction",
"PURPOSE: Initialize the Drimmel03 dust map INPUT: filter= filter to return the extinction",
"Galactic longitude and latitude in degree dist - distance in kpc ext -",
"0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02,",
"= Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y)",
"extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts and a 'distance",
"self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD), sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if",
"(fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch= numpy.exp(pars[3])",
"Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) <",
"#local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(locIndx) > 0: xi",
"self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2,",
"rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx]",
"Galactic longitude and latitude of the center of the disk (deg) dist -",
"[xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]=",
"fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo=",
"mwdust.util.tools import cos_sphere_dist from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model",
"drimmelMaps #Sines and cosines of sky positions of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta=",
"globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk],",
"(pixarea,extinction) - arrays of pixel-area in sq rad and extinction value HISTORY: 2015-03-07",
"if tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori=",
"dust-map INPUT: l- Galactic longitude (deg) b- Galactic latitude (deg) d- distance (kpc)",
"norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b != 0.: dmax=",
"in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta, self._rf_sinphi, self._rf_cosphi, numpy.sin(numpy.pi/2.-b*_DEGTORAD), numpy.cos(numpy.pi/2.-b*_DEGTORAD),",
"the center of the disk (deg) dist - distance in kpc radius -",
"in sf10= (True) if True, use the Schlafly & Finkbeiner calibrations OUTPUT: object",
"and latitude of the center of the disk (deg) dist - distance in",
"yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk],",
"import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003",
"sl,cl)) rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not",
"self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance",
"tdmax d= copy.copy(d) d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl",
"# # Drimmel03: extinction model from Drimmel et al. 2003 2003A&A...409..205D # ###############################################################################",
"Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2. avdisk[locIndx]= map_coordinates(self._drimmelMaps['avdloc'], [xi,yj,zk], mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars beyond",
"Initialize the Drimmel03 dust map INPUT: filter= filter to return the extinction in",
"self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and",
"disk as samples INPUT: lcen, bcen - Galactic longitude and latitude of the",
"the pixels at this resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False)",
"PURPOSE: fit the amplitudes of the disk, spiral, and Orion parts of the",
"= (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax",
"51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51",
"drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions of COBE pixels",
"Written - Bovy (IAS) \"\"\" #Fit consists of #a) overall amplitude A #b)",
"dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb= numpy.cos(b*_DEGTORAD) sb= numpy.sin(b*_DEGTORAD) #Setup",
"numpy.zeros_like(d) #Find nearest pixel in COBE map for the re-scaling rfIndx= numpy.argmax(cos_sphere_dist(self._rf_sintheta, self._rf_costheta,",
"evaluate the dust-map INPUT: l- Galactic longitude (deg) b- Galactic latitude (deg) d-",
"201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.):",
"(numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj",
"def dust_vals_disk(self,lcen,bcen,dist,radius): \"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of extinction within a",
"norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif",
"OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or",
"INPUT: l- Galactic longitude (deg) b- Galactic latitude (deg) d- distance (kpc) can",
"(IAS) \"\"\" # Convert the disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD)",
"dist - distance in kpc ext - extinction at dist e_ext - error",
"OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of disk, spiral, and Orion parts and a 'distance stretch'",
"\"\"\" # Convert the disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) #",
"grid #Orion locIndx= (numpy.fabs(X) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi",
"spir xi = X/self._dx_disk+float(self._nx_disk-1)/2. yj = Y/self._dy_disk+float(self._ny_disk-1)/2. zk = Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk],",
"if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_diskloc+float(self._nx_diskloc-1)/2. yj = Y[locIndx]/self._dy_diskloc+float(self._ny_diskloc-1)/2. zk = Z[locIndx]/self._dz_diskloc+float(self._nz_diskloc-1)/2.",
"(False) if True, don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes of the",
"-8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51 self._dx_disk, self._dy_disk,",
"mode='constant',cval=0.) #Go to Galactocentric coordinates X= X+self._xsun #Stars beyond the local grid #Orion",
"numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2. zk = Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]=",
"sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky",
"None def _evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l-",
"= Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir xi =",
"radius of the disk (deg) OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq",
"extinction.append(self._evaluate(l,b,dist)) extinction= numpy.array(extinction) return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the",
"grid is different from other global grids, so has its own dmax dmax=",
"(3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax",
"- distance in kpc ext - extinction at dist e_ext - error in",
"self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori,",
"pass from mwdust.util.extCurves import aebv from mwdust.util import read_Drimmel from mwdust.util.tools import cos_sphere_dist",
"151, 51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151,",
"#Find maximum distance dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb",
"if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl)",
"amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) dist_stretch= numpy.exp(pars[3]) model_ext= drim(l,b,dist*dist_stretch,_fd=fd,_fs=fs,_fo=fo) return",
"self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun= -8. self._zsun=",
"sf10, first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\ *aebv(self._filter,sf10=self._sf10)",
"import numpy from scipy.ndimage import map_coordinates from scipy import optimize try: import healpy",
"(IAS) \"\"\" #Fit consists of #a) overall amplitude A #b) relative amplitude fd/A,",
"float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]= map_coordinates(self._drimmelMaps['avori'], [xi,yj,zk], mode='constant',cval=0.) #disk & spir",
"the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy",
"amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1])",
"= Z[locIndx]/self._dz_ori2+float(self._nz_ori2-1)/2. avori[locIndx]= map_coordinates(self._drimmelMaps['avori2'], [xi,yj,zk], mode='constant',cval=0.) #local disk locIndx= (numpy.fabs(X) < 0.75)*(numpy.fabs(Y) <",
"if sf10, first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86) else: return out/3.09/((1-self._sf10)+self._sf10*0.86)\\",
"d[d > dmax]= dmax #Rectangular coordinates X= d*cb*cl Y= d*cb*sl Z= d*sb+self._zsun #Local",
"< 0.: tdmax = (1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if sl",
"< 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori",
"l,b- Galactic longitude and latitude in degree dist - distance in kpc ext",
"disk (deg) dist - distance in kpc radius - radius of the disk",
"Yori= dori*cb*sl Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori +",
"elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3",
"at this resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query",
"51 self._dx_ori, self._dy_ori, self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31,",
"_evaluate(self,l,b,d,norescale=False, _fd=1.,_fs=1.,_fo=1.): \"\"\" NAME: _evaluate PURPOSE: evaluate the dust-map INPUT: l- Galactic longitude",
"NotImplementedError(\"array input for l and b for Drimmel dust map not implemented\") cl=",
"0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if cl <",
"of disk, spiral, and Orion parts and a 'distance stretch' applied to the",
"and b for Drimmel dust map not implemented\") cl= numpy.cos(l*_DEGTORAD) sl= numpy.sin(l*_DEGTORAD) cb=",
"0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori",
"'distance stretch' applied to the model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written",
"pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return",
"map for pixels that lie within the disk pixarea= healpy.pixelfunc.nside2pixarea(nside)+numpy.zeros(len(ipixs)) extinction= [] for",
"Convert the disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize",
"+ 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2. avori[globIndx]=",
"True, use the Schlafly & Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started",
"model (applied as self(l,b,dist*dist_stretch)) HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit",
"\"\"\" NAME: dust_vals_disk PURPOSE: return the distribution of extinction within a small disk",
"setups self._xsun= -8. self._zsun= 0.015 #Global grids self._nx_disk, self._ny_disk, self._nz_disk= 151, 151, 51",
"center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with",
"arrays avori= numpy.zeros_like(d) avspir= numpy.zeros_like(d) avdisk= numpy.zeros_like(d) #Find nearest pixel in COBE map",
"2013-12-10 - Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array",
"= (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if cl < 0.: tdmax",
"disk center to a HEALPIX vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map",
"rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx]",
"self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and",
"somewhat # oversample the Drimmel resolution nside= 256 # Find the pixels at",
"#b) relative amplitude fd/A, fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp=",
"and not norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori=",
"extinction= [] for ii, ipix in enumerate(ipixs): # Get glon and glat b9,",
"Find the pixels at this resolution that fall within the disk ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD,",
"maximum distance dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if",
"don't apply re-scalings _fd, _fs, _fo= (1.) amplitudes of the different components OUTPUT:",
"self._dz_ori= 0.05, 0.05, 0.02 #Local grids self._nx_diskloc, self._ny_diskloc, self._nz_diskloc= 31, 31, 51 self._dx_diskloc,",
"class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\"",
"ipixs= healpy.query_disc(nside,vec,radius*_DEGTORAD, inclusive=False,nest=False) # Query the HEALPIX map for pixels that lie within",
"with a HEALPIX grid with nside=256, to somewhat # oversample the Drimmel resolution",
"and latitude in degree dist - distance in kpc ext - extinction at",
"(IAS) \"\"\" DustMap3D.__init__(self,filter=filter) self._sf10= sf10 #Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines",
"inclusive=False,nest=False) # Query the HEALPIX map for pixels that lie within the disk",
"- extinction at dist e_ext - error in extinction OUTPUT: (fd,fs,fo,dist_stretch) amplitudes of",
"numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'], [xi,yj,zk], mode='constant', cval=0.)[globIndx] #Return out=_fd*rfdisk*avdisk+_fs*rfspir*avspir+_fo*rfori*avori if self._filter is",
"tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax",
"dmax= tdmax dori= copy.copy(d) dori[dori > dmax]= dmax Xori= dori*cb*cl+self._xsun Yori= dori*cb*sl Zori=",
"glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate",
"value HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\" # Convert the disk",
"tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax=",
"OUTPUT: (pixarea,extinction) - arrays of pixel-area in sq rad and extinction value HISTORY:",
"in enumerate(ipixs): # Get glon and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/=",
"distance (kpc) can be array norescale= (False) if True, don't apply re-scalings _fd,",
"grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) > 0: #Orion",
"and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2 and not norescale: rfspir=",
"\"\"\" NAME: fit PURPOSE: fit the amplitudes of the disk, spiral, and Orion",
"HISTORY: 2013-12-16 - Written - Bovy (IAS) \"\"\" #Fit consists of #a) overall",
"latitude of the center of the disk (deg) dist - distance in kpc",
"rfori= self._drimmelMaps['rf'][rfIndx] #Find maximum distance dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb)",
"COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups self._xsun=",
"!= 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if",
"Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray) or isinstance(b,numpy.ndarray): raise NotImplementedError(\"array input for",
"sq rad and extinction value HISTORY: 2015-03-07 - Written - Bovy (IAS) \"\"\"",
"2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize the Drimmel03 dust map",
"self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51 self._dx_ori, self._dy_ori, self._dz_ori=",
"#Fit consists of #a) overall amplitude A #b) relative amplitude fd/A, fs/A #c)",
"#Stars beyond the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if",
"of COBE pixels self._rf_sintheta= numpy.sin(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_costheta= numpy.cos(numpy.pi/2.-self._drimmelMaps['rf_glat']*_DEGTORAD) self._rf_sinphi= numpy.sin(self._drimmelMaps['rf_glon']*_DEGTORAD) self._rf_cosphi= numpy.cos(self._drimmelMaps['rf_glon']*_DEGTORAD) #Various setups",
"norescale: rfspir= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 3 and not norescale: rfori= self._drimmelMaps['rf'][rfIndx] #Find",
"amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs= amp*numpy.exp(pars[2])",
"if sl != 0.: tdmax = (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax",
"vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a HEALPIX grid with nside=256,",
"components OUTPUT: extinction HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\" if isinstance(l,numpy.ndarray)",
"1.)*(numpy.fabs(Y) < 2.) if numpy.sum(locIndx) > 0: xi = X[locIndx]/self._dx_ori2+float(self._nx_ori2-1)/2. yj = Y[locIndx]/self._dy_ori2+float(self._ny_ori2-1)/2.",
"0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if",
"the local grid #Orion globIndx= True^(numpy.fabs(X-self._xsun) < 1.)*(numpy.fabs(Y) < 2.) if numpy.sum(globIndx) >",
"own dmax dmax= 100. if b != 0.: dmax= .49999/numpy.fabs(sb) - self._zsun/sb if",
"tdmax < dmax: dmax= tdmax if cl < 0.: tdmax = (1.374999/numpy.fabs(cl)) if",
"the Drimmel resolution nside= 256 # Find the pixels at this resolution that",
"in kpc ext - extinction at dist e_ext - error in extinction OUTPUT:",
"if cl != 0.: tdmax= (14.9999/numpy.fabs(cl)-self._xsun/cl) if tdmax < dmax: dmax= tdmax if",
"= (3.749999/numpy.fabs(sl)) if tdmax < dmax: dmax= tdmax dori= copy.copy(d) dori[dori > dmax]=",
"(1.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if sl != 0.: tdmax =",
"Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk = Zori[globIndx]/self._dz_ori + float(self._nz_ori-1)/2.",
"rfdisk, rfspir, rfori= 1., 1., 1, if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale:",
"51 self._dx_disk, self._dy_disk, self._dz_disk= 0.2, 0.2, 0.02 self._nx_ori, self._ny_ori, self._nz_ori= 76, 151, 51",
"dmax: dmax= tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if tdmax <",
"& Lebovksy (1985); if sf10, first put ebv on SFD scale return out/3.09/((1-self._sf10)+self._sf10*0.86)",
"#Read the maps drimmelMaps= read_Drimmel.readDrimmelAll() self._drimmelMaps= drimmelMaps #Sines and cosines of sky positions",
"from Drimmel et al. 2003 2003A&A...409..205D\"\"\" def __init__(self,filter=None,sf10=True): \"\"\" NAME: __init__ PURPOSE: Initialize",
"(1.) amplitudes of the different components OUTPUT: extinction HISTORY: 2013-12-10 - Started -",
"> 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax: dmax= tdmax if cl",
"vector vec= healpy.pixelfunc.ang2vec((90.-bcen)*_DEGTORAD,lcen*_DEGTORAD) # We pixelize the map with a HEALPIX grid with",
"= Z/self._dz_disk+float(self._nz_disk-1)/2. avspir= map_coordinates(self._drimmelMaps['avspir'], [xi,yj,zk], mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if",
"fs/A #c) distance stretch pars= numpy.array([0.,numpy.log(1./3.),numpy.log(1./3.),0.]) pars=\\ optimize.fmin_powell(_fitFunc,pars,args=(self,l,b,dist,ext,e_ext)) amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs=",
"scipy import optimize try: import healpy except ImportError: pass from mwdust.util.extCurves import aebv",
"if self._drimmelMaps['rf_comp'][rfIndx] == 1 and not norescale: rfdisk= self._drimmelMaps['rf'][rfIndx] elif self._drimmelMaps['rf_comp'][rfIndx] == 2",
"the disk, spiral, and Orion parts of the Drimmel map to other data",
"return (pixarea,extinction) def fit(self,l,b,dist,ext,e_ext): \"\"\" NAME: fit PURPOSE: fit the amplitudes of the",
"return the distribution of extinction within a small disk as samples INPUT: lcen,",
"tdmax < dmax: dmax= tdmax if sl != 0.: tdmax = 14.9999/numpy.fabs(sl) if",
"31, 51 self._dx_diskloc, self._dy_diskloc, self._dz_diskloc= 0.05, 0.05, 0.02 self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201,",
"fs= amp*numpy.exp(pars[2]) fo= amp*(1.-fd-fs) return (fd,fs,fo,numpy.exp(pars[3])) def _fitFunc(pars,drim,l,b,dist,ext,e_ext): amp= numpy.exp(pars[0]) fd= amp*numpy.exp(pars[1]) fs=",
"- Written - Bovy (IAS) \"\"\" # Convert the disk center to a",
"# From Rieke & Lebovksy (1985); if sf10, first put ebv on SFD",
"map to other data INPUT: l,b- Galactic longitude and latitude in degree dist",
"self._nx_ori2, self._ny_ori2, self._nz_ori2= 101, 201, 51 self._dx_ori2, self._dy_ori2, self._dz_ori2= 0.02, 0.02, 0.02 return",
"longitude and latitude in degree dist - distance in kpc ext - extinction",
"mode='constant',cval=0.) globIndx= True^(numpy.fabs(X-self._xsun) < 0.75)*(numpy.fabs(Y) < 0.75) if numpy.sum(globIndx) > 0: avdisk[globIndx]= map_coordinates(self._drimmelMaps['avdisk'],",
"and glat b9, l= healpy.pixelfunc.pix2ang(nside,ipix,nest=False) b= 90.-b9/_DEGTORAD l/= _DEGTORAD # Now evaluate extinction.append(self._evaluate(l,b,dist))",
"= 14.9999/numpy.fabs(sl) if tdmax < dmax: dmax= tdmax d= copy.copy(d) d[d > dmax]=",
"Zori= dori*sb+self._zsun xi = Xori[globIndx]/self._dx_ori + 2.5*float(self._nx_ori-1) yj = Yori[globIndx]/self._dy_ori + float(self._ny_ori-1)/2. zk",
"- self._zsun/sb if cl > 0.: tdmax = (2.374999/numpy.fabs(cl)) if tdmax < dmax:",
"& Finkbeiner calibrations OUTPUT: object HISTORY: 2013-12-10 - Started - Bovy (IAS) \"\"\"",
"HEALPIX grid with nside=256, to somewhat # oversample the Drimmel resolution nside= 256",
"oversample the Drimmel resolution nside= 256 # Find the pixels at this resolution",
"from mwdust.DustMap3D import DustMap3D _DEGTORAD= numpy.pi/180. class Drimmel03(DustMap3D): \"\"\"extinction model from Drimmel et",
"import copy import numpy from scipy.ndimage import map_coordinates from scipy import optimize try:",
"other data INPUT: l,b- Galactic longitude and latitude in degree dist - distance"
] |
[
"== 0 and (year % 400 == 0 or year % 100 !=",
"python # coding: utf-8 # In[ ]: def is_leap(year): leap = False #",
"% 4 == 0 and (year % 400 == 0 or year %",
"logic here if year % 4 == 0 and (year % 400 ==",
"def is_leap(year): leap = False # Write your logic here if year %",
"leap = False # Write your logic here if year % 4 ==",
"0 or year % 100 != 0) : leap = True return leap",
"Write your logic here if year % 4 == 0 and (year %",
"In[ ]: def is_leap(year): leap = False # Write your logic here if",
"# In[ ]: def is_leap(year): leap = False # Write your logic here",
"#!/usr/bin/env python # coding: utf-8 # In[ ]: def is_leap(year): leap = False",
"% 400 == 0 or year % 100 != 0) : leap =",
"coding: utf-8 # In[ ]: def is_leap(year): leap = False # Write your",
"False # Write your logic here if year % 4 == 0 and",
"0 and (year % 400 == 0 or year % 100 != 0)",
"# coding: utf-8 # In[ ]: def is_leap(year): leap = False # Write",
"== 0 or year % 100 != 0) : leap = True return",
"(year % 400 == 0 or year % 100 != 0) : leap",
"your logic here if year % 4 == 0 and (year % 400",
"= False # Write your logic here if year % 4 == 0",
"# Write your logic here if year % 4 == 0 and (year",
"year % 4 == 0 and (year % 400 == 0 or year",
"400 == 0 or year % 100 != 0) : leap = True",
"]: def is_leap(year): leap = False # Write your logic here if year",
"if year % 4 == 0 and (year % 400 == 0 or",
"4 == 0 and (year % 400 == 0 or year % 100",
"utf-8 # In[ ]: def is_leap(year): leap = False # Write your logic",
"here if year % 4 == 0 and (year % 400 == 0",
"is_leap(year): leap = False # Write your logic here if year % 4",
"and (year % 400 == 0 or year % 100 != 0) :"
] |
[
"fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url == \"http://yandex.ru\" assert schedule",
"JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import",
"req1.url == req2.url and req1.meta == req2.meta and req1.headers == req2.headers enc =",
"assert req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error'",
"import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder)",
"o[1].url == req.url and o[1].body == 'SOME CONTENT' and o[1].meta == req.meta assert",
"= dec.decode(it.next()) assert o_type == 'offset' assert partition_id == 0 assert offset ==",
"it = iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) ==",
"assert o_error == \"Host not found\" o_type, fprint, score, url, schedule = dec.decode(it.next())",
"o[1][0] check_request(req_d, req) assert type(req_d) == Request o = dec.decode(it.next()) assert o[0] ==",
"\"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next())",
"== req.url and o[1].body == 'SOME CONTENT' and o[1].meta == req.meta assert type(o[2])",
"o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id == 1 o_type,",
"enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\",",
"enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next()) assert o[0]",
"o[2][0] assert type(req_d) == Request assert req_d.url == req2.url o_type, o_req, o_error =",
"enc = encoder(Request, send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"},",
"\"Host not found\" o_type, fprint, score, url, schedule = dec.decode(it.next()) assert o_type ==",
"partition_id, offset = dec.decode(it.next()) assert o_type == 'offset' assert partition_id == 0 assert",
"import Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder,",
"coding: utf-8 -*- from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder from",
"found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs)",
"assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert",
"req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req),",
"request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796),",
"job_id == 1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type == 'offset' assert",
"== list req_d = o[1][0] check_request(req_d, req) assert type(req_d) == Request o =",
"\"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it",
"assert o_type == 'offset' assert partition_id == 0 assert offset == 28796 o",
"req_d = o[2][0] assert type(req_d) == Request assert req_d.url == req2.url o_type, o_req,",
"Response assert o[1].url == req.url and o[1].body == 'SOME CONTENT' and o[1].meta ==",
"28796), enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds'",
"== 'page_crawled' assert type(o[1]) == Response assert o[1].url == req.url and o[1].body ==",
"dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) == Response assert o[1].url == req.url",
"(MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1, req2): assert",
"assert o[0] == 'page_crawled' assert type(o[1]) == Response assert o[1].url == req.url and",
"req2): assert req1.url == req2.url and req1.meta == req2.meta and req1.headers == req2.headers",
"o[0] == 'add_seeds' assert type(o[1]) == list req_d = o[1][0] check_request(req_d, req) assert",
"'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'},",
"assert score == 0.51 assert url == \"http://yandex.ru\" assert schedule is True o_type,",
"== 'new_job_id' assert job_id == 1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type",
"dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id == 1 o_type, partition_id, offset =",
"# -*- coding: utf-8 -*- from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as",
"and o[1].meta == req.meta assert type(o[2]) == list req_d = o[2][0] assert type(req_d)",
"as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize(",
"assert o[1].url == req.url and o[1].body == 'SOME CONTENT' and o[1].meta == req.meta",
"found\" o_type, fprint, score, url, schedule = dec.decode(it.next()) assert o_type == 'update_score' assert",
"o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert o_error == \"Host",
"and req1.meta == req2.meta and req1.headers == req2.headers enc = encoder(Request, send_body=True) dec",
"= encoder(Request, send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr':",
"CONTENT' and o[1].meta == req.meta assert type(o[2]) == list req_d = o[2][0] assert",
"and o[1].body == 'SOME CONTENT' and o[1].meta == req.meta assert type(o[2]) == list",
"Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ]",
"schedule = dec.decode(it.next()) assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score",
"o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) == list req_d =",
"('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def",
"dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) == list req_d = o[1][0] check_request(req_d,",
"== req2.url and req1.meta == req2.meta and req1.headers == req2.headers enc = encoder(Request,",
"Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\",",
"dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert o_error == \"Host not found\"",
"== req2.meta and req1.headers == req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request,",
"req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [",
"req) assert o_error == \"Host not found\" o_type, fprint, score, url, schedule =",
"'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1,",
"0.51 assert url == \"http://yandex.ru\" assert schedule is True o_type, job_id = dec.decode(it.next())",
"assert o_type == 'new_job_id' assert job_id == 1 o_type, partition_id, offset = dec.decode(it.next())",
"list req_d = o[1][0] check_request(req_d, req) assert type(req_d) == Request o = dec.decode(it.next())",
"== Response assert o[1].url == req.url and o[1].body == 'SOME CONTENT' and o[1].meta",
"iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) == list req_d",
"enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ]",
"req_d = o[1][0] check_request(req_d, req) assert type(req_d) == Request o = dec.decode(it.next()) assert",
"score, url, schedule = dec.decode(it.next()) assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\"",
"[ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"),",
"Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from",
"[req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req)",
"o_error == \"Host not found\" o_type, fprint, score, url, schedule = dec.decode(it.next()) assert",
"== \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url == \"http://yandex.ru\" assert schedule is",
"assert type(o[2]) == list req_d = o[2][0] assert type(req_d) == Request assert req_d.url",
"== 1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type == 'offset' assert partition_id",
"score == 0.51 assert url == \"http://yandex.ru\" assert schedule is True o_type, job_id",
"enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next()) assert o[0] ==",
"MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder',",
"Request assert req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type ==",
"pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder,",
"encoder(Request, send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'})",
"@pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder):",
"assert type(o[1]) == Response assert o[1].url == req.url and o[1].body == 'SOME CONTENT'",
"== 0.51 assert url == \"http://yandex.ru\" assert schedule is True o_type, job_id =",
"'page_crawled' assert type(o[1]) == Response assert o[1].url == req.url and o[1].body == 'SOME",
"decoder): def check_request(req1, req2): assert req1.url == req2.url and req1.meta == req2.meta and",
"== req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\",",
"Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs =",
"body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\",",
"assert job_id == 1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type == 'offset'",
"assert type(o[1]) == list req_d = o[1][0] check_request(req_d, req) assert type(req_d) == Request",
"= iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) == list",
"'add_seeds' assert type(o[1]) == list req_d = o[1][0] check_request(req_d, req) assert type(req_d) ==",
"req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert",
"check_request(req1, req2): assert req1.url == req2.url and req1.meta == req2.meta and req1.headers ==",
"Decoder as MsgPackDecoder from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'),",
"== \"Host not found\" o_type, fprint, score, url, schedule = dec.decode(it.next()) assert o_type",
"o[0] == 'page_crawled' assert type(o[1]) == Response assert o[1].url == req.url and o[1].body",
"assert url == \"http://yandex.ru\" assert schedule is True o_type, job_id = dec.decode(it.next()) assert",
"= o[1][0] check_request(req_d, req) assert type(req_d) == Request o = dec.decode(it.next()) assert o[0]",
"from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder),",
"req.url and o[1].body == 'SOME CONTENT' and o[1].meta == req.meta assert type(o[2]) ==",
"= dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) == Response assert o[1].url ==",
"True o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id == 1",
"Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] )",
"decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs",
"o_type, o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert o_error",
"dec.decode(it.next()) assert o_type == 'offset' assert partition_id == 0 assert offset == 28796",
"type(o[1]) == list req_d = o[1][0] check_request(req_d, req) assert type(req_d) == Request o",
"\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url == \"http://yandex.ru\" assert schedule is True",
"1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type == 'offset' assert partition_id ==",
"req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\":",
"offset = dec.decode(it.next()) assert o_type == 'offset' assert partition_id == 0 assert offset",
"check_request(req_d, req) assert type(req_d) == Request o = dec.decode(it.next()) assert o[0] == 'page_crawled'",
"MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url",
"enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51,",
"JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder",
"url, schedule = dec.decode(it.next()) assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert",
"Request o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) == Response assert",
"def check_request(req1, req2): assert req1.url == req2.url and req1.meta == req2.meta and req1.headers",
"== 'request_error' check_request(o_req, req) assert o_error == \"Host not found\" o_type, fprint, score,",
"True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next()) assert",
"0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o =",
"o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert o_error ==",
"== Request o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) == Response",
"def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url == req2.url and req1.meta ==",
"req1.headers == req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request, Response) req =",
"== 'add_seeds' assert type(o[1]) == list req_d = o[1][0] check_request(req_d, req) assert type(req_d)",
"req2.url and req1.meta == req2.meta and req1.headers == req2.headers enc = encoder(Request, send_body=True)",
"frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder,",
"= Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]),",
"enc.encode_request(req) ] it = iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert",
"req) assert type(req_d) == Request o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert",
"type(o[1]) == Response assert o[1].url == req.url and o[1].body == 'SOME CONTENT' and",
"== 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url ==",
"== \"http://yandex.ru\" assert schedule is True o_type, job_id = dec.decode(it.next()) assert o_type ==",
"= decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\")",
"schedule is True o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id",
"frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as",
"not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it =",
"'SOME CONTENT' and o[1].meta == req.meta assert type(o[2]) == list req_d = o[2][0]",
"job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id == 1 o_type, partition_id,",
"] ) def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url == req2.url and",
"frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request, Response",
"= dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id == 1 o_type, partition_id, offset",
"req1.meta == req2.meta and req1.headers == req2.headers enc = encoder(Request, send_body=True) dec =",
"headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1),",
"type(o[2]) == list req_d = o[2][0] assert type(req_d) == Request assert req_d.url ==",
"== Request assert req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type",
"== 'offset' assert partition_id == 0 assert offset == 28796 o = dec.decode_request(it.next())",
"fprint, score, url, schedule = dec.decode(it.next()) assert o_type == 'update_score' assert fprint ==",
"MsgPackDecoder from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder,",
"headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr':",
"Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req,",
"assert o_type == 'request_error' check_request(o_req, req) assert o_error == \"Host not found\" o_type,",
"-*- from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import",
"\"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT',",
"o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url",
"(JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url ==",
"check_request(o_req, req) assert o_error == \"Host not found\" o_type, fprint, score, url, schedule",
"not found\" o_type, fprint, score, url, schedule = dec.decode(it.next()) assert o_type == 'update_score'",
"Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request, Response import pytest",
"o_type, fprint, score, url, schedule = dec.decode(it.next()) assert o_type == 'update_score' assert fprint",
"as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models",
"assert type(req_d) == Request o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1])",
"is True o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert job_id ==",
"from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request,",
"== 'SOME CONTENT' and o[1].meta == req.meta assert type(o[2]) == list req_d =",
"CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True),",
"dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 =",
"= dec.decode(it.next()) assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score ==",
"== list req_d = o[2][0] assert type(req_d) == Request assert req_d.url == req2.url",
"assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url == \"http://yandex.ru\" assert",
"o[1].meta == req.meta assert type(o[2]) == list req_d = o[2][0] assert type(req_d) ==",
"= dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req) assert o_error == \"Host not",
"Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder",
"assert type(req_d) == Request assert req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next())",
"assert schedule is True o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id' assert",
"o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) == Response assert o[1].url",
"'request_error' check_request(o_req, req) assert o_error == \"Host not found\" o_type, fprint, score, url,",
"JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url == req2.url",
"] it = iter(msgs) o = dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1])",
"'offset' assert partition_id == 0 assert offset == 28796 o = dec.decode_request(it.next()) check_request(o,",
"== req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req, req)",
"meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2 = Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME",
"dec.decode(it.next()) assert o_type == 'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51",
"as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder as MsgPackEncoder, Decoder as",
"'new_job_id' assert job_id == 1 o_type, partition_id, offset = dec.decode(it.next()) assert o_type ==",
"type(req_d) == Request o = dec.decode(it.next()) assert o[0] == 'page_crawled' assert type(o[1]) ==",
"import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def",
"= [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not",
"enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0, 28796), enc.encode_request(req) ] it = iter(msgs) o",
"= o[2][0] assert type(req_d) == Request assert req_d.url == req2.url o_type, o_req, o_error",
"and req1.headers == req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request, Response) req",
"'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host not found\"), enc.encode_update_score(\"1be68ff556fd0bbe5802d1a100850da29f7f15b1\", 0.51, \"http://yandex.ru\", True), enc.encode_new_job_id(1), enc.encode_offset(0,",
"o_type, partition_id, offset = dec.decode(it.next()) assert o_type == 'offset' assert partition_id == 0",
"assert partition_id == 0 assert offset == 28796 o = dec.decode_request(it.next()) check_request(o, req)",
"from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack import Encoder",
"utf-8 -*- from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder from frontera.contrib.backends.remote.codecs.msgpack",
"req2.meta and req1.headers == req2.headers enc = encoder(Request, send_body=True) dec = decoder(Request, Response)",
"req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next()) assert o_type == 'request_error' check_request(o_req,",
"req.meta assert type(o[2]) == list req_d = o[2][0] assert type(req_d) == Request assert",
"import Encoder as MsgPackEncoder, Decoder as MsgPackDecoder from frontera.core.models import Request, Response import",
"o[1].body == 'SOME CONTENT' and o[1].meta == req.meta assert type(o[2]) == list req_d",
"== req.meta assert type(o[2]) == list req_d = o[2][0] assert type(req_d) == Request",
"assert o[0] == 'add_seeds' assert type(o[1]) == list req_d = o[1][0] check_request(req_d, req)",
"[ (MsgPackEncoder, MsgPackDecoder), (JsonEncoder, JsonDecoder) ] ) def test_codec(encoder, decoder): def check_request(req1, req2):",
"test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url == req2.url and req1.meta == req2.meta",
"list req_d = o[2][0] assert type(req_d) == Request assert req_d.url == req2.url o_type,",
"type(req_d) == Request assert req_d.url == req2.url o_type, o_req, o_error = dec.decode(it.next()) assert",
"'update_score' assert fprint == \"1be68ff556fd0bbe5802d1a100850da29f7f15b1\" assert score == 0.51 assert url == \"http://yandex.ru\"",
"assert req1.url == req2.url and req1.meta == req2.meta and req1.headers == req2.headers enc",
"o_type == 'request_error' check_request(o_req, req) assert o_error == \"Host not found\" o_type, fprint,",
"o_type == 'new_job_id' assert job_id == 1 o_type, partition_id, offset = dec.decode(it.next()) assert",
"send_body=True) dec = decoder(Request, Response) req = Request(url=\"http://www.yandex.ru\", meta={\"test\": \"shmest\"}, headers={'reqhdr': 'value'}) req2",
"as MsgPackDecoder from frontera.core.models import Request, Response import pytest @pytest.mark.parametrize( ('encoder', 'decoder'), [",
") def test_codec(encoder, decoder): def check_request(req1, req2): assert req1.url == req2.url and req1.meta",
"= Request(url=\"http://www.yandex.ru/search\") msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]),",
"\"http://yandex.ru\" assert schedule is True o_type, job_id = dec.decode(it.next()) assert o_type == 'new_job_id'",
"msgs = [ enc.encode_add_seeds([req]), enc.encode_page_crawled(Response(url=\"http://www.yandex.ru\", body='SOME CONTENT', headers={'hdr': 'value'}, request=req), [req2]), enc.encode_request_error(req, \"Host",
"= dec.decode(it.next()) assert o[0] == 'add_seeds' assert type(o[1]) == list req_d = o[1][0]",
"o_type == 'offset' assert partition_id == 0 assert offset == 28796 o =",
"url == \"http://yandex.ru\" assert schedule is True o_type, job_id = dec.decode(it.next()) assert o_type",
"-*- coding: utf-8 -*- from frontera.contrib.backends.remote.codecs.json import Encoder as JsonEncoder, Decoder as JsonDecoder"
] |
[
"model module. # You'll have to do the following manually to clean this",
"default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True)",
"default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold',",
"up: # * Rearrange models' order # * Make sure each model has",
"* Make sure each model has one field with primary_key=True # * Remove",
"delete the table # Feel free to rename the models, but don't rename",
"Django model module. # You'll have to do the following manually to clean",
"models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort',",
"Django to create and delete the table # Feel free to rename the",
"sqlcustom [appname]' # into your database. from __future__ import unicode_literals from django.db import",
"to clean this up: # * Rearrange models' order # * Make sure",
"you wish to allow Django to create and delete the table # Feel",
"table # Feel free to rename the models, but don't rename db_table values",
"editable=False) class Meta: managed = False db_table = 'user' def __unicode__(self): return \"%s:%s",
"return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\"",
"your database. from __future__ import unicode_literals from django.db import models from django.conf import",
"D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)), self.d,",
"= models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it was a",
"the following manually to clean this up: # * Rearrange models' order #",
"You'll have to insert the output of 'django-admin.py sqlcustom [appname]' # into your",
"output of 'django-admin.py sqlcustom [appname]' # into your database. from __future__ import unicode_literals",
"model has one field with primary_key=True # * Remove `managed = False` lines",
"# Field renamed because it was a Python reserved word. passwd = models.CharField('ServicePWD',",
"__unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u,",
"`managed = False` lines if you wish to allow Django to create and",
"[appname]' # into your database. from __future__ import unicode_literals from django.db import models",
"False` lines if you wish to allow Django to create and delete the",
"from __future__ import unicode_literals from django.db import models from django.conf import settings class",
"managed = False db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\"",
"database. from __future__ import unicode_literals from django.db import models from django.conf import settings",
"models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable',",
"default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1,",
"models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time =",
"editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed =",
"insert the output of 'django-admin.py sqlcustom [appname]' # into your database. from __future__",
"to do the following manually to clean this up: # * Rearrange models'",
"order # * Make sure each model has one field with primary_key=True #",
"# # Also note: You'll have to insert the output of 'django-admin.py sqlcustom",
"servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it was",
"this up: # * Rearrange models' order # * Make sure each model",
"# * Remove `managed = False` lines if you wish to allow Django",
"class Meta: managed = False db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s)",
"models from django.conf import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd =",
"import unicode_literals from django.db import models from django.conf import settings class SSInstance(models.Model): email",
"last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed = False db_table = 'user' def",
"self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)), self.d, \"%.2f\" % (float(self.transfer_enable)/(1024*1024)), self.transfer_enable)",
"or field names. # # Also note: You'll have to insert the output",
"passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0)",
"rename db_table values or field names. # # Also note: You'll have to",
"editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed = False db_table = 'user'",
"= models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed",
"field names. # # Also note: You'll have to insert the output of",
"# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'",
"Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)), self.d, \"%.2f\"",
"Field renamed because it was a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16)",
"__future__ import unicode_literals from django.db import models from django.conf import settings class SSInstance(models.Model):",
"t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0)",
"from django.conf import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD',",
"models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable =",
"the output of 'django-admin.py sqlcustom [appname]' # into your database. from __future__ import",
"import models from django.conf import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd",
"it was a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive',",
"Meta: managed = False db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s)",
"have to do the following manually to clean this up: # * Rearrange",
"= models.IntegerField(default=1, editable=False) class Meta: managed = False db_table = 'user' def __unicode__(self):",
"email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field",
"# You'll have to do the following manually to clean this up: #",
"unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7,",
"to create and delete the table # Feel free to rename the models,",
"don't rename db_table values or field names. # # Also note: You'll have",
"models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d =",
"def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)),",
"lines if you wish to allow Django to create and delete the table",
"'django-admin.py sqlcustom [appname]' # into your database. from __future__ import unicode_literals from django.db",
"editable=False) # Field renamed because it was a Python reserved word. passwd =",
"allow Django to create and delete the table # Feel free to rename",
"= 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\"",
"rename the models, but don't rename db_table values or field names. # #",
"# * Make sure each model has one field with primary_key=True # *",
"db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port,",
"django.conf import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass',",
"import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16,",
"switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False)",
"db_table values or field names. # # Also note: You'll have to insert",
"django.db import models from django.conf import settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32)",
"<filename>webfrontend/shadowsocks/models.py # This is an auto-generated Django model module. # You'll have to",
"max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download',",
"Rearrange models' order # * Make sure each model has one field with",
"(self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)), self.d, \"%.2f\" % (float(self.transfer_enable)/(1024*1024)),",
"max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it",
"the table # Feel free to rename the models, but don't rename db_table",
"default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed",
"values or field names. # # Also note: You'll have to insert the",
"field with primary_key=True # * Remove `managed = False` lines if you wish",
"= models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type =",
"is an auto-generated Django model module. # You'll have to do the following",
"Feel free to rename the models, but don't rename db_table values or field",
"one field with primary_key=True # * Remove `managed = False` lines if you",
"models' order # * Make sure each model has one field with primary_key=True",
"sure each model has one field with primary_key=True # * Remove `managed =",
"unicode_literals from django.db import models from django.conf import settings class SSInstance(models.Model): email =",
"names. # # Also note: You'll have to insert the output of 'django-admin.py",
"from django.db import models from django.conf import settings class SSInstance(models.Model): email = models.CharField('Email',",
"models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time =",
"models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed = False db_table =",
"was a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0,",
"to insert the output of 'django-admin.py sqlcustom [appname]' # into your database. from",
"renamed because it was a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t",
"\"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" %",
"= models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable",
"clean this up: # * Rearrange models' order # * Make sure each",
"have to insert the output of 'django-admin.py sqlcustom [appname]' # into your database.",
"default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False)",
"False db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable,",
"models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type',",
"models.IntegerField(default=1, editable=False) class Meta: managed = False db_table = 'user' def __unicode__(self): return",
"note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]' # into",
"an auto-generated Django model module. # You'll have to do the following manually",
"You'll have to do the following manually to clean this up: # *",
"default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1)",
"a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False)",
"Make sure each model has one field with primary_key=True # * Remove `managed",
"Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u",
"reserved word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u =",
"of 'django-admin.py sqlcustom [appname]' # into your database. from __future__ import unicode_literals from",
"editable=False) u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD)",
"port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type",
"= models.IntegerField(default=1, editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time",
"= models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch =",
"enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False)",
"= False` lines if you wish to allow Django to create and delete",
"module. # You'll have to do the following manually to clean this up:",
"editable=False) enable = models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1,",
"wish to allow Django to create and delete the table # Feel free",
"= models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable =",
"create and delete the table # Feel free to rename the models, but",
"max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it was a Python reserved word.",
"has one field with primary_key=True # * Remove `managed = False` lines if",
"U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)),",
"'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" % (self.enable, self.port, \"%.2f\" %",
"= models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed = False db_table",
"u = models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port",
"# Feel free to rename the models, but don't rename db_table values or",
"because it was a Python reserved word. passwd = models.CharField('ServicePWD', max_length=16) t =",
"to rename the models, but don't rename db_table values or field names. #",
"d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch",
"models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1,",
"to allow Django to create and delete the table # Feel free to",
"= models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload', default=0) d",
"= models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class",
"each model has one field with primary_key=True # * Remove `managed = False`",
"into your database. from __future__ import unicode_literals from django.db import models from django.conf",
"models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because",
"models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it was a Python",
"type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False)",
"class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False)",
"Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]' #",
"the models, but don't rename db_table values or field names. # # Also",
"models, but don't rename db_table values or field names. # # Also note:",
"auto-generated Django model module. # You'll have to do the following manually to",
"# This is an auto-generated Django model module. # You'll have to do",
"settings class SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>',",
"do the following manually to clean this up: # * Rearrange models' order",
"and delete the table # Feel free to rename the models, but don't",
"models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta:",
"primary_key=True # * Remove `managed = False` lines if you wish to allow",
"free to rename the models, but don't rename db_table values or field names.",
"= models.BooleanField('Enable', default=1) type = models.IntegerField('Type', default=7, editable=False) last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time",
"SSInstance(models.Model): email = models.CharField('Email', max_length=32) servicepwd = models.CharField('AdminPWD', db_column='pass', max_length=16, default='<PASSWORD>', editable=False) #",
"% (self.enable, self.port, \"%.2f\" % (float(self.u)/(1024*1024)), self.u, \"%.2f\" % (float(self.d)/(1024*1024)), self.d, \"%.2f\" %",
"transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port = models.IntegerField('ServicePort', unique=True) switch = models.IntegerField(default=1, editable=False) enable",
"* Rearrange models' order # * Make sure each model has one field",
"This is an auto-generated Django model module. # You'll have to do the",
"word. passwd = models.CharField('ServicePWD', max_length=16) t = models.IntegerField('LastAlive', default=0, editable=False) u = models.BigIntegerField('Upload',",
"db_column='pass', max_length=16, default='<PASSWORD>', editable=False) # Field renamed because it was a Python reserved",
"with primary_key=True # * Remove `managed = False` lines if you wish to",
"= models.BigIntegerField('Upload', default=0) d = models.BigIntegerField('Download', default=0) transfer_enable = models.BigIntegerField('Threshold', default=settings.DEFAULT_THRESHOLD) port =",
"default='<PASSWORD>', editable=False) # Field renamed because it was a Python reserved word. passwd",
"following manually to clean this up: # * Rearrange models' order # *",
"= False db_table = 'user' def __unicode__(self): return \"%s:%s U:%sM(%s) D:%sM(%s) Lmt:%sM(%s)\" %",
"Remove `managed = False` lines if you wish to allow Django to create",
"last_get_gitf_time = models.IntegerField(default=1, editable=False) last_rest_pass_time = models.IntegerField(default=1, editable=False) class Meta: managed = False",
"# into your database. from __future__ import unicode_literals from django.db import models from",
"but don't rename db_table values or field names. # # Also note: You'll",
"# * Rearrange models' order # * Make sure each model has one",
"if you wish to allow Django to create and delete the table #",
"manually to clean this up: # * Rearrange models' order # * Make",
"* Remove `managed = False` lines if you wish to allow Django to"
] |
[
"import models # Create your models here. from Author.models import Author, FriendRequest, Friends",
"here. from Author.models import Author, FriendRequest, Friends from Posts.models import Post, Comment, Image",
"# Create your models here. from Author.models import Author, FriendRequest, Friends from Posts.models",
"models here. from Author.models import Author, FriendRequest, Friends from Posts.models import Post, Comment,",
"Create your models here. from Author.models import Author, FriendRequest, Friends from Posts.models import",
"<reponame>cmput404-ahyyy/group-webproject from django.db import models # Create your models here. from Author.models import",
"your models here. from Author.models import Author, FriendRequest, Friends from Posts.models import Post,",
"django.db import models # Create your models here. from Author.models import Author, FriendRequest,",
"models # Create your models here. from Author.models import Author, FriendRequest, Friends from",
"from django.db import models # Create your models here. from Author.models import Author,"
] |
[
"# def tensor_to_numpy(t): # sess = K.get_session() # t_np = sess.run(t) # #",
"K.get_session() # t_np = sess.run(t) # # Get rid of the extra dimension",
"t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model): # From",
"WIDTH, 1) # def tensor_to_numpy(t): # sess = K.get_session() # t_np = sess.run(t)",
"sess.run(t) # # Get rid of the extra dimension # t_np = t_np.reshape(1,",
"return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer",
"# From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers:",
"mnist models and manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\",",
"input_layer for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel =",
"https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes =",
"WIDTH, 1) # return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape)",
"Helper methods and variables for mnist models and manifolds ''' color_list = [",
"variables for mnist models and manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\",",
"t_np = sess.run(t) # # Get rid of the extra dimension # t_np",
"manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\",",
"# t_np = sess.run(t) # # Get rid of the extra dimension #",
"4D np array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess =",
"the extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np",
"keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer =",
"''' Helper methods and variables for mnist models and manifolds ''' color_list =",
"\"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns",
"\"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D np array",
"prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer)",
"keras ''' Helper methods and variables for mnist models and manifolds ''' color_list",
"\"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D np",
"def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer",
"tensor_to_numpy(t): # sess = K.get_session() # t_np = sess.run(t) # # Get rid",
"[ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] #",
"] # # Returns 4D np array (1, HEIGHT, WIDTH, 1) # def",
"np array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess = K.get_session()",
"extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def",
"HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer =",
"# Get rid of the extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH,",
"and manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\",",
"= t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386",
"HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess = K.get_session() # t_np =",
"\"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D np array (1, HEIGHT, WIDTH,",
"\"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # #",
"models and manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\",",
"\"peru\", ] # # Returns 4D np array (1, HEIGHT, WIDTH, 1) #",
"Returns 4D np array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess",
"= [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ]",
"rid of the extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) #",
"\"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D np array (1,",
"def tensor_to_numpy(t): # sess = K.get_session() # t_np = sess.run(t) # # Get",
"layer in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel = keras.models.Model([input_layer], [prev_layer])",
"\"fuchsia\", \"peru\", ] # # Returns 4D np array (1, HEIGHT, WIDTH, 1)",
"1) # def tensor_to_numpy(t): # sess = K.get_session() # t_np = sess.run(t) #",
"Get rid of the extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1)",
"= input_layer for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel",
"1) # return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer",
"# # Returns 4D np array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t):",
"array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess = K.get_session() #",
"t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer",
"for mnist models and manifolds ''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\",",
"# sess = K.get_session() # t_np = sess.run(t) # # Get rid of",
"for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel = keras.models.Model([input_layer],",
"seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel = keras.models.Model([input_layer], [prev_layer]) return funcmodel",
"\"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D",
"= K.get_session() # t_np = sess.run(t) # # Get rid of the extra",
"(1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): # sess = K.get_session() # t_np",
"methods and variables for mnist models and manifolds ''' color_list = [ \"red\",",
"From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes",
"import keras ''' Helper methods and variables for mnist models and manifolds '''",
"input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes = []",
"# return t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer =",
"convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in",
"and variables for mnist models and manifolds ''' color_list = [ \"red\", \"orange\",",
"# Returns 4D np array (1, HEIGHT, WIDTH, 1) # def tensor_to_numpy(t): #",
"= keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for layer in seq_model.layers: layer._inbound_nodes = [] prev_layer",
"of the extra dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return",
"# # Get rid of the extra dimension # t_np = t_np.reshape(1, HEIGHT,",
"# t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model): #",
"in seq_model.layers: layer._inbound_nodes = [] prev_layer = layer(prev_layer) funcmodel = keras.models.Model([input_layer], [prev_layer]) return",
"sess = K.get_session() # t_np = sess.run(t) # # Get rid of the",
"= sess.run(t) # # Get rid of the extra dimension # t_np =",
"t_np def convert_to_model(seq_model): # From https://github.com/keras-team/keras/issues/10386 input_layer = keras.layers.Input(batch_shape=seq_model.layers[0].input_shape) prev_layer = input_layer for",
"''' color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\",",
"dimension # t_np = t_np.reshape(1, HEIGHT, WIDTH, 1) # return t_np def convert_to_model(seq_model):",
"color_list = [ \"red\", \"orange\", \"yellow\", \"lime\", \"green\", \"cyan\", \"blue\", \"purple\", \"fuchsia\", \"peru\",",
"\"blue\", \"purple\", \"fuchsia\", \"peru\", ] # # Returns 4D np array (1, HEIGHT,"
] |
[
"c == target[i]: i += 1 if i == len(target): result.append(word) break return",
"s): # Write your code here result = [] for word in s:",
"getAns(self, target, s): # Write your code here result = [] for word",
"@param s: @return: output all strings containing target in s \"\"\" def getAns(self,",
"\"\"\" def getAns(self, target, s): # Write your code here result = []",
"@return: output all strings containing target in s \"\"\" def getAns(self, target, s):",
"all strings containing target in s \"\"\" def getAns(self, target, s): # Write",
"target: the target string @param s: @return: output all strings containing target in",
"= [] for word in s: i = 0 for c in word:",
"result = [] for word in s: i = 0 for c in",
"in s: i = 0 for c in word: if c == target[i]:",
"= 0 for c in word: if c == target[i]: i += 1",
"c in word: if c == target[i]: i += 1 if i ==",
"[] for word in s: i = 0 for c in word: if",
"s: @return: output all strings containing target in s \"\"\" def getAns(self, target,",
"target string @param s: @return: output all strings containing target in s \"\"\"",
"the target string @param s: @return: output all strings containing target in s",
"string @param s: @return: output all strings containing target in s \"\"\" def",
"word in s: i = 0 for c in word: if c ==",
"s: i = 0 for c in word: if c == target[i]: i",
"@param target: the target string @param s: @return: output all strings containing target",
"here result = [] for word in s: i = 0 for c",
"0 for c in word: if c == target[i]: i += 1 if",
"output all strings containing target in s \"\"\" def getAns(self, target, s): #",
"def getAns(self, target, s): # Write your code here result = [] for",
"== target[i]: i += 1 if i == len(target): result.append(word) break return result",
"containing target in s \"\"\" def getAns(self, target, s): # Write your code",
"in word: if c == target[i]: i += 1 if i == len(target):",
"\"\"\" @param target: the target string @param s: @return: output all strings containing",
"strings containing target in s \"\"\" def getAns(self, target, s): # Write your",
"i = 0 for c in word: if c == target[i]: i +=",
"word: if c == target[i]: i += 1 if i == len(target): result.append(word)",
"if c == target[i]: i += 1 if i == len(target): result.append(word) break",
"s \"\"\" def getAns(self, target, s): # Write your code here result =",
"Write your code here result = [] for word in s: i =",
"for c in word: if c == target[i]: i += 1 if i",
"code here result = [] for word in s: i = 0 for",
"for word in s: i = 0 for c in word: if c",
"target, s): # Write your code here result = [] for word in",
"Solution: \"\"\" @param target: the target string @param s: @return: output all strings",
"target in s \"\"\" def getAns(self, target, s): # Write your code here",
"your code here result = [] for word in s: i = 0",
"class Solution: \"\"\" @param target: the target string @param s: @return: output all",
"# Write your code here result = [] for word in s: i",
"in s \"\"\" def getAns(self, target, s): # Write your code here result"
] |
[
"import render,render_to_response from django.contrib import auth from django.http import HttpResponseRedirect from django.template.context_processors import",
"from django.shortcuts import render,render_to_response from django.contrib import auth from django.http import HttpResponseRedirect from",
"username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if",
"password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user is not None:",
"args['login_error'] = \"Не верный логин или пароль\" return render_to_response('users/login.html', args) else: return render(request,",
"auth from django.http import HttpResponseRedirect from django.template.context_processors import csrf def login(request): args =",
"верный логин или пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html') def logout(request):",
"render,render_to_response from django.contrib import auth from django.http import HttpResponseRedirect from django.template.context_processors import csrf",
"\"\") user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return",
"django.http import HttpResponseRedirect from django.template.context_processors import csrf def login(request): args = {} args.update(csrf(request))",
"request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user is",
"пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html') def logout(request): auth.logout(request) return HttpResponseRedirect(\"/\")",
"{} args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\",",
"user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или пароль\" return render_to_response('users/login.html',",
"import HttpResponseRedirect from django.template.context_processors import csrf def login(request): args = {} args.update(csrf(request)) if",
"args = {} args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\", \"\") password",
"not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или",
"csrf def login(request): args = {} args.update(csrf(request)) if request.method == \"POST\": username =",
"None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или пароль\"",
"else: args['login_error'] = \"Не верный логин или пароль\" return render_to_response('users/login.html', args) else: return",
"is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин",
"django.template.context_processors import csrf def login(request): args = {} args.update(csrf(request)) if request.method == \"POST\":",
"логин или пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html') def logout(request): auth.logout(request)",
"user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный",
"auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или пароль\" return",
"from django.contrib import auth from django.http import HttpResponseRedirect from django.template.context_processors import csrf def",
"from django.http import HttpResponseRedirect from django.template.context_processors import csrf def login(request): args = {}",
"login(request): args = {} args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\", \"\")",
"def login(request): args = {} args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\",",
"= request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,",
"request.method == \"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user =",
"или пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html') def logout(request): auth.logout(request) return",
"from django.template.context_processors import csrf def login(request): args = {} args.update(csrf(request)) if request.method ==",
"if request.method == \"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user",
"= request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user",
"\"Не верный логин или пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html') def",
"<filename>for-proriv/myfuture/users/views.py from django.shortcuts import render,render_to_response from django.contrib import auth from django.http import HttpResponseRedirect",
"django.shortcuts import render,render_to_response from django.contrib import auth from django.http import HttpResponseRedirect from django.template.context_processors",
"import auth from django.http import HttpResponseRedirect from django.template.context_processors import csrf def login(request): args",
"django.contrib import auth from django.http import HttpResponseRedirect from django.template.context_processors import csrf def login(request):",
"= {} args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\", \"\") password =",
"request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user)",
"== \"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username,",
"\"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password)",
"\"\") password = request.POST.get(\"password\", \"\") user = auth.authenticate(username=username, password=password) if user is not",
"= auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else:",
"args.update(csrf(request)) if request.method == \"POST\": username = request.POST.get(\"username\", \"\") password = request.POST.get(\"password\", \"\")",
"= \"Не верный логин или пароль\" return render_to_response('users/login.html', args) else: return render(request, 'users/login.html')",
"HttpResponseRedirect from django.template.context_processors import csrf def login(request): args = {} args.update(csrf(request)) if request.method",
"import csrf def login(request): args = {} args.update(csrf(request)) if request.method == \"POST\": username",
"return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или пароль\" return render_to_response('users/login.html', args)",
"password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] =",
"HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не верный логин или пароль\" return render_to_response('users/login.html', args) else:",
"auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error']",
"user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\")",
"if user is not None: auth.login(request, user) return HttpResponseRedirect(\"/\") else: args['login_error'] = \"Не"
] |
[
"def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials if correct, authenticate the",
"def router(url): if url=='/home': return app_layout() elif url=='/login': return login_layout() else: return login_layout()",
"app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ]",
"@app.callback( # Output('...'), # [Input('...')] # ) # def func(...): # ... @app.callback(",
"'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials if correct, authenticate",
"'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password',",
"@app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### #",
"return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')],",
"if correct, authenticate the session otherwise, authenticate the session and send user to",
"see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ])",
"], ) ] ) # main app layout app.layout = html.Div( [ dcc.Location(id='url',",
"dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output, State",
"to login ''' if n_clicks is None \\ and n_submit_email is None \\",
"[Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click",
"dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'),",
"else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email','",
"box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'),",
"############################################################################### # @app.callback( # Output('...'), # [Input('...')] # ) # def func(...): #",
"], body=True ), width=6 ), justify='center' ) ] ) ] ) # home",
") ] ) ] ) # home layout content are_sure = dbc.Modal( [",
"... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ###############################################################################",
"# utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url):",
"id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page =",
"@app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email',",
"return True, None else: return is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback(",
"are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col(",
",pw): ''' check credentials if correct, authenticate the session otherwise, authenticate the session",
"[ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger',",
"credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the",
"session otherwise, authenticate the session and send user to login ''' if n_clicks",
"html.Br(), html.H6(\"Change the value in the text box to see callbacks in action!\"),",
"[State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials",
"is None: return no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure',",
"the session and send user to login''' if n_clicks is None: return no_update",
"login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password',",
"login''' if n_clicks is None: return no_update session['authed'] = False return '/login' @app.callback(",
"authenticate the session and send user to login ''' if n_clicks is None",
"dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button',",
"from dash import no_update from flask import session # local imports from auth",
"dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit',",
"'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click is not None:",
"dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True,",
"text box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(),",
"= html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the text box to",
"return False, None elif logout_click is not None: return True, None else: return",
"autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ),",
"[Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app ###############################################################################",
"id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in",
"), justify='center' ) ] ) ] ) # home layout content are_sure =",
"]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page,",
"otherwise, authenticate the session and send user to login ''' if n_clicks is",
"url=='/login': return login_layout() else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')],",
"None: return no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')],",
"from auth import authenticate_user, validate_login_session from server import app, server, ui # login",
"dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ],",
"Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click is not",
"justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(),",
"autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container(",
"the session and send user to login ''' if n_clicks is None \\",
"# @app.callback( # Output('...'), # [Input('...')] # ) # def func(...): # ...",
"as dbc import dash_html_components as html import dash_core_components as dcc from dash.dependencies import",
"placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True",
"session # local imports from auth import authenticate_user, validate_login_session from server import app,",
"[ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, )",
"the text box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True),",
"is None \\ and n_submit_email is None \\ and n_submit_password is None: return",
"[Input('...')] # ) # def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')]",
"check credentials if correct, authenticate the session otherwise, authenticate the session and send",
"import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output,",
"\\ and n_submit_password is None: return no_update, no_update credentials = {'user':email, \"password\":pw} if",
"# home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter(",
"credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed']",
"import app, server, ui # login layout content def login_layout(): return html.Div( [",
"dbc import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input,",
"None \\ and n_submit_password is None: return no_update, no_update credentials = {'user':email, \"password\":pw}",
"# Output('...'), # [Input('...')] # ) # def func(...): # ... @app.callback( Output(component_id='my-output',",
"elif logout_click is not None: return True, None else: return is_open, close_click ###############################################################################",
"and n_submit_password is None: return no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials):",
"ui # login layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False),",
"[ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email',",
"imports from auth import authenticate_user, validate_login_session from server import app, server, ui #",
"'/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], )",
"State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials if correct,",
"id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br() ], ) ] )",
"Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open):",
"close_click is not None: return False, None elif logout_click is not None: return",
"= html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### #",
"def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app ############################################################################### if __name__ ==",
"dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br() ],",
"session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure',",
"''' check credentials if correct, authenticate the session otherwise, authenticate the session and",
"color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session",
"{'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed'] = False",
"no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks):",
"# [Input('...')] # ) # def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input',",
"component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app",
"dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6",
"import no_update from flask import session # local imports from auth import authenticate_user,",
"html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### # utilities ############################################################################### # router @app.callback(",
"server import app, server, ui # login layout content def login_layout(): return html.Div(",
"dcc from dash.dependencies import Input, Output, State from dash import no_update from flask",
"home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row(",
"layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row(",
"html.H6(\"Change the value in the text box to see callbacks in action!\"), dbc.Input(id='my-input',",
"# def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value):",
"test!\"), html.Br(), html.H6(\"Change the value in the text box to see callbacks in",
") ############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] )",
"authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ],",
"n_clicks is None \\ and n_submit_email is None \\ and n_submit_password is None:",
"[Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks,",
"authenticate the session otherwise, authenticate the session and send user to login '''",
"logout_modal(logout_click, close_click, is_open): if close_click is not None: return False, None elif logout_click",
"[Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session and send user to login'''",
"the value in the text box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial",
"dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True,",
"html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col(",
"server, ui # login layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login',",
"import dash import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as",
"authenticate_user, validate_login_session from server import app, server, ui # login layout content def",
"else: return is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'), #",
"as dcc from dash.dependencies import Input, Output, State from dash import no_update from",
"html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' ) ] ) ] )",
"True return '/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True)",
"'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click,",
"[State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click is not None: return",
"dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout',",
"= {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed'] =",
"update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app ############################################################################### if __name__ == \"__main__\":",
"[ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### # utilities ###############################################################################",
"the session otherwise, authenticate the session and send user to login ''' if",
"], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check",
"'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email,",
"dash import no_update from flask import session # local imports from auth import",
"refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password',",
"html import dash_core_components as dcc from dash.dependencies import Input, Output, State from dash",
"package imports import dash import dash_bootstrap_components as dbc import dash_html_components as html import",
"login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [",
"is None \\ and n_submit_password is None: return no_update, no_update credentials = {'user':email,",
"local imports from auth import authenticate_user, validate_login_session from server import app, server, ui",
"############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def",
") # def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def",
"], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value",
"test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4",
"True, None else: return is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback( #",
"authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect",
"auth import authenticate_user, validate_login_session from server import app, server, ui # login layout",
") def logout_(n_clicks): '''clear the session and send user to login''' if n_clicks",
") def logout_modal(logout_click, close_click, is_open): if close_click is not None: return False, None",
"dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear",
"Output, State from dash import no_update from flask import session # local imports",
"return no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return",
"block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' ) ] ) ]",
"close_click, is_open): if close_click is not None: return False, None elif logout_click is",
"content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\",",
") # home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"),",
"test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the text box",
"content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col(",
"in the text box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text',",
"from flask import session # local imports from auth import authenticate_user, validate_login_session from",
"import Input, Output, State from dash import no_update from flask import session #",
"size='sm'), width=4 ), justify='center' ), html.Br() ], ) ] ) # main app",
"'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def",
"action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout():",
"type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center'",
"validate_login_session from server import app, server, ui # login layout content def login_layout():",
"pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True),",
"justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center'",
"[Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'),",
"return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login',",
"html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(),",
"send user to login''' if n_clicks is None: return no_update session['authed'] = False",
") def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app ############################################################################### if __name__",
"app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ),",
"return is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')]",
"Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw):",
"type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'),",
"'/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url',",
"value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\",
"dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success',",
"is not None: return False, None elif logout_click is not None: return True,",
"dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password',",
"############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')] # ) #",
") # main app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(),",
"'''clear the session and send user to login''' if n_clicks is None: return",
"), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the",
"# router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home': return",
"Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run",
"if n_clicks is None: return no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure',",
"you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ),",
"send user to login ''' if n_clicks is None \\ and n_submit_email is",
"Output('...'), # [Input('...')] # ) # def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'),",
"dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\",",
"no_update from flask import session # local imports from auth import authenticate_user, validate_login_session",
"elif url=='/login': return login_layout() else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert',",
"block=True, size='sm'), width=4 ), justify='center' ), html.Br() ], ) ] ) # main",
"'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials if",
"to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure,",
"'pathname')] ) def router(url): if url=='/home': return app_layout() elif url=='/login': return login_layout() else:",
"Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home': return app_layout() elif url=='/login':",
"body=True ), width=6 ), justify='center' ) ] ) ] ) # home layout",
"component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}' ############################################################################### # run app ############################################################################### if",
"dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return",
"not None: return True, None else: return is_open, close_click ############################################################################### # callbacks ###############################################################################",
"flask import session # local imports from auth import authenticate_user, validate_login_session from server",
"@validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ),",
"dash import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as dcc",
"def logout_modal(logout_click, close_click, is_open): if close_click is not None: return False, None elif",
"False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] )",
"n_clicks is None: return no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'),",
"False, None elif logout_click is not None: return True, None else: return is_open,",
"from server import app, server, ui # login layout content def login_layout(): return",
"user to login ''' if n_clicks is None \\ and n_submit_email is None",
"html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [",
"'<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): '''",
"n_submit_password is None: return no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed']",
"centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the",
"None: return True, None else: return is_open, close_click ############################################################################### # callbacks ############################################################################### #",
"''' if n_clicks is None \\ and n_submit_email is None \\ and n_submit_password",
"), justify='center' ), html.Br() ], ) ] ) # main app layout app.layout",
"), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ),",
"as html import dash_core_components as dcc from dash.dependencies import Input, Output, State from",
"className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert')",
"return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def",
"return f'Output: {input_value}' ############################################################################### # run app ############################################################################### if __name__ == \"__main__\": ui.run()",
"no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'),",
"logout_click is not None: return True, None else: return is_open, close_click ############################################################################### #",
"layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] )",
"if url=='/home': return app_layout() elif url=='/login': return login_layout() else: return login_layout() # authenticate",
"] ) # home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you",
"), html.Br() ], ) ] ) # main app layout app.layout = html.Div(",
"in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def",
"return app_layout() elif url=='/login': return login_layout() else: return login_layout() # authenticate @app.callback( [Output('url',",
"html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### # utilities",
"value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([",
"n_submit_email, n_submit_password, email ,pw): ''' check credentials if correct, authenticate the session otherwise,",
"dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User',",
"html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'),",
"dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")),",
"sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ],",
"), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ),",
"app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ###############################################################################",
"to login''' if n_clicks is None: return no_update session['authed'] = False return '/login'",
"'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session and send user to",
"'' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'),",
") def router(url): if url=='/home': return app_layout() elif url=='/login': return login_layout() else: return",
"utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if",
"), ] ) ############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url',",
"router(url): if url=='/home': return app_layout() elif url=='/login': return login_layout() else: return login_layout() #",
"None: return False, None elif logout_click is not None: return True, None else:",
"and send user to login''' if n_clicks is None: return no_update session['authed'] =",
"Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password,",
"] ) # main app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div(",
"\\ and n_submit_email is None \\ and n_submit_password is None: return no_update, no_update",
"html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br()",
"placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ),",
"@app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session and send",
"None elif logout_click is not None: return True, None else: return is_open, close_click",
"def logout_(n_clicks): '''clear the session and send user to login''' if n_clicks is",
"session and send user to login''' if n_clicks is None: return no_update session['authed']",
"imports import dash import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components",
") ] ) # main app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False),",
"id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' ) ]",
"from dash.dependencies import Input, Output, State from dash import no_update from flask import",
"None else: return is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'),",
"id='page-content' ), ] ) ############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content', 'children'),",
"dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row( dbc.Col( dbc.Button('Logout', id='logout-button',",
"dash_core_components as dcc from dash.dependencies import Input, Output, State from dash import no_update",
"dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### # utilities ############################################################################### #",
"[ dbc.Row( dbc.Col( dbc.Card( [ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'),",
"import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as dcc from",
") test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the text",
"n_submit_email is None \\ and n_submit_password is None: return no_update, no_update credentials =",
"html.Br() ], ) ] ) # main app layout app.layout = html.Div( [",
"dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\",",
"return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(),",
"main app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content' ),",
"# package imports import dash import dash_bootstrap_components as dbc import dash_html_components as html",
"), width=6 ), justify='center' ) ] ) ] ) # home layout content",
"refresh=False), html.Div( login_layout(), id='page-content' ), ] ) ############################################################################### # utilities ############################################################################### # router",
"@app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home': return app_layout() elif",
"email ,pw): ''' check credentials if correct, authenticate the session otherwise, authenticate the",
"def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return",
"callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')] # ) # def func(...):",
"width=4 ), justify='center' ), html.Br() ], ) ] ) # main app layout",
"False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure',",
"State from dash import no_update from flask import session # local imports from",
"[ html.H4('Login', className='card-title'), dbc.Input(id='login-email', placeholder='User', autoFocus=True), dbc.Input(id='login-password', placeholder='Password', type='password'), dbc.Button('Submit', id='login-button', color='success', block=True),",
"[ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ],",
"func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output:",
"login_layout() else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'),",
"# authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'),",
"return '/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback(",
"logout_(n_clicks): '''clear the session and send user to login''' if n_clicks is None:",
"login_layout(), id='page-content' ), ] ) ############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content',",
"no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home',",
"'n_clicks')] ) def logout_(n_clicks): '''clear the session and send user to login''' if",
"# login layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container(",
"callbacks in action!\"), dbc.Input(id='my-input', value='initial value', type='text', autoFocus=True), html.Br(), html.Div(id='my-output'), are_sure, ]) @validate_login_session",
"'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click is",
"Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session and send user",
"if authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed'] = False return no_update,",
"dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')] ) def logout_(n_clicks): '''clear the session and",
"'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home': return app_layout() elif url=='/login': return",
"is_open, close_click ############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')] #",
"# callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')] # ) # def",
"no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home', ''",
"justify='center' ) ] ) ] ) # home layout content are_sure = dbc.Modal(",
"dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", )",
"def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center'",
"color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br() ], ) ] ) #",
") ] ) # home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are",
"html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' ) ] ) ] ) #",
"import session # local imports from auth import authenticate_user, validate_login_session from server import",
"user to login''' if n_clicks is None: return no_update session['authed'] = False return",
"dash.dependencies import Input, Output, State from dash import no_update from flask import session",
"= dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\",",
"dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br() ], ) ]",
"'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click, close_click, is_open): if",
"is_open): if close_click is not None: return False, None elif logout_click is not",
") ), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change",
"html.Div([ html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the text box to see",
"# ) # def func(...): # ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] )",
"] ) ############################################################################### # utilities ############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')]",
"correct, authenticate the session otherwise, authenticate the session and send user to login",
"dbc.Button('Submit', id='login-button', color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' )",
"dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([",
"color='success', block=True), html.Br(), html.Div(id='login-alert') ], body=True ), width=6 ), justify='center' ) ] )",
"None \\ and n_submit_email is None \\ and n_submit_password is None: return no_update,",
"# main app layout app.layout = html.Div( [ dcc.Location(id='url', refresh=False), html.Div( login_layout(), id='page-content'",
"router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home': return app_layout()",
"dbc.Col( dbc.Button('Logout', id='logout-button', color='danger', block=True, size='sm'), width=4 ), justify='center' ), html.Br() ], )",
"'is_open')], ) def logout_modal(logout_click, close_click, is_open): if close_click is not None: return False,",
"not None: return False, None elif logout_click is not None: return True, None",
"layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [",
"if n_clicks is None \\ and n_submit_email is None \\ and n_submit_password is",
"login ''' if n_clicks is None \\ and n_submit_email is None \\ and",
"\\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row( dbc.Col( test_page, ), justify='center' ), html.Br(), dbc.Row(",
"login layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [",
"url=='/home': return app_layout() elif url=='/login': return login_layout() else: return login_layout() # authenticate @app.callback(",
"id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI",
"credentials if correct, authenticate the session otherwise, authenticate the session and send user",
"Input, Output, State from dash import no_update from flask import session # local",
"and send user to login ''' if n_clicks is None \\ and n_submit_email",
"close_click ############################################################################### # callbacks ############################################################################### # @app.callback( # Output('...'), # [Input('...')] # )",
"def login_layout(): return html.Div( [ dcc.Location(id='login-url', pathname='/login', refresh=False), dbc.Container( [ dbc.Row( dbc.Col( dbc.Card(",
"n_submit_password, email ,pw): ''' check credentials if correct, authenticate the session otherwise, authenticate",
"html.Div(id='my-output'), are_sure, ]) @validate_login_session def app_layout(): return \\ html.Div([ dcc.Location(id='home-url',pathname='/home'), dbc.Container( [ dbc.Row(",
"is None: return no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] =",
"[Input('url', 'pathname')] ) def router(url): if url=='/home': return app_layout() elif url=='/login': return login_layout()",
"None: return no_update, no_update credentials = {'user':email, \"password\":pw} if authenticate_user(credentials): session['authed'] = True",
"n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')]) def login_auth(n_clicks, n_submit_email, n_submit_password, email",
"app_layout() elif url=='/login': return login_layout() else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'),",
"app, server, ui # login layout content def login_layout(): return html.Div( [ dcc.Location(id='login-url',",
"], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page = html.Div([ html.H1(\"DashUI test!\"),",
"session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure',",
"# ... @app.callback( Output(component_id='my-output', component_property='children'), [Input(component_id='my-input', component_property='value')] ) def update_output_div(input_value): return f'Output: {input_value}'",
"import dash_core_components as dcc from dash.dependencies import Input, Output, State from dash import",
"login_auth(n_clicks, n_submit_email, n_submit_password, email ,pw): ''' check credentials if correct, authenticate the session",
"session and send user to login ''' if n_clicks is None \\ and",
"@app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def",
"= False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')],",
"[Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button', 'n_clicks'), Input('close-are_sure', 'n_clicks')], [State('modal-are_sure', 'is_open')], ) def logout_modal(logout_click,",
"Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'), Input('login-password', '<PASSWORD>'), ], [State('login-email', 'value'), State('login-password', 'value')])",
"# local imports from auth import authenticate_user, validate_login_session from server import app, server,",
"\"password\":pw} if authenticate_user(credentials): session['authed'] = True return '/home', '' session['authed'] = False return",
"return no_update session['authed'] = False return '/login' @app.callback( [Output('modal-are_sure', 'is_open'), Output('close-are_sure', 'n_clicks')], [Input('logout-button',",
"dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as dcc from dash.dependencies",
"= True return '/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.', color='danger',",
"############################################################################### # router @app.callback( Output('page-content', 'children'), [Input('url', 'pathname')] ) def router(url): if url=='/home':",
"return login_layout() else: return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button',",
"dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")), dbc.Col(dbc.Button(\"Close\", id=\"close-are_sure\")), ], justify=\"center\", ) ), ], id=\"modal-are_sure\", centered=True, ) test_page",
"= False return no_update, dbc.Alert('Incorrect credentials.', color='danger', dismissable=True) @app.callback( Output('home-url', 'pathname'), [Input('yes-are_sure', 'n_clicks')]",
"width=6 ), justify='center' ) ] ) ] ) # home layout content are_sure",
"html.H1(\"DashUI test!\"), html.Br(), html.H6(\"Change the value in the text box to see callbacks",
"value in the text box to see callbacks in action!\"), dbc.Input(id='my-input', value='initial value',",
"and n_submit_email is None \\ and n_submit_password is None: return no_update, no_update credentials",
"if close_click is not None: return False, None elif logout_click is not None:",
"import authenticate_user, validate_login_session from server import app, server, ui # login layout content",
"justify='center' ), html.Br() ], ) ] ) # main app layout app.layout =",
"session['authed'] = True return '/home', '' session['authed'] = False return no_update, dbc.Alert('Incorrect credentials.',",
"are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"), dbc.ModalBody(\"Are you sure?\"), dbc.ModalFooter( dbc.Row( [ dbc.Col(dbc.Button(\"Yes\", id=\"yes-are_sure\")),",
"] ) ] ) # home layout content are_sure = dbc.Modal( [ dbc.ModalHeader(\"Logout\"),",
"return login_layout() # authenticate @app.callback( [Output('url', 'pathname'), Output('login-alert', 'children')], [Input('login-button', 'n_clicks'), Input('login-email',' n_submit'),",
"is not None: return True, None else: return is_open, close_click ############################################################################### # callbacks"
] |
[
"for line in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur = conn.cursor()",
"lines = [[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn()",
"open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur = conn.cursor() cur.executemany(sql, lines) conn.commit()",
"dbconf sql = 'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for",
"[[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur =",
"(concept_name) VALUES (?)' lines = [[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()]",
"= [[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur",
"import dbconf sql = 'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()]",
"<reponame>myxxxsquared/search_concept import dbconf sql = 'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines =",
"line in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur = conn.cursor() cur.executemany(sql,",
"in open('names.txt', encoding='utf8') if line.strip()] conn = dbconf.getconn() cur = conn.cursor() cur.executemany(sql, lines)",
"(?)' lines = [[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()] conn =",
"VALUES (?)' lines = [[line.strip()] for line in open('names.txt', encoding='utf8') if line.strip()] conn",
"`search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for line in open('names.txt', encoding='utf8') if",
"= 'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for line in",
"INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for line in open('names.txt', encoding='utf8')",
"sql = 'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for line",
"'INSERT INTO `search_concept` (concept_name) VALUES (?)' lines = [[line.strip()] for line in open('names.txt',"
] |
[
"cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if key==81 or key==113: break webcam.release()",
"cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image)",
"255, 0), 3) cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1,",
"#Choose an image to detect faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read,",
"Face Detection', frame) key = cv2.waitKey(1) if key==81 or key==113: break webcam.release() def",
"key is pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] == \"--image\": image",
"else: print(\"Must use --image [path to image] or --webcam\") else: print(\"Must use --image",
"faces i=0 for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame,",
"grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0",
"# Draw rectangle around faces i=0 for face in face_coordinates: (x, y, w,",
"image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image",
"= face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected",
"Detection', frame) key = cv2.waitKey(1) if key==81 or key==113: break webcam.release() def Image(img):",
"elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image [path to image] or",
"sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image [path to",
"cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect faces in webcam = cv2.VideoCapture(0)",
"cv2.LINE_AA) i += 1 #Show the opencv image cv2.imshow('opencv Face Detector', img) #Wait",
"w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3)",
"algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect faces in",
"i=0 for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x,",
"255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1)",
"= cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle",
"image cv2.imshow('opencv Face Detector', img) #Wait until a key is pressed cv2.waitKey() if",
"webcam.release() def Image(img): img = cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img,",
"img) #Wait until a key is pressed cv2.waitKey() if len(sys.argv) > 1: if",
"from random import * #Load pre-trained data on face frontals from opencv (haar",
"import * #Load pre-trained data on face frontals from opencv (haar cascade algorithm)",
"3) cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255,",
"key==81 or key==113: break webcam.release() def Image(img): img = cv2.imread(img) #Convert image to",
"face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w,",
"print(\"Must use --image [path to image] or --webcam\") else: print(\"Must use --image [path",
"+= 1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if key==81 or key==113:",
"cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if key==81",
"if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam()",
"key = cv2.waitKey(1) if key==81 or key==113: break webcam.release() def Image(img): img =",
"in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h),",
"cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 #Show the opencv",
"y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0),",
"cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect faces",
"i += 1 #Show the opencv image cv2.imshow('opencv Face Detector', img) #Wait until",
"Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image [path to image]",
"True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)",
"(x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1), (x,",
"frame) key = cv2.waitKey(1) if key==81 or key==113: break webcam.release() def Image(img): img",
"cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around",
"0), 3) cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,",
"cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face",
"face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face",
"(x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 #Show",
"+= 1 #Show the opencv image cv2.imshow('opencv Face Detector', img) #Wait until a",
"to image] or --webcam\") else: print(\"Must use --image [path to image] or --webcam\")",
"face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face in face_coordinates:",
"cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection',",
"y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20),",
"where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0",
"= cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the",
"(255, 255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame) key",
"trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect faces in webcam",
"face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face",
"sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image [path to image] or --webcam\")",
"successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates",
"cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),",
"Draw rectangle around faces i=0 for face in face_coordinates: (x, y, w, h)",
"(x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256),",
"y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 #Show the",
"randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,",
"(255, 255, 255), 2, cv2.LINE_AA) i += 1 #Show the opencv image cv2.imshow('opencv",
"cv2 from random import * #Load pre-trained data on face frontals from opencv",
"key==113: break webcam.release() def Image(img): img = cv2.imread(img) #Convert image to grayscale grayscaled_img",
"1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces",
"<reponame>joelwright-dev/PyFaceDetection<gh_stars>0 import sys import cv2 from random import * #Load pre-trained data on",
"while True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame,",
"(x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255,",
"#Load pre-trained data on face frontals from opencv (haar cascade algorithm) trained_data =",
"image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates",
"random import * #Load pre-trained data on face frontals from opencv (haar cascade",
"3) cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255,",
"frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw",
"(x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face ' + str(i+1), (x,",
"1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if key==81 or key==113: break",
"h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img,",
"Webcam(): #Choose an image to detect faces in webcam = cv2.VideoCapture(0) while True:",
"255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame) key =",
"a key is pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] == \"--image\":",
"2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if",
"an image to detect faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame",
"= webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img)",
"= cv2.waitKey(1) if key==81 or key==113: break webcam.release() def Image(img): img = cv2.imread(img)",
"data on face frontals from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def",
"i += 1 cv2.imshow('opencv Face Detection', frame) key = cv2.waitKey(1) if key==81 or",
"y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1),",
"pre-trained data on face frontals from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')",
"to detect faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read()",
"(haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect",
"detect faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame",
"cv2.waitKey(1) if key==81 or key==113: break webcam.release() def Image(img): img = cv2.imread(img) #Convert",
"webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) #",
"def Webcam(): #Choose an image to detect faces in webcam = cv2.VideoCapture(0) while",
"y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face",
"Image(img): img = cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect",
"in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h),",
"cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),",
"to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates =",
"255), 2, cv2.LINE_AA) i += 1 #Show the opencv image cv2.imshow('opencv Face Detector',",
"[path to image] or --webcam\") else: print(\"Must use --image [path to image] or",
"cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle",
"the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for",
"face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256),",
"\"--webcam\": Webcam() else: print(\"Must use --image [path to image] or --webcam\") else: print(\"Must",
"faces i=0 for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img,",
"(x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv",
"image to detect faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame =",
"i=0 for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x,",
"for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y),",
"= cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to detect faces in webcam =",
"from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image",
"in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame,",
"#Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is",
"grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) #",
"= sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use --image [path",
"== \"--webcam\": Webcam() else: print(\"Must use --image [path to image] or --webcam\") else:",
"cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face '",
"trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face in face_coordinates: (x, y,",
"Detector', img) #Wait until a key is pressed cv2.waitKey() if len(sys.argv) > 1:",
"sys import cv2 from random import * #Load pre-trained data on face frontals",
"--image [path to image] or --webcam\") else: print(\"Must use --image [path to image]",
"import cv2 from random import * #Load pre-trained data on face frontals from",
"y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face ' + str(i+1),",
"face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0,",
"1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 #Show the opencv image",
"opencv image cv2.imshow('opencv Face Detector', img) #Wait until a key is pressed cv2.waitKey()",
"or key==113: break webcam.release() def Image(img): img = cv2.imread(img) #Convert image to grayscale",
"face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face",
"cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face '",
"#Wait until a key is pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1]",
"' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i",
"opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an image to",
"face frontals from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose",
"break webcam.release() def Image(img): img = cv2.imread(img) #Convert image to grayscale grayscaled_img =",
"cv2.imshow('opencv Face Detector', img) #Wait until a key is pressed cv2.waitKey() if len(sys.argv)",
"1 #Show the opencv image cv2.imshow('opencv Face Detector', img) #Wait until a key",
"on face frontals from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam():",
"is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face in",
"= face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected",
"import sys import cv2 from random import * #Load pre-trained data on face",
"w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3)",
"rectangle around faces i=0 for face in face_coordinates: (x, y, w, h) =",
"face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w,",
"= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw",
"h) = face_coordinates[i] cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame,",
"255, 255), 2, cv2.LINE_AA) i += 1 #Show the opencv image cv2.imshow('opencv Face",
"'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2,",
"2, cv2.LINE_AA) i += 1 #Show the opencv image cv2.imshow('opencv Face Detector', img)",
"== \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must",
"y, w, h) = face_coordinates[i] cv2.rectangle(img, (x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)),",
"image] or --webcam\") else: print(\"Must use --image [path to image] or --webcam\") print(\"---END---\")",
"faces in webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame =",
"(x, y), (x+w, y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' +",
"cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face",
"> 1: if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] ==",
"\"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else: print(\"Must use",
"for face in face_coordinates: (x, y, w, h) = face_coordinates[i] cv2.rectangle(frame, (x, y),",
"until a key is pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] ==",
"grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img)",
"use --image [path to image] or --webcam\") else: print(\"Must use --image [path to",
"Webcam() else: print(\"Must use --image [path to image] or --webcam\") else: print(\"Must use",
"face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)",
"1: if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\":",
"#Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces",
"is pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] == \"--image\": image =",
"(randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX,",
"* #Load pre-trained data on face frontals from opencv (haar cascade algorithm) trained_data",
"(x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(frame, 'Detected face ' +",
"if len(sys.argv) > 1: if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif",
"the opencv image cv2.imshow('opencv Face Detector', img) #Wait until a key is pressed",
"pressed cv2.waitKey() if len(sys.argv) > 1: if sys.argv[1] == \"--image\": image = sys.argv[2]",
"= cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img",
"sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1] == \"--webcam\": Webcam() else:",
"(0, 255, 0), 3) cv2.putText(frame, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX,",
"frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates =",
"= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for",
"cv2.COLOR_BGR2GRAY) #Detect where the face is face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around",
"if key==81 or key==113: break webcam.release() def Image(img): img = cv2.imread(img) #Convert image",
"Face Detector', img) #Wait until a key is pressed cv2.waitKey() if len(sys.argv) >",
"+ str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i +=",
"randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1,",
"webcam = cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1)",
"frontals from opencv (haar cascade algorithm) trained_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def Webcam(): #Choose an",
"around faces i=0 for face in face_coordinates: (x, y, w, h) = face_coordinates[i]",
"#Show the opencv image cv2.imshow('opencv Face Detector', img) #Wait until a key is",
"cv2.COLOR_BGR2GRAY) face_coordinates = trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face in",
"= trained_data.detectMultiScale(grayscaled_img) # Draw rectangle around faces i=0 for face in face_coordinates: (x,",
"str(i+1), (x, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) i += 1",
"y+h), (randrange(50,256), randrange(50,256), randrange(50,256)), 3) cv2.putText(img, 'Detected face ' + str(i+1), (x, y-20),",
"cv2.VideoCapture(0) while True: successful_frame_read, frame = webcam.read() frame = cv2.flip(frame, 1) grayscaled_img =",
"len(sys.argv) > 1: if sys.argv[1] == \"--image\": image = sys.argv[2] Image(image) elif sys.argv[1]",
"1, (255, 255, 255), 2, cv2.LINE_AA) i += 1 cv2.imshow('opencv Face Detection', frame)",
"img = cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Detect where",
"def Image(img): img = cv2.imread(img) #Convert image to grayscale grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)"
] |
[
"now 'local', '%Y' %} {{ cookiecutter.full_name }} {% if is_open_source -%} # Distributed",
"}} {% if is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license }}. See",
"{% if is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE",
"{{ cookiecutter.project_name }} project # # Copyright (c) {% now 'local', '%Y' %}",
"See LICENSE for more info. {% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name",
"-*- coding: utf-8 -*- # # This file is part of the {{",
"{% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name",
"}}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ =",
"{% set klass = cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license != 'Not",
"-%} {% set is_open_source = cookiecutter.open_source_license != 'Not open source' -%} # -*-",
"coding: utf-8 -*- # # This file is part of the {{ cookiecutter.project_name",
"__email__ = '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from .core import",
"= \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version",
"source' -%} # -*- coding: utf-8 -*- # # This file is part",
"cookiecutter.open_source_license }}. See LICENSE for more info. {% endif %} \"\"\"Top-level package for",
"'{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from .core import {{ klass",
"utf-8 -*- # # This file is part of the {{ cookiecutter.project_name }}",
"set klass = cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license != 'Not open",
"more info. {% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ =",
"= '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from .core import {{",
"cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from .core import {{ klass }}",
"info. {% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{",
"{% now 'local', '%Y' %} {{ cookiecutter.full_name }} {% if is_open_source -%} #",
"__author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ = '{{",
"<reponame>ALBA-Synchrotron/cookiecutter-albalib {% set klass = cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license !=",
"# # Copyright (c) {% now 'local', '%Y' %} {{ cookiecutter.full_name }} {%",
"-*- # # This file is part of the {{ cookiecutter.project_name }} project",
"}}. See LICENSE for more info. {% endif %} \"\"\"Top-level package for {{",
"\"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}'",
"'local', '%Y' %} {{ cookiecutter.full_name }} {% if is_open_source -%} # Distributed under",
"-%} # -*- coding: utf-8 -*- # # This file is part of",
"Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE for more info. {% endif",
"# Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE for more info. {%",
"{{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}'",
"the {{ cookiecutter.open_source_license }}. See LICENSE for more info. {% endif %} \"\"\"Top-level",
"cookiecutter.open_source_license != 'Not open source' -%} # -*- coding: utf-8 -*- # #",
"file is part of the {{ cookiecutter.project_name }} project # # Copyright (c)",
"the {{ cookiecutter.project_name }} project # # Copyright (c) {% now 'local', '%Y'",
"open source' -%} # -*- coding: utf-8 -*- # # This file is",
"of the {{ cookiecutter.project_name }} project # # Copyright (c) {% now 'local',",
"'%Y' %} {{ cookiecutter.full_name }} {% if is_open_source -%} # Distributed under the",
"part of the {{ cookiecutter.project_name }} project # # Copyright (c) {% now",
"'Not open source' -%} # -*- coding: utf-8 -*- # # This file",
"\"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ =",
"cookiecutter.full_name }} {% if is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license }}.",
"endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\"",
"set is_open_source = cookiecutter.open_source_license != 'Not open source' -%} # -*- coding: utf-8",
"# Copyright (c) {% now 'local', '%Y' %} {{ cookiecutter.full_name }} {% if",
"# This file is part of the {{ cookiecutter.project_name }} project # #",
"project # # Copyright (c) {% now 'local', '%Y' %} {{ cookiecutter.full_name }}",
"{{ cookiecutter.full_name }} {% if is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license",
"Copyright (c) {% now 'local', '%Y' %} {{ cookiecutter.full_name }} {% if is_open_source",
"klass = cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license != 'Not open source'",
"is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE for more",
"(c) {% now 'local', '%Y' %} {{ cookiecutter.full_name }} {% if is_open_source -%}",
"!= 'Not open source' -%} # -*- coding: utf-8 -*- # # This",
"is part of the {{ cookiecutter.project_name }} project # # Copyright (c) {%",
"# -*- coding: utf-8 -*- # # This file is part of the",
"%} {{ cookiecutter.full_name }} {% if is_open_source -%} # Distributed under the {{",
"-%} # Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE for more info.",
"}}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from .core",
"cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license != 'Not open source' -%} #",
"= cookiecutter.open_source_license != 'Not open source' -%} # -*- coding: utf-8 -*- #",
"cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__ = '{{ cookiecutter.version }}' from",
"package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{",
"LICENSE for more info. {% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\"",
"cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email }}' __version__",
"under the {{ cookiecutter.open_source_license }}. See LICENSE for more info. {% endif %}",
"%} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__",
"for {{ cookiecutter.project_name }}.\"\"\" __author__ = \"\"\"{{ cookiecutter.full_name }}\"\"\" __email__ = '{{ cookiecutter.email",
"= cookiecutter.project_slug.capitalize() -%} {% set is_open_source = cookiecutter.open_source_license != 'Not open source' -%}",
"{{ cookiecutter.open_source_license }}. See LICENSE for more info. {% endif %} \"\"\"Top-level package",
"}} project # # Copyright (c) {% now 'local', '%Y' %} {{ cookiecutter.full_name",
"for more info. {% endif %} \"\"\"Top-level package for {{ cookiecutter.project_name }}.\"\"\" __author__",
"# # This file is part of the {{ cookiecutter.project_name }} project #",
"cookiecutter.project_name }} project # # Copyright (c) {% now 'local', '%Y' %} {{",
"This file is part of the {{ cookiecutter.project_name }} project # # Copyright",
"is_open_source = cookiecutter.open_source_license != 'Not open source' -%} # -*- coding: utf-8 -*-",
"{% set is_open_source = cookiecutter.open_source_license != 'Not open source' -%} # -*- coding:",
"if is_open_source -%} # Distributed under the {{ cookiecutter.open_source_license }}. See LICENSE for"
] |
[
"diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в произведении, если такая ошибка одна,",
"to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в произведении,",
"idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2 # потенциально правильное",
"произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul",
"dec_num2 != 0: # крайний случай if len(num1) != 1: num1 = 0",
"define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2 # потенциально правильное число под",
"2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul /",
"= input() num2 = input() mul = input() dec_num1 = to_dec_num(num1) dec_num2 =",
"# потенциально правильное число под номером 2 if int(div1) == div1: return to_hex_str(int(div1)),",
"0 and dec_num1 * dec_num2 != 0: # крайний случай if len(num1) !=",
"mul2): # Возвращает индекс ошибки записи в произведении, если такая ошибка одна, иначе",
"Возвращает индекс ошибки записи в произведении, если такая ошибка одна, иначе -1 len_mul1",
"dec_mul == 0 and dec_num1 * dec_num2 != 0: # крайний случай if",
"!= 1: num1 = 0 else: num2 = 0 print(num1) print(num2) print(mul) exit()",
"случай if len(num1) != 1: num1 = 0 else: num2 = 0 print(num1)",
"# правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else:",
"номером 2 if int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2:",
"num1 = 0 else: num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right =",
"range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong = i if cnt_wrongs",
"= 0 idx_wrong = -1 if len_mul1 != len_mul2: return -1 for i",
"to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert 0 num1",
"== 0 and dec_num1 * dec_num2 != 0: # крайний случай if len(num1)",
"to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0 and dec_num1",
"if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul правильные произведения #",
"dec_mul = to_dec_num(mul) if dec_mul == 0 and dec_num1 * dec_num2 != 0:",
"== div2: return num1, to_hex_str(int(div2)) else: assert 0 num1 = input() num2 =",
"i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong = i",
"div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert",
"if len_mul1 != len_mul2: return -1 for i in range(len_mul1): if mul1[i] !=",
"else: assert 0 num1 = input() num2 = input() mul = input() dec_num1",
"exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right)",
"print(hex_mul_right) else: # mul и dec_mul правильные произведения # только одно число изменится",
"1 idx_wrong = i if cnt_wrongs >= 2: return -1 return idx_wrong def",
"to_dec_num(hex_str): return int(hex_str, 16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает",
"diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul правильные",
"в произведении, если такая ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2 =",
"to_dec_num(mul) if dec_mul == 0 and dec_num1 * dec_num2 != 0: # крайний",
"= dec_mul / dec_num1 # потенциально правильное число под номером 2 if int(div1)",
"hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul правильные произведения",
"1: num1 = 0 else: num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right",
"иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong =",
"len(num1) != 1: num1 = 0 else: num2 = 0 print(num1) print(num2) print(mul)",
"return int(hex_str, 16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс",
"len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong = -1 if len_mul1 != len_mul2:",
"правильные произведения # только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1, dec_num2, dec_mul)",
"= 0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное",
"0 num1 = input() num2 = input() mul = input() dec_num1 = to_dec_num(num1)",
"return -1 for i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1",
"hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if",
"div1 = dec_mul / dec_num2 # потенциально правильное число под номером 1 div2",
"dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0",
"число под номером 2 if int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2)",
"mul и dec_mul правильные произведения # только одно число изменится new_num1, new_num2 =",
"такая ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs =",
"0 idx_wrong = -1 if len_mul1 != len_mul2: return -1 for i in",
"def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в",
"idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и",
"произведения # только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1, dec_num2, dec_mul) print(new_num1)",
"if len(num1) != 1: num1 = 0 else: num2 = 0 print(num1) print(num2)",
"return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2",
"dec_mul правильные произведения # только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1, dec_num2,",
"len(mul2) cnt_wrongs = 0 idx_wrong = -1 if len_mul1 != len_mul2: return -1",
"# потенциально правильное число под номером 1 div2 = dec_mul / dec_num1 #",
"def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в произведении, если такая ошибка",
"# Возвращает индекс ошибки записи в произведении, если такая ошибка одна, иначе -1",
"mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong = i if cnt_wrongs >= 2:",
"= to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0 and",
"num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) #",
"правильное число под номером 2 if int(div1) == div1: return to_hex_str(int(div1)), num2 elif",
"print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong =",
"idx_wrong = i if cnt_wrongs >= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1,",
"if dec_mul == 0 and dec_num1 * dec_num2 != 0: # крайний случай",
"dec_num2 # потенциально правильное число под номером 1 div2 = dec_mul / dec_num1",
"num2 elif int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert 0 num1 =",
"+= 1 idx_wrong = i if cnt_wrongs >= 2: return -1 return idx_wrong",
"len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong = -1 if",
"16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи",
"= dec_mul / dec_num2 # потенциально правильное число под номером 1 div2 =",
"int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert 0 num1 = input() num2",
"return num1, to_hex_str(int(div2)) else: assert 0 num1 = input() num2 = input() mul",
"assert 0 num1 = input() num2 = input() mul = input() dec_num1 =",
"hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в произведении, если такая",
"== div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1, to_hex_str(int(div2)) else:",
"индекс ошибки записи в произведении, если такая ошибка одна, иначе -1 len_mul1 =",
"len_mul1 != len_mul2: return -1 for i in range(len_mul1): if mul1[i] != mul2[i]:",
"/ dec_num1 # потенциально правильное число под номером 2 if int(div1) == div1:",
"* dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2)",
"0 else: num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 *",
"под номером 1 div2 = dec_mul / dec_num1 # потенциально правильное число под",
"= 0 else: num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1",
"# только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1, dec_num2, dec_mul) print(new_num1) print(new_num2)",
"число под номером 1 div2 = dec_mul / dec_num1 # потенциально правильное число",
"только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1, dec_num2, dec_mul) print(new_num1) print(new_num2) print(mul)",
"потенциально правильное число под номером 1 div2 = dec_mul / dec_num1 # потенциально",
"= i if cnt_wrongs >= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2,",
"div2: return num1, to_hex_str(int(div2)) else: assert 0 num1 = input() num2 = input()",
"input() num2 = input() mul = input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2)",
"i if cnt_wrongs >= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul):",
"div2 = dec_mul / dec_num1 # потенциально правильное число под номером 2 if",
"return to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert 0",
"0: # крайний случай if len(num1) != 1: num1 = 0 else: num2",
"to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0 and dec_num1 * dec_num2 !=",
"mul = input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if",
"for i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong =",
"cnt_wrongs += 1 idx_wrong = i if cnt_wrongs >= 2: return -1 return",
"cnt_wrongs = 0 idx_wrong = -1 if len_mul1 != len_mul2: return -1 for",
"-1 if len_mul1 != len_mul2: return -1 for i in range(len_mul1): if mul1[i]",
"dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right)",
"dec_mul): div1 = dec_mul / dec_num2 # потенциально правильное число под номером 1",
"крайний случай if len(num1) != 1: num1 = 0 else: num2 = 0",
"len_mul2: return -1 for i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs +=",
"cnt_wrongs >= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 =",
"= diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul",
"dec_mul / dec_num1 # потенциально правильное число под номером 2 if int(div1) ==",
"dec_num1 # потенциально правильное число под номером 2 if int(div1) == div1: return",
"and dec_num1 * dec_num2 != 0: # крайний случай if len(num1) != 1:",
"= to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0 and dec_num1 * dec_num2",
"if cnt_wrongs >= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1",
"<filename>MGTU-final-stage/3.py def to_dec_num(hex_str): return int(hex_str, 16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2):",
"return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2 # потенциально",
"def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2 # потенциально правильное число",
"= input() mul = input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul =",
"ошибки записи в произведении, если такая ошибка одна, иначе -1 len_mul1 = len(mul1)",
"input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul ==",
"= len(mul2) cnt_wrongs = 0 idx_wrong = -1 if len_mul1 != len_mul2: return",
"~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul правильные произведения # только",
"-1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul / dec_num2 #",
"elif int(div2) == div2: return num1, to_hex_str(int(div2)) else: assert 0 num1 = input()",
"правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1) print(num2) print(hex_mul_right) else: #",
"print(num2) print(hex_mul_right) else: # mul и dec_mul правильные произведения # только одно число",
">= 2: return -1 return idx_wrong def define_rights_numbers(dec_num1, dec_num2, dec_mul): div1 = dec_mul",
"else: num2 = 0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2)",
"in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong = i if",
"dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul == 0 and dec_num1 *",
"dec_num1 * dec_num2 != 0: # крайний случай if len(num1) != 1: num1",
"= to_dec_num(mul) if dec_mul == 0 and dec_num1 * dec_num2 != 0: #",
"return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки записи в произведении, если",
"def to_dec_num(hex_str): return int(hex_str, 16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): #",
"под номером 2 if int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2) ==",
"to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong: print(num1)",
"else: # mul и dec_mul правильные произведения # только одно число изменится new_num1,",
"dec_num2, dec_mul): div1 = dec_mul / dec_num2 # потенциально правильное число под номером",
"num2 = input() mul = input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul",
"print(num1) print(num2) print(hex_mul_right) else: # mul и dec_mul правильные произведения # только одно",
"-1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong = -1",
"= to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong = diff_mul(mul, hex_mul_right) if ~idx_wrong:",
"правильное число под номером 1 div2 = dec_mul / dec_num1 # потенциально правильное",
"num1, to_hex_str(int(div2)) else: assert 0 num1 = input() num2 = input() mul =",
"idx_wrong = -1 if len_mul1 != len_mul2: return -1 for i in range(len_mul1):",
"# mul и dec_mul правильные произведения # только одно число изменится new_num1, new_num2",
"произведении, если такая ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2)",
"потенциально правильное число под номером 2 if int(div1) == div1: return to_hex_str(int(div1)), num2",
"-1 for i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong",
"if int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1,",
"int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2: return num1, to_hex_str(int(div2))",
"ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0",
"mul2[i]: cnt_wrongs += 1 idx_wrong = i if cnt_wrongs >= 2: return -1",
"# крайний случай if len(num1) != 1: num1 = 0 else: num2 =",
"!= 0: # крайний случай if len(num1) != 1: num1 = 0 else:",
"/ dec_num2 # потенциально правильное число под номером 1 div2 = dec_mul /",
"одна, иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong",
"input() mul = input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul)",
"int(hex_str, 16) def to_hex_str(dec_num): return hex(dec_num).upper()[2:] def diff_mul(mul1, mul2): # Возвращает индекс ошибки",
"= input() dec_num1 = to_dec_num(num1) dec_num2 = to_dec_num(num2) dec_mul = to_dec_num(mul) if dec_mul",
"* dec_num2 != 0: # крайний случай if len(num1) != 1: num1 =",
"print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong",
"0 print(num1) print(num2) print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение",
"если такая ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2 = len(mul2) cnt_wrongs",
"num1 = input() num2 = input() mul = input() dec_num1 = to_dec_num(num1) dec_num2",
"записи в произведении, если такая ошибка одна, иначе -1 len_mul1 = len(mul1) len_mul2",
"len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong = -1 if len_mul1 !=",
"dec_mul / dec_num2 # потенциально правильное число под номером 1 div2 = dec_mul",
"if mul1[i] != mul2[i]: cnt_wrongs += 1 idx_wrong = i if cnt_wrongs >=",
"print(mul) exit() hex_mul_right = to_hex_str(dec_num1 * dec_num2) # правильное произведение idx_wrong = diff_mul(mul,",
"2 if int(div1) == div1: return to_hex_str(int(div1)), num2 elif int(div2) == div2: return",
"номером 1 div2 = dec_mul / dec_num1 # потенциально правильное число под номером",
"= -1 if len_mul1 != len_mul2: return -1 for i in range(len_mul1): if",
"и dec_mul правильные произведения # только одно число изменится new_num1, new_num2 = define_rights_numbers(dec_num1,",
"!= len_mul2: return -1 for i in range(len_mul1): if mul1[i] != mul2[i]: cnt_wrongs",
"= len(mul1) len_mul2 = len(mul2) cnt_wrongs = 0 idx_wrong = -1 if len_mul1",
"!= mul2[i]: cnt_wrongs += 1 idx_wrong = i if cnt_wrongs >= 2: return",
"1 div2 = dec_mul / dec_num1 # потенциально правильное число под номером 2",
"to_hex_str(int(div2)) else: assert 0 num1 = input() num2 = input() mul = input()"
] |
[
"2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf, ) = (1, 2,",
"sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf,",
"3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf, ) = (1, 2, 3)",
"= 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf, ) =",
"<reponame>alexchamberlain/black sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf,",
"1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf, ) = (1,",
"sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf,",
"sdsfsdfjskdflsfsdf = 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf, )",
"sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 # output ( sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf,"
] |
[
"<filename>bonked/__init__.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__",
"# -*- coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__",
"coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\"",
"\"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\"",
"utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__",
"bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" __version__ = \"0.1.2dev\"",
"package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" __version__",
"for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__ = \"MIT\" __version__ =",
"python3 # -*- coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\"",
"-*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __license__ =",
"-*- coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ = \"<NAME>\" __email__ =",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\"Top-level package for bonked.\"\"\" __author__ ="
] |
[
"range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3))",
"scores = [] for i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i +",
"DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import numpy as np",
"# Train model rf = RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre",
"sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names'] rf =",
"X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape = -1, -1 X = [list(i)",
"cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores",
"sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import",
"iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = [] for i in range(X.shape[1]): score",
"Y_test.shape = -1, -1 X = [list(i) for i in X] X_test =",
"RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:',",
"X_test] print('X:', X) print('Y:', Y) # Train model rf = RandomForestRegressor() rf.fit(X, Y)",
"in X_test] print('X:', X) print('Y:', Y) # Train model rf = RandomForestRegressor() rf.fit(X,",
"X) print('Y:', Y) # Train model rf = RandomForestRegressor() rf.fit(X, Y) # Predict",
"score = cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score),",
"print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:,",
"1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape = -1, -1 X =",
"= load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y",
"1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if __name__",
"np iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY)",
"rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X,",
"[] for i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1], Y,",
"import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import numpy as",
"Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape",
"import RandomForestRegressor from sklearn.datasets import load_iris import numpy as np iris = load_iris()",
"import cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor()",
"import numpy as np iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY =",
"def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target,",
"sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import numpy as np iris =",
"Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names",
"names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = [] for i",
"shuffle from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris",
"from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import numpy as np iris",
"iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:,",
"[list(i) for i in X_test] print('X:', X) print('Y:', Y) # Train model rf",
"X = [list(i) for i in X] X_test = [list(i) for i in",
"-1, -1 X = [list(i) for i in X] X_test = [list(i) for",
"len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100],",
"-1, -1 X_test.shape, Y_test.shape = -1, -1 X = [list(i) for i in",
"# Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2():",
"rf = RandomForestRegressor() scores = [] for i in range(X.shape[1]): score = cross_val_score(rf,",
"X_test = [list(i) for i in X_test] print('X:', X) print('Y:', Y) # Train",
"test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100]",
"rf.fit(X, Y) # Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre)",
"numpy as np iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data,",
"= cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3),",
"= rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit",
"X_test.shape, Y_test.shape = -1, -1 X = [list(i) for i in X] X_test",
"Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if __name__ ==",
"= RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test)",
"i in X] X_test = [list(i) for i in X_test] print('X:', X) print('Y:',",
"X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape,",
"XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape = -1,",
"print('Y:', Y) # Train model rf = RandomForestRegressor() rf.fit(X, Y) # Predict new",
"= [] for i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1],",
"for i in X_test] print('X:', X) print('Y:', Y) # Train model rf =",
"+ 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if",
"np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test =",
"sklearn.datasets import load_iris import numpy as np iris = load_iris() print(type(iris), len(iris.data)) def",
"1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1",
"RandomForestRegressor from sklearn.datasets import load_iris import numpy as np iris = load_iris() print(type(iris),",
"Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from",
":1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape = -1, -1",
"X, Y, names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = []",
"= [list(i) for i in X] X_test = [list(i) for i in X_test]",
"cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i]))",
"X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:,",
"from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import",
"X] X_test = [list(i) for i in X_test] print('X:', X) print('Y:', Y) #",
"ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores =",
"from sklearn.datasets import load_iris import numpy as np iris = load_iris() print(type(iris), len(iris.data))",
"scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if __name__ == '__main__':",
"load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y =",
"= XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape =",
"XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape = -1,",
"[list(i) for i in X] X_test = [list(i) for i in X_test] print('X:',",
"sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import load_iris import numpy",
"iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X,",
"iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = [] for i in range(X.shape[1]):",
"i in X_test] print('X:', X) print('Y:', Y) # Train model rf = RandomForestRegressor()",
"iris['feature_names'] rf = RandomForestRegressor() scores = [] for i in range(X.shape[1]): score =",
"XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test,",
"model rf = RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre = rf.predict(X_test)",
"XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape",
"-1 X_test.shape, Y_test.shape = -1, -1 X = [list(i) for i in X]",
"load_iris import numpy as np iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY",
"= -1, -1 X = [list(i) for i in X] X_test = [list(i)",
"-1 X = [list(i) for i in X] X_test = [list(i) for i",
"for i in X] X_test = [list(i) for i in X_test] print('X:', X)",
"Y, names = iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = [] for",
"i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X),",
"= np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test",
"print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y,",
"print('X:', X) print('Y:', Y) # Train model rf = RandomForestRegressor() rf.fit(X, Y) #",
"= RandomForestRegressor() scores = [] for i in range(X.shape[1]): score = cross_val_score(rf, X[:,",
"XY[:, 1:][100:] X.shape, Y.shape = -1, -1 X_test.shape, Y_test.shape = -1, -1 X",
"test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names']",
"Train model rf = RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre =",
"in X] X_test = [list(i) for i in X_test] print('X:', X) print('Y:', Y)",
"as np iris = load_iris() print(type(iris), len(iris.data)) def test1(): XY = np.array(zip(iris.data, iris.target))",
"Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score,",
"from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names = iris.data, iris.target, iris['feature_names'] rf",
"Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:]",
"X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores,",
"def test1(): XY = np.array(zip(iris.data, iris.target)) np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:,",
"in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3,",
"random import shuffle from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets",
"for i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i + 1], Y, scoring='r2',",
"= [list(i) for i in X_test] print('X:', X) print('Y:', Y) # Train model",
"import shuffle from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import",
"= iris.data, iris.target, iris['feature_names'] rf = RandomForestRegressor() scores = [] for i in",
"import load_iris import numpy as np iris = load_iris() print(type(iris), len(iris.data)) def test1():",
"np.random.shuffle(XY) X, Y = XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:],",
"i:i + 1], Y, scoring='r2', cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True))",
":1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape, Y.shape =",
"print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names =",
"from random import shuffle from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from",
"RandomForestRegressor() scores = [] for i in range(X.shape[1]): score = cross_val_score(rf, X[:, i:i",
"= XY[:, :1][:100], XY[:, 1:][:100] X_test, Y_test = XY[:, :1][100:], XY[:, 1:][100:] X.shape,",
"Y_pre) def test2(): from sklearn.cross_validation import cross_val_score, ShuffleSplit X, Y, names = iris.data,",
"new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def test2(): from sklearn.cross_validation",
"rf = RandomForestRegressor() rf.fit(X, Y) # Predict new sample Y_pre = rf.predict(X_test) print('Y_test:',",
"= -1, -1 X_test.shape, Y_test.shape = -1, -1 X = [list(i) for i",
"Y) # Train model rf = RandomForestRegressor() rf.fit(X, Y) # Predict new sample",
"Y) # Predict new sample Y_pre = rf.predict(X_test) print('Y_test:', Y_test) print('Y_pre:', Y_pre) def",
"3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if __name__ == '__main__': test1() test2()",
"Y.shape = -1, -1 X_test.shape, Y_test.shape = -1, -1 X = [list(i) for",
"cv=ShuffleSplit(len(X), 3, .3)) scores.append((round(np.mean(score), 3), names[i])) print(sorted(scores, reverse=True)) if __name__ == '__main__': test1()"
] |
[] |
[
"if element == \"1\": result *= b result %= n return result result",
"e, n): seq = bin(e)[3:] result = b for element in seq: result",
"result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789,",
"123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) ) print(result)",
"seq = bin(e)[3:] result = b for element in seq: result = pow(result,",
"= bin(e)[3:] result = b for element in seq: result = pow(result, 2)",
"2) if element == \"1\": result *= b result %= n return result",
"\"1\": result *= b result %= n return result result = fast_expo( 123456789123456789,",
"pow(result, 2) if element == \"1\": result *= b result %= n return",
"def fast_expo(b, e, n): seq = bin(e)[3:] result = b for element in",
"in seq: result = pow(result, 2) if element == \"1\": result *= b",
"*= b result %= n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789",
"b for element in seq: result = pow(result, 2) if element == \"1\":",
"element in seq: result = pow(result, 2) if element == \"1\": result *=",
"result %= n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print(",
"n): seq = bin(e)[3:] result = b for element in seq: result =",
"fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 )",
"result = pow(result, 2) if element == \"1\": result *= b result %=",
"fast_expo(b, e, n): seq = bin(e)[3:] result = b for element in seq:",
"bin(e)[3:] result = b for element in seq: result = pow(result, 2) if",
"result = b for element in seq: result = pow(result, 2) if element",
"%= n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result",
"result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789, 123456789123456789123456789123456789,",
"123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) )",
"b result %= n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 )",
"seq: result = pow(result, 2) if element == \"1\": result *= b result",
"= pow(result, 2) if element == \"1\": result *= b result %= n",
"= fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789",
"return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result == pow(",
"for element in seq: result = pow(result, 2) if element == \"1\": result",
"element == \"1\": result *= b result %= n return result result =",
"result *= b result %= n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789,",
"== \"1\": result *= b result %= n return result result = fast_expo(",
"n return result result = fast_expo( 123456789123456789, 123456789123456789123456789123456789, 123456789123456789123456789123456789123456789 ) print( result ==",
"= b for element in seq: result = pow(result, 2) if element =="
] |
[
"_get(row, 7) client = _get(row, 8) material_price = _get(row, 9) material_client = _get(row,",
"_get(row, 11) milling_client = _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row,",
"load_workbook(path, read_only=True) ws = wb[worksheet] return ws def parse(): tmp_drawing = 'SW-' CNT",
"if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj",
"int(main_division) except: pass try: sub_division = int(sub_division) except: pass if not main_division or",
"import Part, Material, OutSource def _get(data, index): try: if data[index].value != 0: return",
"= 'SW-' CNT = 0 # Just for temporary usage worksheets = ['상우정밀',",
"or milling_price or \\ heat_treat_price or wire_price: is_os = True if drawing: drawing,",
"= _get(row, 15) wire_client = _get(row, 16) try: main_division = int(main_division) except: pass",
"in worksheets: data = load('utils/data.xlsx', ws) first_row = False for row in data.rows:",
"worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx', ws) first_row",
"data = load('utils/data.xlsx', ws) first_row = False for row in data.rows: if not",
"CNT = 0 # Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for",
"else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get(",
"IndexError: return None def load(path, worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet]",
"openpyxl import load_workbook from apps.client.models import Client from apps.division.models import Division from apps.drawing.models",
"None if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int(",
"if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if",
"= wb[worksheet] return ws def parse(): tmp_drawing = 'SW-' CNT = 0 #",
"if not first_row: first_row = True continue x = str(_get(row, 0)) y =",
"name=material_client) if material_price else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None",
"z = str(_get(row, 2)) material = _get(row, 3) price = _get(row, 4) main_division",
"return None except IndexError: return None def load(path, worksheet): wb = load_workbook(path, read_only=True)",
"apps.client.models import Client from apps.division.models import Division from apps.drawing.models import Drawing from apps.part.models",
"if not main_division or main_division == ' ': continue if x: print('{},{},{} -",
"8) material_price = _get(row, 9) material_client = _get(row, 10) milling_price = _get(row, 11)",
"y = str(_get(row, 1)) z = str(_get(row, 2)) material = _get(row, 3) price",
"if wire_price else None outsource = None if is_os: outsource = OutSource.objects.create( material_price=int(",
"6) drawing = _get(row, 7) client = _get(row, 8) material_price = _get(row, 9)",
"None outsource = None if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price",
"x = str(_get(row, 0)) y = str(_get(row, 1)) z = str(_get(row, 2)) material",
"data[index].value else: return None except IndexError: return None def load(path, worksheet): wb =",
"heat_treat_client = _get(row, 14) wire_price = _get(row, 15) wire_client = _get(row, 16) try:",
"worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet] return ws def parse(): tmp_drawing",
"16) try: main_division = int(main_division) except: pass try: sub_division = int(sub_division) except: pass",
"['상우정밀', '성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx', ws) first_row = False",
"heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj,",
"is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int( milling_price) if",
"milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj =",
"in data.rows: if not first_row: first_row = True continue x = str(_get(row, 0))",
"Part, Material, OutSource def _get(data, index): try: if data[index].value != 0: return data[index].value",
"= _get(row, 8) material_price = _get(row, 9) material_client = _get(row, 10) milling_price =",
"pass if not main_division or main_division == ' ': continue if x: print('{},{},{}",
"milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price)",
"_get(row, 8) material_price = _get(row, 9) material_client = _get(row, 10) milling_price = _get(row,",
"Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os =",
"= None if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price else None,",
"material_client = _get(row, 10) milling_price = _get(row, 11) milling_client = _get(row, 12) heat_treat_price",
"# Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets:",
"import date from openpyxl import load_workbook from apps.client.models import Client from apps.division.models import",
"apps.drawing.models import Drawing from apps.part.models import Part, Material, OutSource def _get(data, index): try:",
"else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get(",
"material = _get(row, 3) price = _get(row, 4) main_division = _get(row, 5) sub_division",
"return None def load(path, worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet] return",
"continue x = str(_get(row, 0)) y = str(_get(row, 1)) z = str(_get(row, 2))",
"heat_treat_price else None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj",
"return data[index].value else: return None except IndexError: return None def load(path, worksheet): wb",
"name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None",
"is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True,",
"= str(_get(row, 1)) z = str(_get(row, 2)) material = _get(row, 3) price =",
"def _get(data, index): try: if data[index].value != 0: return data[index].value else: return None",
"= Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price",
"': continue if x: print('{},{},{} - {}W {}'.format(x, y, z, price, drawing)) client_obj,",
"from apps.part.models import Part, Material, OutSource def _get(data, index): try: if data[index].value !=",
"= _get(row, 3) price = _get(row, 4) main_division = _get(row, 5) sub_division =",
"= int(main_division) except: pass try: sub_division = int(sub_division) except: pass if not main_division",
"material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing,",
"Material, OutSource def _get(data, index): try: if data[index].value != 0: return data[index].value else:",
"0: return data[index].value else: return None except IndexError: return None def load(path, worksheet):",
"material_price else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj =",
"else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os",
"= str(_get(row, 2)) material = _get(row, 3) price = _get(row, 4) main_division =",
"= ['상우정밀', '성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx', ws) first_row =",
"Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y, z=z, price=int(price), material=material_obj, outsource=outsource )",
"created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get( name=material_client) if material_price else",
"= _get(row, 6) drawing = _get(row, 7) client = _get(row, 8) material_price =",
"client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj",
"5) sub_division = _get(row, 6) drawing = _get(row, 7) client = _get(row, 8)",
"from apps.client.models import Client from apps.division.models import Division from apps.drawing.models import Drawing from",
"= _get(row, 14) wire_price = _get(row, 15) wire_client = _get(row, 16) try: main_division",
"Drawing from apps.part.models import Part, Material, OutSource def _get(data, index): try: if data[index].value",
"= _get(row, 5) sub_division = _get(row, 6) drawing = _get(row, 7) client =",
"row in data.rows: if not first_row: first_row = True continue x = str(_get(row,",
"None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if wire_price else None,",
"Client from apps.division.models import Division from apps.drawing.models import Drawing from apps.part.models import Part,",
"z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create(",
"_get(row, 9) material_client = _get(row, 10) milling_price = _get(row, 11) milling_client = _get(row,",
"= Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT",
"'성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx', ws) first_row = False for",
"else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None outsource = None",
"import Client from apps.division.models import Division from apps.drawing.models import Drawing from apps.part.models import",
"sub_division=sub_division, client=client_obj ) is_os = False if material_price or milling_price or \\ heat_treat_price",
"= _get(row, 4) main_division = _get(row, 5) sub_division = _get(row, 6) drawing =",
"print('{},{},{} - {}W {}'.format(x, y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client",
"_ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if material_price or",
"13) heat_treat_client = _get(row, 14) wire_price = _get(row, 15) wire_client = _get(row, 16)",
"client=client_obj ) is_os = False if material_price or milling_price or \\ heat_treat_price or",
"name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None",
"Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing +",
"= Client.objects.get( name=wire_client) if wire_price else None outsource = None if is_os: outsource",
"else None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj )",
"milling_client = _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14) wire_price",
"int(sub_division) except: pass if not main_division or main_division == ' ': continue if",
"or \\ heat_treat_price or wire_price: is_os = True if drawing: drawing, _ =",
"return ws def parse(): tmp_drawing = 'SW-' CNT = 0 # Just for",
"True continue x = str(_get(row, 0)) y = str(_get(row, 1)) z = str(_get(row,",
"try: main_division = int(main_division) except: pass try: sub_division = int(sub_division) except: pass if",
"= load_workbook(path, read_only=True) ws = wb[worksheet] return ws def parse(): tmp_drawing = 'SW-'",
"wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None outsource = None if is_os:",
"!= 0: return data[index].value else: return None except IndexError: return None def load(path,",
"_ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y, z=z, price=int(price), material=material_obj,",
"7) client = _get(row, 8) material_price = _get(row, 9) material_client = _get(row, 10)",
"wire_price = _get(row, 15) wire_client = _get(row, 16) try: main_division = int(main_division) except:",
"tmp_drawing = 'SW-' CNT = 0 # Just for temporary usage worksheets =",
"None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client)",
"_get(row, 5) sub_division = _get(row, 6) drawing = _get(row, 7) client = _get(row,",
"if heat_treat_price else None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj,",
"main_division == ' ': continue if x: print('{},{},{} - {}W {}'.format(x, y, z,",
"milling_price or \\ heat_treat_price or wire_price: is_os = True if drawing: drawing, _",
"True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os )",
"Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets: data",
"except IndexError: return None def load(path, worksheet): wb = load_workbook(path, read_only=True) ws =",
"first_row: first_row = True continue x = str(_get(row, 0)) y = str(_get(row, 1))",
"_get(row, 6) drawing = _get(row, 7) client = _get(row, 8) material_price = _get(row,",
") CNT += 1 material_client_obj = Client.objects.get( name=material_client) if material_price else None milling_client_obj",
"outsource = None if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price else",
"temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx',",
"else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if wire_price else",
"div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if material_price",
"drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing",
"None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj,",
"else None outsource = None if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if",
"0)) y = str(_get(row, 1)) z = str(_get(row, 2)) material = _get(row, 3)",
"str(_get(row, 2)) material = _get(row, 3) price = _get(row, 4) main_division = _get(row,",
"first_row = True continue x = str(_get(row, 0)) y = str(_get(row, 1)) z",
"is_os = True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()),",
"or main_division == ' ': continue if x: print('{},{},{} - {}W {}'.format(x, y,",
"date from openpyxl import load_workbook from apps.client.models import Client from apps.division.models import Division",
"None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client)",
"= _get(row, 13) heat_treat_client = _get(row, 14) wire_price = _get(row, 15) wire_client =",
"= _get(row, 11) milling_client = _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client =",
"Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if material_price or milling_price or",
"= Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price",
"None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None,",
"ws in worksheets: data = load('utils/data.xlsx', ws) first_row = False for row in",
"if material_price else None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if",
"Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else",
"_get(row, 14) wire_price = _get(row, 15) wire_client = _get(row, 16) try: main_division =",
"drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing =",
"= True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os",
"except: pass if not main_division or main_division == ' ': continue if x:",
"milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if",
"0 # Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in",
"Division from apps.drawing.models import Drawing from apps.part.models import Part, Material, OutSource def _get(data,",
"drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os )",
"def parse(): tmp_drawing = 'SW-' CNT = 0 # Just for temporary usage",
"milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj,",
"is_os = False if material_price or milling_price or \\ heat_treat_price or wire_price: is_os",
"client = _get(row, 8) material_price = _get(row, 9) material_client = _get(row, 10) milling_price",
"pass try: sub_division = int(sub_division) except: pass if not main_division or main_division ==",
"try: sub_division = int(sub_division) except: pass if not main_division or main_division == '",
"data[index].value != 0: return data[index].value else: return None except IndexError: return None def",
"def load(path, worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet] return ws def",
"= Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if material_price or milling_price",
"load(path, worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet] return ws def parse():",
"client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' %",
"index): try: if data[index].value != 0: return data[index].value else: return None except IndexError:",
"= OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int( milling_price) if milling_price else",
"14) wire_price = _get(row, 15) wire_client = _get(row, 16) try: main_division = int(main_division)",
"for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets: data =",
"main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if material_price or milling_price or \\",
"if x: print('{},{},{} - {}W {}'.format(x, y, z, price, drawing)) client_obj, _ =",
"from openpyxl import load_workbook from apps.client.models import Client from apps.division.models import Division from",
"for row in data.rows: if not first_row: first_row = True continue x =",
"wire_price else None outsource = None if is_os: outsource = OutSource.objects.create( material_price=int( material_price)",
"worksheets: data = load('utils/data.xlsx', ws) first_row = False for row in data.rows: if",
"15) wire_client = _get(row, 16) try: main_division = int(main_division) except: pass try: sub_division",
"4) main_division = _get(row, 5) sub_division = _get(row, 6) drawing = _get(row, 7)",
"= _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14) wire_price =",
"else None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else",
"if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create(",
"material_price) if material_price else None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price)",
"material_price else None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price",
"'SW-' CNT = 0 # Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)']",
"datetime import date from openpyxl import load_workbook from apps.client.models import Client from apps.division.models",
"name=wire_client) if wire_price else None outsource = None if is_os: outsource = OutSource.objects.create(",
"material_price=int( material_price) if material_price else None, milling_price=int( milling_price) if milling_price else None, heat_treat_price=int(",
"not main_division or main_division == ' ': continue if x: print('{},{},{} - {}W",
"price = _get(row, 4) main_division = _get(row, 5) sub_division = _get(row, 6) drawing",
"or wire_price: is_os = True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj,",
"3) price = _get(row, 4) main_division = _get(row, 5) sub_division = _get(row, 6)",
"material_price or milling_price or \\ heat_treat_price or wire_price: is_os = True if drawing:",
"if data[index].value != 0: return data[index].value else: return None except IndexError: return None",
"= load('utils/data.xlsx', ws) first_row = False for row in data.rows: if not first_row:",
"wire_client = _get(row, 16) try: main_division = int(main_division) except: pass try: sub_division =",
"10) milling_price = _get(row, 11) milling_client = _get(row, 12) heat_treat_price = _get(row, 13)",
"from apps.division.models import Division from apps.drawing.models import Drawing from apps.part.models import Part, Material,",
") else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()),",
"if is_os: outsource = OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int( milling_price)",
"read_only=True) ws = wb[worksheet] return ws def parse(): tmp_drawing = 'SW-' CNT =",
"main_division = int(main_division) except: pass try: sub_division = int(sub_division) except: pass if not",
"try: if data[index].value != 0: return data[index].value else: return None except IndexError: return",
"heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj,",
"milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int( wire_price) if wire_price",
"2)) material = _get(row, 3) price = _get(row, 4) main_division = _get(row, 5)",
"OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int( milling_price) if milling_price else None,",
"_get(row, 15) wire_client = _get(row, 16) try: main_division = int(main_division) except: pass try:",
"sub_division = int(sub_division) except: pass if not main_division or main_division == ' ':",
"drawing = _get(row, 7) client = _get(row, 8) material_price = _get(row, 9) material_client",
"y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _ =",
"11) milling_client = _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14)",
"= Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os",
"_get(row, 16) try: main_division = int(main_division) except: pass try: sub_division = int(sub_division) except:",
"created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj,",
"first_row = False for row in data.rows: if not first_row: first_row = True",
"1 material_client_obj = Client.objects.get( name=material_client) if material_price else None milling_client_obj = Client.objects.get( name=milling_client)",
"= True continue x = str(_get(row, 0)) y = str(_get(row, 1)) z =",
"_ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create(",
"name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1",
"_get(row, 13) heat_treat_client = _get(row, 14) wire_price = _get(row, 15) wire_client = _get(row,",
") material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y, z=z,",
"= False if material_price or milling_price or \\ heat_treat_price or wire_price: is_os =",
"+= 1 material_client_obj = Client.objects.get( name=material_client) if material_price else None milling_client_obj = Client.objects.get(",
"' ': continue if x: print('{},{},{} - {}W {}'.format(x, y, z, price, drawing))",
"ws) first_row = False for row in data.rows: if not first_row: first_row =",
"data.rows: if not first_row: first_row = True continue x = str(_get(row, 0)) y",
"material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y, z=z, price=int(price),",
"\\ heat_treat_price or wire_price: is_os = True if drawing: drawing, _ = Drawing.objects.get_or_create(",
"_get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14) wire_price = _get(row,",
"heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14) wire_price = _get(row, 15) wire_client",
"Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else",
") is_os = False if material_price or milling_price or \\ heat_treat_price or wire_price:",
"wb[worksheet] return ws def parse(): tmp_drawing = 'SW-' CNT = 0 # Just",
"_get(row, 10) milling_price = _get(row, 11) milling_client = _get(row, 12) heat_treat_price = _get(row,",
"outsource = OutSource.objects.create( material_price=int( material_price) if material_price else None, milling_price=int( milling_price) if milling_price",
"_get(row, 4) main_division = _get(row, 5) sub_division = _get(row, 6) drawing = _get(row,",
"if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None outsource",
"wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material",
"CNT += 1 material_client_obj = Client.objects.get( name=material_client) if material_price else None milling_client_obj =",
"except: pass try: sub_division = int(sub_division) except: pass if not main_division or main_division",
"OutSource def _get(data, index): try: if data[index].value != 0: return data[index].value else: return",
"not first_row: first_row = True continue x = str(_get(row, 0)) y = str(_get(row,",
"is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get( name=material_client) if material_price",
"from apps.drawing.models import Drawing from apps.part.models import Part, Material, OutSource def _get(data, index):",
"wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ =",
"= int(sub_division) except: pass if not main_division or main_division == ' ': continue",
"= _get(row, 9) material_client = _get(row, 10) milling_price = _get(row, 11) milling_client =",
"material_price = _get(row, 9) material_client = _get(row, 10) milling_price = _get(row, 11) milling_client",
") div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False if",
"<filename>utils/data_parser.py from datetime import date from openpyxl import load_workbook from apps.client.models import Client",
"+ '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj",
"drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division,",
"wire_price: is_os = True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True,",
"milling_price=int( milling_price) if milling_price else None, heat_treat_price=int( heat_treat_price) if heat_treat_price else None, wire_price=int(",
"name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj ) is_os = False",
"None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None outsource = None if",
"heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x,",
"else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material )",
"= _get(row, 10) milling_price = _get(row, 11) milling_client = _get(row, 12) heat_treat_price =",
"parse(): tmp_drawing = 'SW-' CNT = 0 # Just for temporary usage worksheets",
"ws = wb[worksheet] return ws def parse(): tmp_drawing = 'SW-' CNT = 0",
"== ' ': continue if x: print('{},{},{} - {}W {}'.format(x, y, z, price,",
"if material_price else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else None heat_treat_client_obj",
"import load_workbook from apps.client.models import Client from apps.division.models import Division from apps.drawing.models import",
"for ws in worksheets: data = load('utils/data.xlsx', ws) first_row = False for row",
"milling_price = _get(row, 11) milling_client = _get(row, 12) heat_treat_price = _get(row, 13) heat_treat_client",
"usage worksheets = ['상우정밀', '성우금형(제작)'] for ws in worksheets: data = load('utils/data.xlsx', ws)",
"price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division,",
"% CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get(",
"{}W {}'.format(x, y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj,",
"= Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing",
"= 0 # Just for temporary usage worksheets = ['상우정밀', '성우금형(제작)'] for ws",
"heat_treat_client_obj = Client.objects.get( name=heat_treat_client) if heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if",
"if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else:",
"material_client_obj = Client.objects.get( name=material_client) if material_price else None milling_client_obj = Client.objects.get( name=milling_client) if",
"False if material_price or milling_price or \\ heat_treat_price or wire_price: is_os = True",
"_get(row, 3) price = _get(row, 4) main_division = _get(row, 5) sub_division = _get(row,",
"Drawing.objects.create( name=tmp_drawing + '%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT +=",
"load_workbook from apps.client.models import Client from apps.division.models import Division from apps.drawing.models import Drawing",
"None except IndexError: return None def load(path, worksheet): wb = load_workbook(path, read_only=True) ws",
"None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create(",
"Client.objects.get( name=wire_client) if wire_price else None outsource = None if is_os: outsource =",
"is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d' % CNT,",
"if material_price or milling_price or \\ heat_treat_price or wire_price: is_os = True if",
"from datetime import date from openpyxl import load_workbook from apps.client.models import Client from",
"1)) z = str(_get(row, 2)) material = _get(row, 3) price = _get(row, 4)",
"load('utils/data.xlsx', ws) first_row = False for row in data.rows: if not first_row: first_row",
"Client.objects.get( name=material_client) if material_price else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price else",
"heat_treat_price or wire_price: is_os = True if drawing: drawing, _ = Drawing.objects.get_or_create( name=drawing,",
"= False for row in data.rows: if not first_row: first_row = True continue",
"wb = load_workbook(path, read_only=True) ws = wb[worksheet] return ws def parse(): tmp_drawing =",
"= str(_get(row, 0)) y = str(_get(row, 1)) z = str(_get(row, 2)) material =",
"sub_division = _get(row, 6) drawing = _get(row, 7) client = _get(row, 8) material_price",
"client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get( name=material_client) if",
"= Client.objects.get( name=material_client) if material_price else None milling_client_obj = Client.objects.get( name=milling_client) if milling_price",
"main_division or main_division == ' ': continue if x: print('{},{},{} - {}W {}'.format(x,",
"wire_client=wire_client_obj ) material_obj, _ = Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y,",
"continue if x: print('{},{},{} - {}W {}'.format(x, y, z, price, drawing)) client_obj, _",
"= _get(row, 7) client = _get(row, 8) material_price = _get(row, 9) material_client =",
"_get(data, index): try: if data[index].value != 0: return data[index].value else: return None except",
"else: return None except IndexError: return None def load(path, worksheet): wb = load_workbook(path,",
"ws def parse(): tmp_drawing = 'SW-' CNT = 0 # Just for temporary",
"None def load(path, worksheet): wb = load_workbook(path, read_only=True) ws = wb[worksheet] return ws",
"import Drawing from apps.part.models import Part, Material, OutSource def _get(data, index): try: if",
"'%05d' % CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj =",
"_ = Client.objects.get_or_create( name=client ) div_obj, _ = Division.objects.get_or_create( main_division=main_division, sub_division=sub_division, client=client_obj )",
"- {}W {}'.format(x, y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client )",
"False for row in data.rows: if not first_row: first_row = True continue x",
"CNT, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get( name=material_client)",
"name=drawing, client=client_obj, is_closed=True, created_at=str(date.today()), is_outsource=is_os ) else: drawing = Drawing.objects.create( name=tmp_drawing + '%05d'",
"heat_treat_price else None wire_client_obj = Client.objects.get( name=wire_client) if wire_price else None outsource =",
"{}'.format(x, y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create( name=client ) div_obj, _",
"x: print('{},{},{} - {}W {}'.format(x, y, z, price, drawing)) client_obj, _ = Client.objects.get_or_create(",
"12) heat_treat_price = _get(row, 13) heat_treat_client = _get(row, 14) wire_price = _get(row, 15)",
"apps.part.models import Part, Material, OutSource def _get(data, index): try: if data[index].value != 0:",
"9) material_client = _get(row, 10) milling_price = _get(row, 11) milling_client = _get(row, 12)",
"str(_get(row, 1)) z = str(_get(row, 2)) material = _get(row, 3) price = _get(row,",
"is_outsource=is_os ) CNT += 1 material_client_obj = Client.objects.get( name=material_client) if material_price else None",
"main_division = _get(row, 5) sub_division = _get(row, 6) drawing = _get(row, 7) client",
"apps.division.models import Division from apps.drawing.models import Drawing from apps.part.models import Part, Material, OutSource",
"import Division from apps.drawing.models import Drawing from apps.part.models import Part, Material, OutSource def",
"wire_price=int( wire_price) if wire_price else None, material_client=material_client_obj, milling_client=milling_client_obj, heat_treat_client=heat_treat_client_obj, wire_client=wire_client_obj ) material_obj, _",
"= Material.objects.get_or_create( name=material ) Part.objects.create( drawing=drawing, division=div_obj, x=x, y=y, z=z, price=int(price), material=material_obj, outsource=outsource",
"= _get(row, 16) try: main_division = int(main_division) except: pass try: sub_division = int(sub_division)",
"str(_get(row, 0)) y = str(_get(row, 1)) z = str(_get(row, 2)) material = _get(row,"
] |
[
"import Resource class Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint). The",
"resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data",
"access biographic and demographic data on the following personnel involved in a football",
"on the following personnel involved in a football match: * Players, * Managers,",
"in a football match: * Players, * Managers, * Match referees. Derived from",
"* Managers, * Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri,",
"auth): \"\"\" Constructor of Personnel class. :param resource: Name of resource. :type resource:",
"Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access",
":param resource: Name of resource. :type resource: string :param base_uri: Base URI of",
"resources let you access biographic and demographic data on the following personnel involved",
"resource: Name of resource. :type resource: string :param base_uri: Base URI of API.",
"the following personnel involved in a football match: * Players, * Managers, *",
"API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel,",
"string :param auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth) self.endpoint +=",
"\"\"\" Constructor of Personnel class. :param resource: Name of resource. :type resource: string",
"The Personnel resources let you access biographic and demographic data on the following",
":type resource: string :param base_uri: Base URI of API. :type base_uri: string :param",
"resource: string :param base_uri: Base URI of API. :type base_uri: string :param auth:",
"__init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel class. :param resource: Name of",
"\"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel class. :param resource:",
"class. :param resource: Name of resource. :type resource: string :param base_uri: Base URI",
"Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth) self.endpoint += \"/personnel/%s\" % resource",
"following personnel involved in a football match: * Players, * Managers, * Match",
"of Personnel class. :param resource: Name of resource. :type resource: string :param base_uri:",
"string :param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication",
"biographic and demographic data on the following personnel involved in a football match:",
"Players, * Managers, * Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource,",
"Managers, * Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth):",
"Personnel resources let you access biographic and demographic data on the following personnel",
"base_uri, auth): \"\"\" Constructor of Personnel class. :param resource: Name of resource. :type",
"let you access biographic and demographic data on the following personnel involved in",
"of resource. :type resource: string :param base_uri: Base URI of API. :type base_uri:",
":type base_uri: string :param auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth)",
"involved in a football match: * Players, * Managers, * Match referees. Derived",
"Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel",
"def __init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel class. :param resource: Name",
"Name of resource. :type resource: string :param base_uri: Base URI of API. :type",
"a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic",
"REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic",
"Personnel class. :param resource: Name of resource. :type resource: string :param base_uri: Base",
"Base URI of API. :type base_uri: string :param auth: Authentication credential. :type auth:",
"Resource class Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel",
"* Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\"",
"you access biographic and demographic data on the following personnel involved in a",
"data on the following personnel involved in a football match: * Players, *",
"football match: * Players, * Managers, * Match referees. Derived from :class:`Resource`. \"\"\"",
"* Players, * Managers, * Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self,",
"Match referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor",
":class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel class. :param",
"(/personnel/<resource> endpoint). The Personnel resources let you access biographic and demographic data on",
"auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth) self.endpoint += \"/personnel/%s\" %",
"Constructor of Personnel class. :param resource: Name of resource. :type resource: string :param",
"of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple \"\"\"",
"URI of API. :type base_uri: string :param auth: Authentication credential. :type auth: tuple",
"Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you access biographic and",
"base_uri: string :param auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth) self.endpoint",
"and demographic data on the following personnel involved in a football match: *",
":param auth: Authentication credential. :type auth: tuple \"\"\" super(Personnel, self).__init__(base_uri,auth) self.endpoint += \"/personnel/%s\"",
":param base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential.",
"match: * Players, * Managers, * Match referees. Derived from :class:`Resource`. \"\"\" def",
"personnel involved in a football match: * Players, * Managers, * Match referees.",
"referees. Derived from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor of",
"resource, base_uri, auth): \"\"\" Constructor of Personnel class. :param resource: Name of resource.",
"a football match: * Players, * Managers, * Match referees. Derived from :class:`Resource`.",
"base_uri: Base URI of API. :type base_uri: string :param auth: Authentication credential. :type",
"\"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let you",
"soccermetrics.rest.resources import Resource class Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint).",
"endpoint). The Personnel resources let you access biographic and demographic data on the",
"from :class:`Resource`. \"\"\" def __init__(self, resource, base_uri, auth): \"\"\" Constructor of Personnel class.",
"from soccermetrics.rest.resources import Resource class Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource>",
"resource. :type resource: string :param base_uri: Base URI of API. :type base_uri: string",
"demographic data on the following personnel involved in a football match: * Players,",
"Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources let",
"class Personnel(Resource): \"\"\" Represents a Personnel REST resource (/personnel/<resource> endpoint). The Personnel resources"
] |
[
"aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\",",
"call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY),",
"from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP),",
"\"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\",",
"\"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\",",
"\"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_FIGHTER), \"--group_id\", str(EVE_GROUP_ID_HARVESTABLE_CLOUD), )",
"EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads",
"\"Preloads data required for aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\",",
"for aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL),",
"*args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE),",
"import BaseCommand from ... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY,",
"BaseCommand from ... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE,",
"EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data",
"data required for aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__,",
") class Command(BaseCommand): help = \"Preloads data required for aa-buybacks2 from ESI\" def",
"def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE),",
"django.core.management.base import BaseCommand from ... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE,",
"handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\",",
"**options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\",",
"help = \"Preloads data required for aa-buybacks2 from ESI\" def handle(self, *args, **options):",
"\"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY), \"--category_id\",",
"EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data required",
"EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help =",
"from django.core.management.base import BaseCommand from ... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID,",
"EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data required for aa-buybacks2",
"str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY),",
"str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_FIGHTER),",
"from ... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER,",
"import call_command from django.core.management.base import BaseCommand from ... import __title__ from ...constants import",
"EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data required for",
"from django.core.management import call_command from django.core.management.base import BaseCommand from ... import __title__ from",
"\"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_FIGHTER), \"--group_id\",",
"__title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE),",
"...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD,",
"ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\",",
"required for aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command( \"eveuniverse_load_types\", __title__, \"--category_id\",",
"str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID),",
"\"eveuniverse_load_types\", __title__, \"--category_id\", str(EVE_CATEGORY_ID_MATERIAL), \"--category_id\", str(EVE_CATEGORY_ID_SHIP), \"--category_id\", str(EVE_CATEGORY_ID_MODULE), \"--category_id\", str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\",",
"str(EVE_CATEGORY_ID_CHARGE), \"--category_id\", str(EVE_CATEGORY_ID_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_DRONE), \"--category_id\", str(EVE_CATEGORY_ID_ASTEROID), \"--category_id\", str(EVE_CATEGORY_ID_PLANETARY_COMMODITY), \"--category_id\", str(EVE_CATEGORY_ID_FIGHTER), \"--group_id\", str(EVE_GROUP_ID_HARVESTABLE_CLOUD),",
"import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, )",
"EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data required for aa-buybacks2 from",
"class Command(BaseCommand): help = \"Preloads data required for aa-buybacks2 from ESI\" def handle(self,",
"= \"Preloads data required for aa-buybacks2 from ESI\" def handle(self, *args, **options): call_command(",
"... import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL,",
"import __title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE,",
"__title__ from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY,",
"( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class",
"EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand):",
"EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP, EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help",
"call_command from django.core.management.base import BaseCommand from ... import __title__ from ...constants import (",
"from ...constants import ( EVE_CATEGORY_ID_ASTEROID, EVE_CATEGORY_ID_CHARGE, EVE_CATEGORY_ID_COMMODITY, EVE_CATEGORY_ID_DRONE, EVE_CATEGORY_ID_FIGHTER, EVE_CATEGORY_ID_MATERIAL, EVE_CATEGORY_ID_MODULE, EVE_CATEGORY_ID_PLANETARY_COMMODITY, EVE_CATEGORY_ID_SHIP,",
"Command(BaseCommand): help = \"Preloads data required for aa-buybacks2 from ESI\" def handle(self, *args,",
"django.core.management import call_command from django.core.management.base import BaseCommand from ... import __title__ from ...constants",
"EVE_GROUP_ID_HARVESTABLE_CLOUD, ) class Command(BaseCommand): help = \"Preloads data required for aa-buybacks2 from ESI\""
] |
[
"= 127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] = tag.id() i +=",
"+= 1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] = tag.cy() i +=",
"tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i += 1",
"import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory if the",
"= img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if",
"modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory if",
"ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory if the resolution",
"the resolution is much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus",
"TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i = 1",
"= 2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img =",
"clock.tick() img = sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11 without \"families\".",
"defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i",
"parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock =",
"# defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags)",
"while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags() #",
"color = 127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] = tag.id() i",
"sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory if the resolution is",
"= ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True)",
"modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] = tag.cy() i += 1 #print(modbus.REGISTER[0:15])",
"from pyb import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we",
"= 1 for tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family()",
"i += 1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] = tag.cy() i",
"= sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0]",
"uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time =",
"if tags: print(tags) i = 1 for tag in tags: img.draw_rectangle(tag.rect(), color =",
"tags: print(tags) i = 1 for tag in tags: img.draw_rectangle(tag.rect(), color = 127)",
"image import time from pyb import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE)",
"img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags:",
"else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11 without",
"of memory if the resolution is much bigger... uart = UART(3,115200, parity=None, stop=2,",
"<gh_stars>1000+ import sensor, image import time from pyb import UART from modbus import",
"= len(tags) if tags: print(tags) i = 1 for tag in tags: img.draw_rectangle(tag.rect(),",
"stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock()",
"len(tags) if tags: print(tags) i = 1 for tag in tags: img.draw_rectangle(tag.rect(), color",
"import sensor, image import time from pyb import UART from modbus import ModbusRTU",
"# we run out of memory if the resolution is much bigger... uart",
"without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i = 1 for",
"= UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000)",
"time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags()",
"we run out of memory if the resolution is much bigger... uart =",
"is much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart,",
"memory if the resolution is much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1,",
"+= 1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i +=",
"modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i = 1 for tag in",
"for tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i +=",
"if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags() # defaults",
"import time from pyb import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA)",
"sensor.skip_frames(time = 2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img",
"timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True): if",
"modbus.REGISTER[0] = len(tags) if tags: print(tags) i = 1 for tag in tags:",
"modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i]",
"= tag.cx() i += 1 modbus.REGISTER[i] = tag.cy() i += 1 #print(modbus.REGISTER[0:15]) #print(clock.fps())",
"modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True): if modbus.any():",
"tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] = tag.cy()",
"img = sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear()",
"time from pyb import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) #",
"from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory",
"ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else:",
"sensor.set_framesize(sensor.QQVGA) # we run out of memory if the resolution is much bigger...",
"sensor, image import time from pyb import UART from modbus import ModbusRTU sensor.reset()",
"tags = img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags)",
"= time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags =",
"if the resolution is much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4)",
"sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] =",
"sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of memory if the resolution is much",
"timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True):",
"= tag.family() i += 1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] =",
"2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot()",
"import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out",
"clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags",
"i = 1 for tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] =",
"much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999)",
"1 for tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i",
"img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] = tag.id()",
"\"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i = 1 for tag",
"UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run out of",
"modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i]",
"pyb import UART from modbus import ModbusRTU sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) # we run",
"modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags() # defaults to TAG36H11",
"1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i += 1",
"register_num=9999) sensor.skip_frames(time = 2000) clock = time.clock() while(True): if modbus.any(): modbus.handle(debug=True) else: clock.tick()",
"= tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] =",
"print(tags) i = 1 for tag in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i]",
"modbus.any(): modbus.handle(debug=True) else: clock.tick() img = sensor.snapshot() tags = img.find_apriltags() # defaults to",
"i += 1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] = tag.cx() i",
"bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time",
"resolution is much bigger... uart = UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus =",
"UART(3,115200, parity=None, stop=2, timeout=1, timeout_char=4) modbus = ModbusRTU(uart, register_num=9999) sensor.skip_frames(time = 2000) clock",
"tag.family() i += 1 modbus.REGISTER[i] = tag.id() i += 1 modbus.REGISTER[i] = tag.cx()",
"1 modbus.REGISTER[i] = tag.cx() i += 1 modbus.REGISTER[i] = tag.cy() i += 1",
"127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] = tag.id() i += 1",
"out of memory if the resolution is much bigger... uart = UART(3,115200, parity=None,",
"to TAG36H11 without \"families\". modbus.clear() modbus.REGISTER[0] = len(tags) if tags: print(tags) i =",
"in tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i]",
"tags: img.draw_rectangle(tag.rect(), color = 127) modbus.REGISTER[i] = tag.family() i += 1 modbus.REGISTER[i] =",
"run out of memory if the resolution is much bigger... uart = UART(3,115200,"
] |
[
"cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', package_data={}, data_files=[],",
"url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable',",
"name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom resources' ), long_description=readme +",
"Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python",
"import setup with codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file:",
"-*- from __future__ import absolute_import import codecs from setuptools import setup with codecs.open('README.rst')",
"'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI",
"setup with codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history",
"readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0',",
"resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT',",
":: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python",
"'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ],",
"as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building",
":: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python ::",
"2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3',",
"codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read()",
"Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language",
"import absolute_import import codecs from setuptools import setup with codecs.open('README.rst') as readme_file: readme",
":: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language ::",
"history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 -",
"], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*,",
"'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language",
"= readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=(",
"License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7',",
"setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom resources' ), long_description=readme",
"with codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history =",
"version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom resources' ), long_description=readme + '\\n\\n'",
"decorators for building CloudFormation custom resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout',",
"Python :: 3.6', ], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7,",
"from setuptools import setup with codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst')",
"'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming",
"license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License",
"3.6', ], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*,",
"for building CloudFormation custom resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>',",
"'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2',",
"with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators",
":: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming",
"Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python ::",
"'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming",
":: Python :: 3.6', ], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"],",
"custom resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>',",
"MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python ::",
"resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', package_data={}, data_files=[], entry_points={}, )",
"CloudFormation custom resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>',",
"+ '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status",
"aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', package_data={},",
"classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License ::",
"author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience",
"Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved",
"Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language ::",
"keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',",
"as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup(",
":: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved ::",
"custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', package_data={}, data_files=[], entry_points={},",
"OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language",
"'Wrapper decorators for building CloudFormation custom resources' ), long_description=readme + '\\n\\n' + history,",
"= history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom resources'",
"Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python",
"'\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status ::",
"), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[",
":: 3.6', ], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"], install_requires=[\"requests\"], python_requires='>=2.7, !=3.0.*,",
"author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended",
"import codecs from setuptools import setup with codecs.open('README.rst') as readme_file: readme = readme_file.read()",
"readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout',",
"# -*- coding:utf-8 -*- from __future__ import absolute_import import codecs from setuptools import",
"__future__ import absolute_import import codecs from setuptools import setup with codecs.open('README.rst') as readme_file:",
"3', 'Programming Language :: Python :: 3.6', ], keywords='cloudformation aws cloud custom resource",
":: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language ::",
"history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom",
"'Programming Language :: Python :: 3.6', ], keywords='cloudformation aws cloud custom resource amazon',",
"- Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License',",
"setuptools import setup with codecs.open('README.rst') as readme_file: readme = readme_file.read() with codecs.open('HISTORY.rst') as",
"maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience ::",
"Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], keywords='cloudformation",
"Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language ::",
":: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python",
"readme_file.read() with codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper",
"Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language",
"coding:utf-8 -*- from __future__ import absolute_import import codecs from setuptools import setup with",
"from __future__ import absolute_import import codecs from setuptools import setup with codecs.open('README.rst') as",
":: Python :: 3', 'Programming Language :: Python :: 3.6', ], keywords='cloudformation aws",
"codecs.open('HISTORY.rst') as history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for",
"history_file: history = history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation",
"history_file.read() setup( name='cfn-resource-timeout', version='1.2.0', description=( 'Wrapper decorators for building CloudFormation custom resources' ),",
"Language :: Python :: 3.6', ], keywords='cloudformation aws cloud custom resource amazon', py_modules=[\"cfn_resource\"],",
"+ history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5",
":: 3', 'Programming Language :: Python :: 3.6', ], keywords='cloudformation aws cloud custom",
"maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers',",
"codecs from setuptools import setup with codecs.open('README.rst') as readme_file: readme = readme_file.read() with",
"building CloudFormation custom resources' ), long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>',",
":: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python ::",
"-*- coding:utf-8 -*- from __future__ import absolute_import import codecs from setuptools import setup",
"long_description=readme + '\\n\\n' + history, url='https://github.com/timeoutdigital/cfn-resource-timeout', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', license='MIT', classifiers=[ 'Development",
"absolute_import import codecs from setuptools import setup with codecs.open('README.rst') as readme_file: readme =",
"description=( 'Wrapper decorators for building CloudFormation custom resources' ), long_description=readme + '\\n\\n' +",
"2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6',",
"Python :: 3', 'Programming Language :: Python :: 3.6', ], keywords='cloudformation aws cloud",
"5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT",
"Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming"
] |
[
"setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger logger =",
"= \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir = log_dir self.logger",
"log_console_format = \"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False",
"handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format)",
"# # # File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) #",
"# self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d",
"# \"\"\" # Initialize logger. # # :param str log_dir: directory to save",
"console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self,",
"str log_dir: directory to save log file # :param filename: log filename #",
"# self.logger.propagate = False # # # File handler # self.fh = logging.FileHandler(os.path.join(log_dir,",
"# # :param str msg: string to log # \"\"\" # self.logger.info(msg) #",
"= logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: #",
"for d in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir = '%d_%s' %",
"Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') #",
"idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir",
"%(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir)",
"filename='log.txt'): # \"\"\" # Initialize logger. # # :param str log_dir: directory to",
"self.log_dir = log_dir # self.logger = logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO)",
"import strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory path to log :param",
"os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\"",
"log # \"\"\" # self.logger.info(msg) # # def close(self): # \"\"\" # close",
"filename # \"\"\" # self.log_dir = log_dir # self.logger = logging.getLogger('StarRec - '",
"# # Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format =",
"filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) #",
"# def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger. # # :param",
"msg: string to log # \"\"\" # self.logger.info(msg) # # def close(self): #",
"file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]:",
"- ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # #",
"Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO)",
"idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir)",
"# self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\" # Log given msg.",
"= os.listdir(log_dir) if len(log_dirs) == 0: idx = 0 else: idx_list = sorted([int(d.split('_')[0])",
"not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx = 0",
"info(self, msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir):",
"self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\" # Log given msg. #",
"close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\"",
"1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not",
"# def info(self, msg): # \"\"\" # Log given msg. # # :param",
"self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')",
"self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" #",
"self.logger.info(msg) # # def close(self): # \"\"\" # close file and command line",
"string to log # \"\"\" # self.logger.info(msg) # # def close(self): # \"\"\"",
"self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'),",
"log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) ==",
"False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler)",
"% (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir",
"ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg): #",
"= \"%(message)s\" # Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate",
"logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\" #",
"sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir = '%d_%s'",
"file # :param filename: log filename # \"\"\" # self.log_dir = log_dir #",
"= logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return",
"\"\"\" # self.logger.info(msg) # # def close(self): # \"\"\" # close file and",
"file and command line log stream. # # \"\"\" # self.logger.removeHandler(self.fh) # self.logger.removeHandler(self.ch)",
"d in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx,",
"class logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger. #",
"<reponame>JiwooKimAR/MWP-solver-with-pretrained-language-model import os from time import strftime import logging def make_log_dir(log_dir): \"\"\" Generate",
"os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir):",
"encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for handle",
"log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir = log_dir",
"# self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler # self.ch = logging.StreamHandler(sys.stdout)",
"# \"\"\" # self.logger.info(msg) # # def close(self): # \"\"\" # close file",
"cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir): log_file_format",
"# # :param str log_dir: directory to save log file # :param filename:",
"import logging def make_log_dir(log_dir): \"\"\" Generate directory path to log :param log_dir: :return:",
"Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main",
"0 else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1] +",
"file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for handle in",
"in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\"",
"logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger",
"= logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler =",
"idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx =",
"'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: # def __init__(self,",
"= log_dir # self.logger = logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) #",
"to log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir)",
"# self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh)",
"logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler",
"console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg):",
"__init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger. # # :param str log_dir:",
"# \"\"\" # Log given msg. # # :param str msg: string to",
"'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for",
"self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler()",
"logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir,",
"idx = idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir =",
"and command line log stream. # # \"\"\" # self.logger.removeHandler(self.fh) # self.logger.removeHandler(self.ch) #",
"class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" #",
"msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format",
"file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: # def __init__(self, log_dir,",
"given msg. # # :param str msg: string to log # \"\"\" #",
"\"\"\" Generate directory path to log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir):",
"= idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir,",
"log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir =",
"# :param filename: log filename # \"\"\" # self.log_dir = log_dir # self.logger",
"file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: # def __init__(self, log_dir, filename='log.txt'):",
"log filename # \"\"\" # self.log_dir = log_dir # self.logger = logging.getLogger('StarRec -",
"cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir):",
"+ 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if",
"log_console_format = \"%(message)s\" # Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO)",
"close(self): # \"\"\" # close file and command line log stream. # #",
"\"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir = log_dir self.logger =",
"logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self):",
"datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler # self.ch",
"%(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler #",
"console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler)",
"self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch)",
"+ filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # # File handler",
"make_log_dir(log_dir): \"\"\" Generate directory path to log :param log_dir: :return: \"\"\" if not",
"# File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format =",
"log_dirs]) idx = idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir",
"log_dir: directory to save log file # :param filename: log filename # \"\"\"",
"directory to save log file # :param filename: log filename # \"\"\" #",
"self.logger.propagate = False # # # File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename))",
"def close(self): # \"\"\" # close file and command line log stream. #",
"os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx = 0 else:",
"= False # # # File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) #",
"= \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO)",
"if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx =",
"self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8')",
"= \"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler",
"self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main",
"# self.logger = logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate =",
"# fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # #",
"in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir = '%d_%s' % (idx, strftime('%Y%m%d-%H%M'))",
"os.listdir(log_dir) if len(log_dirs) == 0: idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for",
"def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s:",
"self.logger.addHandler(self.fh) # # # Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) #",
"= logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def",
"= logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') #",
"self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle)",
"\"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler =",
"os from time import strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory path",
"# def close(self): # \"\"\" # close file and command line log stream.",
"full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def",
"self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self,",
"not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s:",
"log_dir # self.logger = logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate",
"self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler # self.ch = logging.StreamHandler(sys.stdout) #",
"close file and command line log stream. # # \"\"\" # self.logger.removeHandler(self.fh) #",
"(idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class",
"handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format =",
"def make_log_dir(log_dir): \"\"\" Generate directory path to log :param log_dir: :return: \"\"\" if",
":return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0:",
"\"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx",
"log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx = 0 else: idx_list =",
"logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format))",
"filename: log filename # \"\"\" # self.log_dir = log_dir # self.logger = logging.getLogger('StarRec",
"# Initialize logger. # # :param str log_dir: directory to save log file",
"= logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler)",
"# close file and command line log stream. # # \"\"\" # self.logger.removeHandler(self.fh)",
"def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger",
"self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # # File handler # self.fh =",
"def info(self, msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def",
"file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg)",
"'%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return",
"from time import strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory path to",
"if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir): log_file_format =",
"Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler",
"return logger # class logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\" #",
"logger # class logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize",
"# # def info(self, msg): # \"\"\" # Log given msg. # #",
"logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # #",
"logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG)",
"File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s:",
"Generate directory path to log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir)",
"# Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler()",
"len(log_dirs) == 0: idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for d in",
"0: idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx",
"logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False # #",
"def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger. # # :param str",
"logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger",
"logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler =",
"== 0: idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs])",
"\"\"\" # Initialize logger. # # :param str log_dir: directory to save log",
"# self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def",
"handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s',",
"logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir,",
"logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: # def __init__(self, log_dir, filename='log.txt'): #",
"console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler)",
"self.logger.addHandler(file_handler) def info(self, msg): self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown()",
"log_dir, filename='log.txt'): # \"\"\" # Initialize logger. # # :param str log_dir: directory",
"log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger logger = logging.getLogger()",
"time import strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory path to log",
"self.logger.info(msg) def close(self): for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format =",
"# class logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger.",
"logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'))",
"to save log file # :param filename: log filename # \"\"\" # self.log_dir",
"msg): # \"\"\" # Log given msg. # # :param str msg: string",
"logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format)",
"%(message)s\" log_console_format = \"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate =",
"\"\"\" # close file and command line log stream. # # \"\"\" #",
"# Log given msg. # # :param str msg: string to log #",
"logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) def",
"console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class",
":param str log_dir: directory to save log file # :param filename: log filename",
"# self.log_dir = log_dir # self.logger = logging.getLogger('StarRec - ' + filename) #",
"# # # Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format",
"# self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\" # Log",
"= 0 else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1]",
"os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format",
"= logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) #",
"log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format))",
"self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\" # Log given",
"Initialize logger. # # :param str log_dir: directory to save log file #",
"# self.logger.info(msg) # # def close(self): # \"\"\" # close file and command",
"\"%(message)s\" # Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate =",
"= logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console",
"= sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1] + 1 cur_log_dir =",
"# :param str log_dir: directory to save log file # :param filename: log",
"# self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # # File handler # self.fh",
"def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger logger",
"msg. # # :param str msg: string to log # \"\"\" # self.logger.info(msg)",
":param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs)",
"info(self, msg): # \"\"\" # Log given msg. # # :param str msg:",
"filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # # File handler #",
"self.logger = logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False",
"logging def make_log_dir(log_dir): \"\"\" Generate directory path to log :param log_dir: :return: \"\"\"",
"# self.logger.addHandler(self.fh) # # # Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO)",
"= logging.getLogger('StarRec - ' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False #",
"= '%d_%s' % (idx, strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir)",
"def info(self, msg): # \"\"\" # Log given msg. # # :param str",
"# Console handler # self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s')",
"\"\"\" # self.log_dir = log_dir # self.logger = logging.getLogger('StarRec - ' + filename)",
"= logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler =",
"# :param str msg: string to log # \"\"\" # self.logger.info(msg) # #",
"self.fh.setLevel(logging.DEBUG) # fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) #",
"return full_log_dir class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format =",
"path to log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs =",
"logger.addHandler(file_handler) return logger # class logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\"",
"save log file # :param filename: log filename # \"\"\" # self.log_dir =",
"= log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO)",
"log file # :param filename: log filename # \"\"\" # self.log_dir = log_dir",
"logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler",
"console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger #",
":param str msg: string to log # \"\"\" # self.logger.info(msg) # # def",
"os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if len(log_dirs) == 0: idx = 0 else: idx_list",
"# \"\"\" # self.log_dir = log_dir # self.logger = logging.getLogger('StarRec - ' +",
"False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format))",
"\"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger logger = logging.getLogger() logger.setLevel(logging.INFO) logger.propagate",
"else: idx_list = sorted([int(d.split('_')[0]) for d in log_dirs]) idx = idx_list[-1] + 1",
"= os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger: def __init__(self,",
"False # # # File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG)",
"# self.ch = logging.StreamHandler(sys.stdout) # self.ch.setLevel(logging.INFO) # ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) #",
"to log # \"\"\" # self.logger.info(msg) # # def close(self): # \"\"\" #",
"logger: # def __init__(self, log_dir, filename='log.txt'): # \"\"\" # Initialize logger. # #",
"strftime('%Y%m%d-%H%M')) full_log_dir = os.path.join(log_dir, cur_log_dir) if not os.path.exists(full_log_dir): os.mkdir(full_log_dir) return full_log_dir class Logger:",
"# Main logger self.log_dir = log_dir self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False",
"__init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\" # Main logger self.log_dir",
"# \"\"\" # close file and command line log stream. # # \"\"\"",
"self.logger = logging.getLogger(log_dir) self.logger.setLevel(logging.INFO) self.logger.propagate = False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler",
"%H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # # Console handler # self.ch =",
"\"\"\" # Log given msg. # # :param str msg: string to log",
"log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs = os.listdir(log_dir) if",
"full_log_dir class Logger: def __init__(self, log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format = \"%(message)s\"",
"logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger: # def",
"' + filename) # self.logger.setLevel(logging.INFO) # self.logger.propagate = False # # # File",
"# # def close(self): # \"\"\" # close file and command line log",
"# ch_format = logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg):",
"Log given msg. # # :param str msg: string to log # \"\"\"",
"import os from time import strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory",
":param filename: log filename # \"\"\" # self.log_dir = log_dir # self.logger =",
"directory path to log :param log_dir: :return: \"\"\" if not os.path.exists(log_dir): os.mkdir(log_dir) log_dirs",
"command line log stream. # # \"\"\" # self.logger.removeHandler(self.fh) # self.logger.removeHandler(self.ch) # logging.shutdown()",
"file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format)) logger.addHandler(console_handler) logger.addHandler(file_handler) return logger # class logger:",
"for handle in self.logger.handlers[:]: self.logger.removeHandler(handle) logging.shutdown() def setup_logger(log_dir): log_file_format = \"[%(lineno)d]%(asctime)s: %(message)s\" log_console_format",
"= False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log'), encoding='UTF-8') file_handler.setLevel(logging.DEBUG)",
"= logging.Formatter('%(message)s') # self.ch.setFormatter(ch_format) # self.logger.addHandler(self.ch) # # def info(self, msg): # \"\"\"",
"fh_format = logging.Formatter('%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # self.fh.setFormatter(fh_format) # self.logger.addHandler(self.fh) # # #",
"strftime import logging def make_log_dir(log_dir): \"\"\" Generate directory path to log :param log_dir:",
"= False console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter(log_console_format)) file_handler = logging.FileHandler(os.path.join(log_dir, 'experiments.log')) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter(log_file_format))",
"logger. # # :param str log_dir: directory to save log file # :param",
"# # File handler # self.fh = logging.FileHandler(os.path.join(log_dir, filename)) # self.fh.setLevel(logging.DEBUG) # fh_format",
"if len(log_dirs) == 0: idx = 0 else: idx_list = sorted([int(d.split('_')[0]) for d",
"str msg: string to log # \"\"\" # self.logger.info(msg) # # def close(self):"
] |
[
"v[idxs] = i return v def summary(results: np.array, varname: str = None): \"\"\"",
"infile: # Skip blank lines and comments. if not line.strip() or line.strip().startswith('#'): continue",
"# Observed agreement: How often the two annotators actually agreed. # Equivalent to",
"default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False return args def",
"\"print\", \"log\". Default is \"suppress\". If \"log\", writes file names to \"disagreements.log\" in",
"1: k = 0.0 else: k = (p_o - p_e) / (1 -",
"f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other) -> bool:",
"a.end) for a in anns if a.label == lab] idxs = [j for",
"of the variable being summarized. \"\"\" if varname is not None: print(varname) if",
"range(len(labels)+1)]) if p_e == 1: k = 0.0 else: k = (p_o -",
"of paths to .ann files to read. returns: List of annotations. \"\"\" all_anns",
"return all([self.label == other.label, self.start == other.start, self.end == other.end, self.text == other.text])",
"of entity labels. \"\"\" labels = set() with open(ann_conf, 'r') as infile: copy",
"this annotation task --disagreements, Whether to suppress, print, or log files in which",
"\"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\", writes file names to \"disagreements.log\"",
"annotated. If None, uses indir1. param disagreements: How disagreements are logged. Possible values",
"b2 = BratANN.from_string(ann) >>> b1 == b2 True >>> b3 = BratANN(\"T3\", \"ent\",",
"[--test, Test the ira function] [--docdir, Directory containing the documents that were annotated.",
"rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa",
"List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files and converts their annotations to",
"to annotation.conf returns: set of entity labels. \"\"\" labels = set() with open(ann_conf,",
"1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the two annotators are expected",
"parse_args(): def usage(): return \"\"\"ira.py [--help, Show this help message and exit] [--test,",
"n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 == k) for",
"b3 False \"\"\" def __init__(self, num: str, label: str, start: int, end: int,",
"lab) in enumerate(labels): i += 1 # 0 is reserved for no label",
"docs = [\"The cats sat on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\",",
"brat annotated files from two annotators for a sequence labeling task (e.g. NER).",
"np.zeros(len(doc)) # For each character for (i, lab) in enumerate(labels): i += 1",
"v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement:",
"rater j predicted label k, n_j_k: # p_e = (1/N^2) * sum_k (n_1_k",
"glob import glob from typing import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>)",
"disagree. Possible values are \"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\", writes",
"line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy = True elif line.strip()",
"p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the two annotators",
"Set[str]) -> np.array: \"\"\" Converts the document into an integer vector. The value",
"other.text]) else: return False def parse_args(): def usage(): return \"\"\"ira.py [--help, Show this",
"the ira function] [--docdir, Directory containing the documents that were annotated. If not",
"'r') as infile: copy = False for line in infile: # Skip blank",
"annotation.conf returns: set of entity labels. \"\"\" labels = set() with open(ann_conf, 'r')",
"character position, with 0 indicating no annotation. So an annotation task with 3",
"Directory containing the .txt files which were annotated. If None, uses indir1. param",
"===\") for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements",
"def parse_args(): def usage(): return \"\"\"ira.py [--help, Show this help message and exit]",
"\"[entities]\": copy = True elif line.strip() == \"[relations]\": copy = False elif copy",
"p_o)) # Expected agreement: How often the two annotators are expected to #",
"required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str,",
"= \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>>",
"anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if",
"label self.start = int(start) self.end = int(end) self.text = text @classmethod def from_string(cls,",
"noqa \"\"\" Computes Cohen's kappa and percentage agreement between two annotators. param docs:",
"== lab] idxs = [j for mask in idxs for j in mask]",
"annotated. param anns: Annotations for each document. param labels: Set of entity labels",
"Show this help message and exit] [--test, Test the ira function] [--docdir, Directory",
"List of annotations. \"\"\" all_anns = [] for annfile in fnames: anns =",
"\"cat \") >>> b1 == b3 False \"\"\" def __init__(self, num: str, label:",
"continue if line.strip() == \"[entities]\": copy = True elif line.strip() == \"[relations]\": copy",
"indir1.] --indir1, Directory containing first annotators annotations --indir2, Directory containing second annotators annotations",
"considering equal iff they have the same label, offset, and text. Equality does",
"in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads",
"b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1",
"into an integer vector. The value of each element corresponds to the entity",
"\"\"\" Prints summary statistics for the supplied results. param results: Numeric array of",
"to .txt files to read. returns: List of input documents. \"\"\" all_docs =",
".ann files and converts their annotations to BratANN objects. param fnames: List of",
"percentage agreement for a set of brat annotated files from two annotators for",
"offset, and text. Equality does not consider the annotation number, e.g. T1 \"\"\"",
"choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False return args def main(indir1:",
"Input directories containing the first and second annotators .ann files, respectively. param ann_conf:",
"annotators. param docs: List of documents, output of read_docs(). param anns1: List of",
"their annotations to BratANN objects. param fnames: List of paths to .ann files",
"False return args def main(indir1: str, indir2: str, ann_conf: str, docdir: str =",
"@classmethod def from_string(cls, string: str): (n, l, s, e, t) = string.split(maxsplit=4) return",
"s in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2,",
"\"\"\"ira.py [--help, Show this help message and exit] [--test, Test the ira function]",
"example to test ira(). \"\"\" docs = [\"The cats sat on the mat\"]",
"Computes character-level Cohen's kappa and percentage agreement for a set of brat annotated",
"True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str])",
"= read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2): raise",
"return False def parse_args(): def usage(): return \"\"\"ira.py [--help, Show this help message",
"Cohen's kappa at the token level for a sequence labeling task.\"\"\" parser =",
"often the two annotators actually agreed. # Equivalent to accuracy. p_o = np.sum(v1",
"0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\": args = parse_args() if",
"{self.text}'>\" # noqa def __eq__(self, other) -> bool: \"\"\" Overrides the default implementation",
"[os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames]",
"Set of labels annotated, output of read_labels(). returns: Kappa and percentage agreement for",
"in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i],",
"\"disagreements.log\" in the current working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at",
"or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy = True elif line.strip() ==",
"l, int(s), int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" #",
"for s in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1,",
"# noqa \"\"\" Computes Cohen's kappa and percentage agreement between two annotators. param",
"to # agree. For number of items N, labels k, and the number",
"(n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 ==",
"files to read. returns: List of input documents. \"\"\" all_docs = [] for",
"raise ValueError(\"Different numbers of documents and annotations.\") # Read the entity labels. labels",
"document into an integer vector. The value of each element corresponds to the",
"files which were annotated. If None, uses indir1. param disagreements: How disagreements are",
"kappas = np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs): denom = len(docs[i])",
"agreement for each document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas =",
"results (e.g. kappas). param varname: (Optional) Name of the variable being summarized. \"\"\"",
"an integer vector. The value of each element corresponds to the entity type",
"2s, and 3s. param doc: Document that was annotated. param anns: Annotations for",
"List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa and percentage agreement between two",
"agreement for a set of brat annotated files from two annotators for a",
"are logged. Possible values are \"suppress\", \"print\" and \"log\". If \"suppress\", do nothing.",
"two annotators are expected to # agree. For number of items N, labels",
"ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test is True: return args parser",
"argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args()",
"label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement: How often",
"np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs): denom = len(docs[i]) v1 =",
"labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array,",
"a vector of 0s, 1s, 2s, and 3s. param doc: Document that was",
"range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i],",
"read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2,",
"= read_docs(doc_fnames) # Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in",
"= BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1 == b3 False \"\"\"",
"anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements",
"anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement: How often the",
"character level annotations. \"\"\" v = np.zeros(len(doc)) # For each character for (i,",
"entity labels for this task. returns: Vector of character level annotations. \"\"\" v",
"1, 5, \"cat \") >>> b1 == b3 False \"\"\" def __init__(self, num:",
"to the console. If \"log\", files that disagree will be written to \"disagreements.log\"",
".ann files, respectively. param ann_conf: Path to the annotation.conf file. param docdir: Directory",
"which were annotated. If None, uses indir1. param disagreements: How disagreements are logged.",
"denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the",
"param disagreements: How disagreements are logged. Possible values are \"suppress\", \"print\" and \"log\".",
"the default implementation Two BratANNs are considering equal iff they have the same",
"annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1,",
"import datetime import numpy as np from glob import glob from typing import",
"Compute inter rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa,",
"for j in mask] v[idxs] = i return v def summary(results: np.array, varname:",
"\"[relations]\": copy = False elif copy is True: labels.add(line.strip()) return labels def ira(docs:",
"from_string(cls, string: str): (n, l, s, e, t) = string.split(maxsplit=4) return cls(n, l,",
"anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers",
"of paths to .txt files to read. returns: List of input documents. \"\"\"",
"current working directory. \"\"\" # Read in the documents. if docdir is not",
"the number of times # rater j predicted label k, n_j_k: # p_e",
"anns1: List of first annotators annotations, output of read_anns(). param anns2: List of",
"l, s, e, t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def",
"List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage",
"self.start = int(start) self.end = int(end) self.text = text @classmethod def from_string(cls, string:",
"= False for line in infile: # Skip blank lines and comments. if",
"+/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small example to test",
"action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test is",
"self.end = int(end) self.text = text @classmethod def from_string(cls, string: str): (n, l,",
"files that disagree will be written to \"disagreements.log\" in the current working directory.",
"\"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = []",
"line.strip() == \"[entities]\": copy = True elif line.strip() == \"[relations]\": copy = False",
"bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w') as",
"(1 - p_e) p_os[i] = p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po)",
"self.start == other.start, self.end == other.end, self.text == other.text]) else: return False def",
"def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa",
"in range(len(labels)+1)]) if p_e == 1: k = 0.0 else: k = (p_o",
"console. If \"log\", files that disagree will be written to \"disagreements.log\" in the",
"annfile in fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return",
"exit] [--test, Test the ira function] [--docdir, Directory containing the documents that were",
"k, n_j_k: # p_e = (1/N^2) * sum_k (n_1_k * n_2_k) p_e =",
"f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label},",
"labels for this task. returns: Vector of character level annotations. \"\"\" v =",
"of the annotation at that character position, with 0 indicating no annotation. So",
"True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1 ==",
"labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with disagreements. if",
"{rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small example to",
"usage(): return \"\"\"ira.py [--help, Show this help message and exit] [--test, Test the",
"output of read_anns(). param labels: Set of labels annotated, output of read_labels(). returns:",
"type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\",",
"if args.test is True: import doctest doctest.testmod() test() else: main(args.indir1, args.indir2, args.annotation_conf, docdir=args.docdir,",
"the token level for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\",",
"= text @classmethod def from_string(cls, string: str): (n, l, s, e, t) =",
"0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\": args",
"\"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False return args def main(indir1: str,",
"Observed agreement: How often the two annotators actually agreed. # Equivalent to accuracy.",
"(i, lab) in enumerate(labels): i += 1 # 0 is reserved for no",
"If \"print\", prints files that disagree to the console. If \"log\", files that",
"string: str): (n, l, s, e, t) = string.split(maxsplit=4) return cls(n, l, int(s),",
"j predicted label k, n_j_k: # p_e = (1/N^2) * sum_k (n_1_k *",
"How often the two annotators actually agreed. # Equivalent to accuracy. p_o =",
"function] [--docdir, Directory containing the documents that were annotated. If not specified, looks",
"If not specified, looks in indir1.] --indir1, Directory containing first annotators annotations --indir2,",
"task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat annotation. >>> ann =",
"logged. Possible values are \"suppress\", \"print\" and \"log\". If \"suppress\", do nothing. If",
"self.text == other.text]) else: return False def parse_args(): def usage(): return \"\"\"ira.py [--help,",
"'{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other) -> bool: \"\"\"",
"[[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23",
"required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test",
"Directory containing first annotators annotations --indir2, Directory containing second annotators annotations --annotation_conf, The",
"first annotators annotations --indir2, Directory containing second annotators annotations --annotation_conf, The brat annotation.conf",
"Read in the documents. if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else:",
"in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2,",
"docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str])",
"sequence labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat annotation. >>>",
"23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\",",
"docs: List of documents, output of read_docs(). param anns1: List of first annotators",
"to the entity type of the annotation at that character position, with 0",
"If \"log\", files that disagree will be written to \"disagreements.log\" in the current",
"- p_e) p_os[i] = p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po) def",
"agreement: How often the two annotators actually agreed. # Equivalent to accuracy. p_o",
"[j for mask in idxs for j in mask] v[idxs] = i return",
"the supplied results. param results: Numeric array of results (e.g. kappas). param varname:",
"== 1: k = 0.0 else: k = (p_o - p_e) / (1",
"all_docs = [] for docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return",
"Reads in the documents. param fnames: List of paths to .txt files to",
"anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the document into an integer",
"test ira(). \"\"\" docs = [\"The cats sat on the mat\"] ann_strs1 =",
"and \"log\". If \"suppress\", do nothing. If \"print\", prints files that disagree to",
"other.start, self.end == other.end, self.text == other.text]) else: return False def parse_args(): def",
"== other.end, self.text == other.text]) else: return False def parse_args(): def usage(): return",
"glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the annotations.",
"+ '\\n')) for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def",
"rmean = np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean:",
"not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) #",
"returns: List of input documents. \"\"\" all_docs = [] for docfile in fnames:",
"def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity labels from annotation.conf. param",
"inter rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's",
"= label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement: How",
"and text. Equality does not consider the annotation number, e.g. T1 \"\"\" if",
"if p_e == 1: k = 0.0 else: k = (p_o - p_e)",
"def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the documents. param fnames: List",
"first and second annotators .ann files, respectively. param ann_conf: Path to the annotation.conf",
"\"log\". If \"suppress\", do nothing. If \"print\", prints files that disagree to the",
"indir{1,2}: Input directories containing the first and second annotators .ann files, respectively. param",
"agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03))",
"text: str): self.num = num self.label = label self.start = int(start) self.end =",
".ann files to read. returns: List of annotations. \"\"\" all_anns = [] for",
"doc: Document that was annotated. param anns: Annotations for each document. param labels:",
"labels) # Observed agreement: How often the two annotators actually agreed. # Equivalent",
"nothing. If \"print\", prints files that disagree to the console. If \"log\", files",
"__str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str:",
"anns2[i], labels) # Observed agreement: How often the two annotators actually agreed. #",
"copy = False elif copy is True: labels.add(line.strip()) return labels def ira(docs: List[str],",
"brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\",",
"documents that were annotated. If not specified, looks in indir1.] --indir1, Directory containing",
">>> ann = \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4,",
"anns if a.label == lab] idxs = [j for mask in idxs for",
"the documents. if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames =",
"which annotators disagree. Possible values are \"suppress\", \"print\", \"log\". Default is \"suppress\". If",
"two annotators. param docs: List of documents, output of read_docs(). param anns1: List",
"agreement between two annotators. param docs: List of documents, output of read_docs(). param",
"str, docdir: str = None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input",
"= ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do",
"vector of 0s, 1s, 2s, and 3s. param doc: Document that was annotated.",
"parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder",
"outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\")",
"\"\"\" Converts the document into an integer vector. The value of each element",
"args.test is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str,",
"= argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str,",
"\"\"\" # Read in the documents. if docdir is not None: doc_fnames =",
"all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity labels",
"to test ira(). \"\"\" docs = [\"The cats sat on the mat\"] ann_strs1",
"np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") #",
"actually agreed. # Equivalent to accuracy. p_o = np.sum(v1 == v2) / denom",
"as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx])",
"entity labels from annotation.conf. param ann_conf: Path to annotation.conf returns: set of entity",
"of labels annotated, output of read_labels(). returns: Kappa and percentage agreement for each",
"# agree. For number of items N, labels k, and the number of",
"prints files that disagree to the console. If \"log\", files that disagree will",
"None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read",
"Default is \"suppress\". If \"log\", writes file names to \"disagreements.log\" in the current",
"ann_conf: Path to annotation.conf returns: set of entity labels. \"\"\" labels = set()",
"annotators actually agreed. # Equivalent to accuracy. p_o = np.sum(v1 == v2) /",
"type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"])",
"= set() with open(ann_conf, 'r') as infile: copy = False for line in",
"b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1 == b3 False",
"BratANN objects. param fnames: List of paths to .ann files to read. returns:",
"to suppress, print, or log files in which annotators disagree. Possible values are",
"idxs for j in mask] v[idxs] = i return v def summary(results: np.array,",
"(kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\"",
"np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs): denom =",
"= len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) #",
"containing first annotators annotations --indir2, Directory containing second annotators annotations --annotation_conf, The brat",
"= [\"The cats sat on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent",
"np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange:",
"in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\"",
"20 23 mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"]",
"the entity type of the annotation at that character position, with 0 indicating",
"[] for docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def",
"agreed. # Equivalent to accuracy. p_o = np.sum(v1 == v2) / denom if",
"def test(): \"\"\" A small example to test ira(). \"\"\" docs = [\"The",
"Equality does not consider the annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN):",
"assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\": args = parse_args()",
"to the annotation.conf file. param docdir: Directory containing the .txt files which were",
"== other.text]) else: return False def parse_args(): def usage(): return \"\"\"ira.py [--help, Show",
"False \"\"\" def __init__(self, num: str, label: str, start: int, end: int, text:",
"the first and second annotators .ann files, respectively. param ann_conf: Path to the",
"= [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20",
"= False return args def main(indir1: str, indir2: str, ann_conf: str, docdir: str",
"False def parse_args(): def usage(): return \"\"\"ira.py [--help, Show this help message and",
"on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20",
"# noqa def __eq__(self, other) -> bool: \"\"\" Overrides the default implementation Two",
"ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1) anns2 =",
"[os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in",
"args def main(indir1: str, indir2: str, ann_conf: str, docdir: str = None, disagreements:",
"List of first annotators annotations, output of read_anns(). param anns2: List of second",
"= len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for i",
"and exit] [--test, Test the ira function] [--docdir, Directory containing the documents that",
"import numpy as np from glob import glob from typing import List, Set,",
"== k) * np.sum(v2 == k) for k in range(len(labels)+1)]) if p_e ==",
"= (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 == k) for k in",
"How disagreements are logged. Possible values are \"suppress\", \"print\" and \"log\". If \"suppress\",",
"len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents and annotations.\") # Read the",
"Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa and percentage agreement",
"\"\"\" def __init__(self, num: str, label: str, start: int, end: int, text: str):",
"and second annotators .ann files, respectively. param ann_conf: Path to the annotation.conf file.",
"of times # rater j predicted label k, n_j_k: # p_e = (1/N^2)",
"# noqa def test(): \"\"\" A small example to test ira(). \"\"\" docs",
"for a sequence labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat",
"percentage agreement for each document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas",
"Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa and",
"= int(start) self.end = int(end) self.text = text @classmethod def from_string(cls, string: str):",
"and percentage agreement for a set of brat annotated files from two annotators",
"basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1) ==",
"varname: str = None): \"\"\" Prints summary statistics for the supplied results. param",
"are expected to # agree. For number of items N, labels k, and",
"read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity labels from annotation.conf. param ann_conf:",
"anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with disagreements.",
"int(end) self.text = text @classmethod def from_string(cls, string: str): (n, l, s, e,",
"List[str]) -> List[str]: \"\"\" Reads in the documents. param fnames: List of paths",
"number, e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label == other.label, self.start ==",
"List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\"",
"len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed",
"3s. param doc: Document that was annotated. param anns: Annotations for each document.",
"indicating no annotation. So an annotation task with 3 annotation types would have",
"If \"log\", writes file names to \"disagreements.log\" in the current working directory. \"\"\"",
"'\\n')) for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames:",
"param docdir: Directory containing the .txt files which were annotated. If None, uses",
"Whether to suppress, print, or log files in which annotators disagree. Possible values",
"else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the annotations. basenames",
"List of paths to .ann files to read. returns: List of annotations. \"\"\"",
"Reads the entity labels from annotation.conf. param ann_conf: Path to annotation.conf returns: set",
"Directory containing second annotators annotations --annotation_conf, The brat annotation.conf that was used for",
"string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label}",
"0 is reserved for no label idxs = [np.arange(a.start, a.end) for a in",
"ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\")",
"4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]]",
"Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the documents. param fnames:",
"{self.end}, {self.text}'>\" # noqa def __eq__(self, other) -> bool: \"\"\" Overrides the default",
"# Read the entity labels. labels = read_labels(ann_conf) # Compute inter rater agreement.",
"other.end, self.text == other.text]) else: return False def parse_args(): def usage(): return \"\"\"ira.py",
"k) for k in range(len(labels)+1)]) if p_e == 1: k = 0.0 else:",
"# Equivalent to accuracy. p_o = np.sum(v1 == v2) / denom if p_o",
"annotators annotations --indir2, Directory containing second annotators annotations --annotation_conf, The brat annotation.conf that",
"are \"suppress\", \"print\" and \"log\". If \"suppress\", do nothing. If \"print\", prints files",
"\"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels =",
"is not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results)",
"equal iff they have the same label, offset, and text. Equality does not",
"brat annotation.conf that was used for this annotation task --disagreements, Whether to suppress,",
"== k) for k in range(len(labels)+1)]) if p_e == 1: k = 0.0",
"text. Equality does not consider the annotation number, e.g. T1 \"\"\" if isinstance(other,",
"is True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels:",
"anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2):",
"Agreement\") # Do something with disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\")",
"BratANN(object): \"\"\" A brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>> b1",
"n_docs = len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for",
"label, offset, and text. Equality does not consider the annotation number, e.g. T1",
"working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at the token level for",
"[\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0],",
"= [] for i in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i],",
"np.sum([np.sum(v1 == k) * np.sum(v2 == k) for k in range(len(labels)+1)]) if p_e",
"= [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn",
"Kappa and percentage agreement for each document. \"\"\" n_docs = len(docs) p_os =",
"0.0 else: k = (p_o - p_e) / (1 - p_e) p_os[i] =",
"rmax = np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f},",
"'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann",
"List[List[BratANN]]: \"\"\" Reads all .ann files and converts their annotations to BratANN objects.",
"were annotated. If not specified, looks in indir1.] --indir1, Directory containing first annotators",
"values are \"suppress\", \"print\" and \"log\". If \"suppress\", do nothing. If \"print\", prints",
"disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads",
"for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1",
"label: str, start: int, end: int, text: str): self.num = num self.label =",
"this task. returns: Vector of character level annotations. \"\"\" v = np.zeros(len(doc)) #",
"ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for",
"that character position, with 0 indicating no annotation. So an annotation task with",
"{self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other) -> bool: \"\"\" Overrides",
"p_e = (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 == k) for k",
"elif copy is True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2:",
"\"\"\" desc = \"\"\"Computes Cohen's kappa at the token level for a sequence",
"Do something with disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\") for (idx,",
"something with disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\") for (idx, p_o)",
"print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd =",
"num: str, label: str, start: int, end: int, text: str): self.num = num",
"= [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s)",
"read_docs(doc_fnames) # Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames]",
"is \"suppress\". If \"log\", writes file names to \"disagreements.log\" in the current working",
"f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames]",
"= BratANN.from_string(ann) >>> b1 == b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1,",
"basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn",
"annotation types would have a vector of 0s, 1s, 2s, and 3s. param",
"\"\"\" param indir{1,2}: Input directories containing the first and second annotators .ann files,",
"corresponds to the entity type of the annotation at that character position, with",
"is reserved for no label idxs = [np.arange(a.start, a.end) for a in anns",
"names to \"disagreements.log\" in the current working directory. \"\"\" desc = \"\"\"Computes Cohen's",
"= np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f}",
"noqa def test(): \"\"\" A small example to test ira(). \"\"\" docs =",
"-> List[List[BratANN]]: \"\"\" Reads all .ann files and converts their annotations to BratANN",
"(e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat annotation. >>> ann = \"T1\\tent",
"if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the two",
"= i return v def summary(results: np.array, varname: str = None): \"\"\" Prints",
"Prints summary statistics for the supplied results. param results: Numeric array of results",
"Annotations for each document. param labels: Set of entity labels for this task.",
"is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True)",
"return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num},",
"read_docs(). param anns1: List of first annotators annotations, output of read_anns(). param anns2:",
"/ denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often",
"read_labels(). returns: Kappa and percentage agreement for each document. \"\"\" n_docs = len(docs)",
"3 annotation types would have a vector of 0s, 1s, 2s, and 3s.",
"param labels: Set of entity labels for this task. returns: Vector of character",
"parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None)",
"List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's",
"read_anns(). param anns2: List of second annotators annotations, output of read_anns(). param labels:",
"f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not",
"doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the annotations. basenames =",
"kappa at the token level for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc,",
"for (i, lab) in enumerate(labels): i += 1 # 0 is reserved for",
"files in which annotators disagree. Possible values are \"suppress\", \"print\", \"log\". Default is",
"supplied results. param results: Numeric array of results (e.g. kappas). param varname: (Optional)",
"test(): \"\"\" A small example to test ira(). \"\"\" docs = [\"The cats",
"set of entity labels. \"\"\" labels = set() with open(ann_conf, 'r') as infile:",
"typing import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa",
"containing the first and second annotators .ann files, respectively. param ann_conf: Path to",
"items N, labels k, and the number of times # rater j predicted",
"for this task. returns: Vector of character level annotations. \"\"\" v = np.zeros(len(doc))",
"the document into an integer vector. The value of each element corresponds to",
"annotated. If not specified, looks in indir1.] --indir1, Directory containing first annotators annotations",
"annotation. So an annotation task with 3 annotation types would have a vector",
"labels. labels = read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement, disagree_idxs =",
"default implementation Two BratANNs are considering equal iff they have the same label,",
"the documents. param fnames: List of paths to .txt files to read. returns:",
"= False elif copy is True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1:",
"param fnames: List of paths to .ann files to read. returns: List of",
"documents and annotations.\") # Read the entity labels. labels = read_labels(ann_conf) # Compute",
"# p_e = (1/N^2) * sum_k (n_1_k * n_2_k) p_e = (1/denom**2) *",
"bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in",
"T1 \"\"\" if isinstance(other, BratANN): return all([self.label == other.label, self.start == other.start, self.end",
"as np from glob import glob from typing import List, Set, Tuple \"\"\"",
"\"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in",
"1 # 0 is reserved for no label idxs = [np.arange(a.start, a.end) for",
"def __eq__(self, other) -> bool: \"\"\" Overrides the default implementation Two BratANNs are",
"Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 =",
"label k, n_j_k: # p_e = (1/N^2) * sum_k (n_1_k * n_2_k) p_e",
"second annotators annotations, output of read_anns(). param labels: Set of labels annotated, output",
"\"\"\" if isinstance(other, BratANN): return all([self.label == other.label, self.start == other.start, self.end ==",
"Expected agreement: How often the two annotators are expected to # agree. For",
"np.array, varname: str = None): \"\"\" Prints summary statistics for the supplied results.",
"bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 =",
"expected to # agree. For number of items N, labels k, and the",
"\"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2",
"annotators for a sequence labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A",
"current working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at the token level",
"1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 == b2 True >>>",
"annotated, output of read_labels(). returns: Kappa and percentage agreement for each document. \"\"\"",
"np.sum(v1 == v2) / denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected",
"List of paths to .txt files to read. returns: List of input documents.",
"and percentage agreement for each document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs)",
"int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def",
"type of the annotation at that character position, with 0 indicating no annotation.",
"in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1)",
"__name__ == \"__main__\": args = parse_args() if args.test is True: import doctest doctest.testmod()",
"np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test():",
"line.strip() == \"[relations]\": copy = False elif copy is True: labels.add(line.strip()) return labels",
"param labels: Set of labels annotated, output of read_labels(). returns: Kappa and percentage",
"= \"\"\"Computes Cohen's kappa at the token level for a sequence labeling task.\"\"\"",
"e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label == other.label, self.start == other.start,",
"that disagree will be written to \"disagreements.log\" in the current working directory. \"\"\"",
"(1/N^2) * sum_k (n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k)",
"True elif line.strip() == \"[relations]\": copy = False elif copy is True: labels.add(line.strip())",
"disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the",
"b1 == b3 False \"\"\" def __init__(self, num: str, label: str, start: int,",
"k, and the number of times # rater j predicted label k, n_j_k:",
"of items N, labels k, and the number of times # rater j",
"bn in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) ==",
"cls(n, l, int(s), int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\"",
"A brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\",",
"Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n'))",
"= None): \"\"\" Prints summary statistics for the supplied results. param results: Numeric",
"* np.sum(v2 == k) for k in range(len(labels)+1)]) if p_e == 1: k",
"disagreements: How disagreements are logged. Possible values are \"suppress\", \"print\" and \"log\". If",
"0s, 1s, 2s, and 3s. param doc: Document that was annotated. param anns:",
"return cls(n, l, int(s), int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start}",
"= parser.parse_known_args() if args.test is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str,",
"def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files and converts their",
"if a.label == lab] idxs = [j for mask in idxs for j",
"of each element corresponds to the entity type of the annotation at that",
"have a vector of 0s, 1s, 2s, and 3s. param doc: Document that",
"for this annotation task --disagreements, Whether to suppress, print, or log files in",
"entity labels. labels = read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement, disagree_idxs",
"numpy as np from glob import glob from typing import List, Set, Tuple",
"of brat annotated files from two annotators for a sequence labeling task (e.g.",
"== len(anns2): raise ValueError(\"Different numbers of documents and annotations.\") # Read the entity",
"in mask] v[idxs] = i return v def summary(results: np.array, varname: str =",
"in anns if a.label == lab] idxs = [j for mask in idxs",
"in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 =",
"files to read. returns: List of annotations. \"\"\" all_anns = [] for annfile",
"percentage agreement between two annotators. param docs: List of documents, output of read_docs().",
"Equivalent to accuracy. p_o = np.sum(v1 == v2) / denom if p_o !=",
"\"disagreements.log\" in the current working directory. \"\"\" # Read in the documents. if",
"disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All",
"set() with open(ann_conf, 'r') as infile: copy = False for line in infile:",
"in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1)",
"the current working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at the token",
"np from glob import glob from typing import List, Set, Tuple \"\"\" Author:",
"\"log\". Default is \"suppress\". If \"log\", writes file names to \"disagreements.log\" in the",
"= (p_o - p_e) / (1 - p_e) p_os[i] = p_o kappas[i] =",
"being summarized. \"\"\" if varname is not None: print(varname) if len(results) == 1:",
"ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something",
"for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"]",
"labels: Set of entity labels for this task. returns: Vector of character level",
"str, label: str, start: int, end: int, text: str): self.num = num self.label",
"in the documents. param fnames: List of paths to .txt files to read.",
"kappa and percentage agreement for a set of brat annotated files from two",
"that were annotated. If not specified, looks in indir1.] --indir1, Directory containing first",
"assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\":",
"would have a vector of 0s, 1s, 2s, and 3s. param doc: Document",
"return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array:",
"if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs",
"the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\")",
"else: rmean = np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd = np.std(results)",
"len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents and annotations.\") #",
"for line in infile: # Skip blank lines and comments. if not line.strip()",
"of first annotators annotations, output of read_anns(). param anns2: List of second annotators",
"all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files",
"docs = read_docs(doc_fnames) # Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn",
"second annotators .ann files, respectively. param ann_conf: Path to the annotation.conf file. param",
"= [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for s",
"1s, 2s, and 3s. param doc: Document that was annotated. param anns: Annotations",
"# For each character for (i, lab) in enumerate(labels): i += 1 #",
"i return v def summary(results: np.array, varname: str = None): \"\"\" Prints summary",
"and converts their annotations to BratANN objects. param fnames: List of paths to",
"the annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label == other.label,",
"documents. if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\")",
"documents. param fnames: List of paths to .txt files to read. returns: List",
"indir1. param disagreements: How disagreements are logged. Possible values are \"suppress\", \"print\" and",
"each element corresponds to the entity type of the annotation at that character",
"- p_e) / (1 - p_e) p_os[i] = p_o kappas[i] = k return",
"{self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start},",
"-> np.array: \"\"\" Converts the document into an integer vector. The value of",
"the annotation at that character position, with 0 indicating no annotation. So an",
"p_e = (1/N^2) * sum_k (n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1",
"args, remainder = parser.parse_known_args() if args.test is True: return args parser = argparse.ArgumentParser(usage=usage())",
"not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents and annotations.\")",
"== \"__main__\": args = parse_args() if args.test is True: import doctest doctest.testmod() test()",
"'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs: bn =",
"for a in anns if a.label == lab] idxs = [j for mask",
"they have the same label, offset, and text. Equality does not consider the",
"specified, looks in indir1.] --indir1, Directory containing first annotators annotations --indir2, Directory containing",
"of results (e.g. kappas). param varname: (Optional) Name of the variable being summarized.",
"have the same label, offset, and text. Equality does not consider the annotation",
"files, respectively. param ann_conf: Path to the annotation.conf file. param docdir: Directory containing",
"Name of the variable being summarized. \"\"\" if varname is not None: print(varname)",
"return v def summary(results: np.array, varname: str = None): \"\"\" Prints summary statistics",
"= num self.label = label self.start = int(start) self.end = int(end) self.text =",
"str): (n, l, s, e, t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e),",
"annotations, output of read_anns(). param labels: Set of labels annotated, output of read_labels().",
"!= 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the two annotators are",
"disagreements are logged. Possible values are \"suppress\", \"print\" and \"log\". If \"suppress\", do",
"(idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) ->",
"noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" #",
"message and exit] [--test, Test the ira function] [--docdir, Directory containing the documents",
"entity type of the annotation at that character position, with 0 indicating no",
"int(s), int(e), t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa",
"class BratANN(object): \"\"\" A brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>>",
"if args.test is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\",",
"from annotation.conf. param ann_conf: Path to annotation.conf returns: set of entity labels. \"\"\"",
"BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 == b2",
"\"\"\" Reads all .ann files and converts their annotations to BratANN objects. param",
"Numeric array of results (e.g. kappas). param varname: (Optional) Name of the variable",
"== other.start, self.end == other.end, self.text == other.text]) else: return False def parse_args():",
"param ann_conf: Path to the annotation.conf file. param docdir: Directory containing the .txt",
"p_e) p_os[i] = p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po) def label_vector(doc:",
"param anns1: List of first annotators annotations, output of read_anns(). param anns2: List",
"\"\"\" A brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\" >>> b1 =",
"os import argparse import datetime import numpy as np from glob import glob",
"returns: List of annotations. \"\"\" all_anns = [] for annfile in fnames: anns",
"Converts the document into an integer vector. The value of each element corresponds",
"a set of brat annotated files from two annotators for a sequence labeling",
">>> b2 = BratANN.from_string(ann) >>> b1 == b2 True >>> b3 = BratANN(\"T3\",",
"no label idxs = [np.arange(a.start, a.end) for a in anns if a.label ==",
"and percentage agreement between two annotators. param docs: List of documents, output of",
"If \"suppress\", do nothing. If \"print\", prints files that disagree to the console.",
"label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the document into",
"reserved for no label idxs = [np.arange(a.start, a.end) for a in anns if",
"List of second annotators annotations, output of read_anns(). param labels: Set of labels",
"kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage",
"directory. \"\"\" # Read in the documents. if docdir is not None: doc_fnames",
"(Optional) Name of the variable being summarized. \"\"\" if varname is not None:",
"no annotation. So an annotation task with 3 annotation types would have a",
"consider the annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label ==",
"kappas, agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826,",
"== other.label, self.start == other.start, self.end == other.end, self.text == other.text]) else: return",
"= np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs): denom = len(docs[i]) v1",
"that was annotated. param anns: Annotations for each document. param labels: Set of",
"/ (1 - p_e) p_os[i] = p_o kappas[i] = k return (kappas, p_os,",
"p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]:",
"fnames: List of paths to .txt files to read. returns: List of input",
"p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs):",
"task. returns: Vector of character level annotations. \"\"\" v = np.zeros(len(doc)) # For",
"annotations. \"\"\" all_anns = [] for annfile in fnames: anns = [BratANN.from_string(a.strip()) for",
"rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\")",
"None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax =",
"rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\"",
"= None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input directories containing the",
"\"\"\" all_anns = [] for annfile in fnames: anns = [BratANN.from_string(a.strip()) for a",
"= parse_args() if args.test is True: import doctest doctest.testmod() test() else: main(args.indir1, args.indir2,",
"\"suppress\". If \"log\", writes file names to \"disagreements.log\" in the current working directory.",
"for mask in idxs for j in mask] v[idxs] = i return v",
"= [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2)",
"for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2",
"disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") #",
"= BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 ==",
"character-level Cohen's kappa and percentage agreement for a set of brat annotated files",
"of documents, output of read_docs(). param anns1: List of first annotators annotations, output",
"infile: copy = False for line in infile: # Skip blank lines and",
"task --disagreements, Whether to suppress, print, or log files in which annotators disagree.",
"def usage(): return \"\"\"ira.py [--help, Show this help message and exit] [--test, Test",
"of read_labels(). returns: Kappa and percentage agreement for each document. \"\"\" n_docs =",
"-> Set[str]: \"\"\" Reads the entity labels from annotation.conf. param ann_conf: Path to",
"annotation task --disagreements, Whether to suppress, print, or log files in which annotators",
"disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w')",
"for k in range(len(labels)+1)]) if p_e == 1: k = 0.0 else: k",
"\"\"\" A small example to test ira(). \"\"\" docs = [\"The cats sat",
"in enumerate(labels): i += 1 # 0 is reserved for no label idxs",
"None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input directories containing the first",
"with disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\") for (idx, p_o) in",
"str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return f\"<ira.BratANN",
"labels. \"\"\" labels = set() with open(ann_conf, 'r') as infile: copy = False",
"-> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa and percentage",
"param anns: Annotations for each document. param labels: Set of entity labels for",
"function.\"\"\") args, remainder = parser.parse_known_args() if args.test is True: return args parser =",
"For each character for (i, lab) in enumerate(labels): i += 1 # 0",
"False for line in infile: # Skip blank lines and comments. if not",
"def summary(results: np.array, varname: str = None): \"\"\" Prints summary statistics for the",
"kappas). param varname: (Optional) Name of the variable being summarized. \"\"\" if varname",
"Overrides the default implementation Two BratANNs are considering equal iff they have the",
"# Skip blank lines and comments. if not line.strip() or line.strip().startswith('#'): continue if",
"read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different",
"containing the documents that were annotated. If not specified, looks in indir1.] --indir1,",
"\"\"\" class BratANN(object): \"\"\" A brat annotation. >>> ann = \"T1\\tent 1 4\\tcat\"",
"the current working directory. \"\"\" # Read in the documents. if docdir is",
"\"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with disagreements. if disagreements ==",
"annotators annotations, output of read_anns(). param anns2: List of second annotators annotations, output",
"labels: Set of labels annotated, output of read_labels(). returns: Kappa and percentage agreement",
"in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) ->",
"values are \"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\", writes file names",
"= int(end) self.text = text @classmethod def from_string(cls, string: str): (n, l, s,",
"return \"\"\"ira.py [--help, Show this help message and exit] [--test, Test the ira",
"= label_vector(docs[i], anns2[i], labels) # Observed agreement: How often the two annotators actually",
"= argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder =",
"\"\"\" Reads the entity labels from annotation.conf. param ann_conf: Path to annotation.conf returns:",
"mask] v[idxs] = i return v def summary(results: np.array, varname: str = None):",
"ann = \"T1\\tent 1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\")",
"int(start) self.end = int(end) self.text = text @classmethod def from_string(cls, string: str): (n,",
"anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent",
"* n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 == k)",
"\"\"\"Computes Cohen's kappa at the token level for a sequence labeling task.\"\"\" parser",
"in which annotators disagree. Possible values are \"suppress\", \"print\", \"log\". Default is \"suppress\".",
"outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the documents. param",
"12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 =",
"__repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def",
"{self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other) -> bool: \"\"\" Overrides the",
"were annotated. If None, uses indir1. param disagreements: How disagreements are logged. Possible",
"annotators are expected to # agree. For number of items N, labels k,",
"= (1/N^2) * sum_k (n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 ==",
"end: int, text: str): self.num = num self.label = label self.start = int(start)",
"summary(results: np.array, varname: str = None): \"\"\" Prints summary statistics for the supplied",
"main(indir1: str, indir2: str, ann_conf: str, docdir: str = None, disagreements: str =",
"of second annotators annotations, output of read_anns(). param labels: Set of labels annotated,",
"read. returns: List of annotations. \"\"\" all_anns = [] for annfile in fnames:",
"atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\": args = parse_args() if args.test",
"def __init__(self, num: str, label: str, start: int, end: int, text: str): self.num",
"open(ann_conf, 'r') as infile: copy = False for line in infile: # Skip",
"required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args",
"the same label, offset, and text. Equality does not consider the annotation number,",
"-> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return",
"= [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03))",
"param indir{1,2}: Input directories containing the first and second annotators .ann files, respectively.",
"comments. if not line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy =",
"Computes Cohen's kappa and percentage agreement between two annotators. param docs: List of",
"idxs = [j for mask in idxs for j in mask] v[idxs] =",
"None, uses indir1. param disagreements: How disagreements are logged. Possible values are \"suppress\",",
"fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]:",
"parser.parse_args(remainder) args.test = False return args def main(indir1: str, indir2: str, ann_conf: str,",
"7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels",
"disagree will be written to \"disagreements.log\" in the current working directory. \"\"\" #",
"param fnames: List of paths to .txt files to read. returns: List of",
"(p_o - p_e) / (1 - p_e) p_os[i] = p_o kappas[i] = k",
"does not consider the annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN): return",
"\"suppress\", do nothing. If \"print\", prints files that disagree to the console. If",
"if disagreements == \"print\": print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs: bn",
"= string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def __str__(self) -> str: return",
"containing the .txt files which were annotated. If None, uses indir1. param disagreements:",
"__init__(self, num: str, label: str, start: int, end: int, text: str): self.num =",
"times # rater j predicted label k, n_j_k: # p_e = (1/N^2) *",
"np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small",
"\"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage agreement for a",
"Path to annotation.conf returns: set of entity labels. \"\"\" labels = set() with",
"= np.zeros(len(doc)) # For each character for (i, lab) in enumerate(labels): i +=",
"annotations. \"\"\" v = np.zeros(len(doc)) # For each character for (i, lab) in",
"the annotation.conf file. param docdir: Directory containing the .txt files which were annotated.",
"\"\"\" Reads in the documents. param fnames: List of paths to .txt files",
"self.num = num self.label = label self.start = int(start) self.end = int(end) self.text",
"to accuracy. p_o = np.sum(v1 == v2) / denom if p_o != 1.0:",
"Test the ira function] [--docdir, Directory containing the documents that were annotated. If",
"ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 =",
"# Read in the documents. if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\")",
"1 4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 =",
"all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity labels from annotation.conf.",
"varname is not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean =",
"# Do something with disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\") for",
"t) def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self)",
"the ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test is True: return args",
"[--docdir, Directory containing the documents that were annotated. If not specified, looks in",
"type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\",",
"ann_conf: str, docdir: str = None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}:",
"Reads all .ann files and converts their annotations to BratANN objects. param fnames:",
"[np.arange(a.start, a.end) for a in anns if a.label == lab] idxs = [j",
"all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files and converts",
"self.label = label self.start = int(start) self.end = int(end) self.text = text @classmethod",
"respectively. param ann_conf: Path to the annotation.conf file. param docdir: Directory containing the",
"else: return False def parse_args(): def usage(): return \"\"\"ira.py [--help, Show this help",
"paths to .txt files to read. returns: List of input documents. \"\"\" all_docs",
"doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\"",
"labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ ==",
"return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str,",
"directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at the token level for a",
"at that character position, with 0 indicating no annotation. So an annotation task",
"p_o = np.sum(v1 == v2) / denom if p_o != 1.0: disagree_idxs_po.append((i, p_o))",
"If None, uses indir1. param disagreements: How disagreements are logged. Possible values are",
"annotation.conf file. param docdir: Directory containing the .txt files which were annotated. If",
"blank lines and comments. if not line.strip() or line.strip().startswith('#'): continue if line.strip() ==",
"str, ann_conf: str, docdir: str = None, disagreements: str = \"suppress\"): \"\"\" param",
"in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1,",
"writes file names to \"disagreements.log\" in the current working directory. \"\"\" desc =",
"other.label, self.start == other.start, self.end == other.end, self.text == other.text]) else: return False",
"== 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results) rmin = np.min(results)",
"in the current working directory. \"\"\" # Read in the documents. if docdir",
"print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() +",
"labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) ->",
"documents, output of read_docs(). param anns1: List of first annotators annotations, output of",
"annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label == other.label, self.start",
"implementation Two BratANNs are considering equal iff they have the same label, offset,",
"annotation.conf that was used for this annotation task --disagreements, Whether to suppress, print,",
"k = (p_o - p_e) / (1 - p_e) p_os[i] = p_o kappas[i]",
"and 3s. param doc: Document that was annotated. param anns: Annotations for each",
"ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for",
"\"\"\" docs = [\"The cats sat on the mat\"] ann_strs1 = [\"T1\\tent 4",
"p_os[i] = p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str],",
"disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input directories containing the first and",
"= [[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements =",
"at the token level for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage())",
"doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\")",
"Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage agreement",
"copy = False for line in infile: # Skip blank lines and comments.",
"lab] idxs = [j for mask in idxs for j in mask] v[idxs]",
"help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test is True: return",
"required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False return args",
"np.sum(v2 == k) for k in range(len(labels)+1)]) if p_e == 1: k =",
"in infile: # Skip blank lines and comments. if not line.strip() or line.strip().startswith('#'):",
"ValueError(\"Different numbers of documents and annotations.\") # Read the entity labels. labels =",
"\"print\" and \"log\". If \"suppress\", do nothing. If \"print\", prints files that disagree",
"\"suppress\"): \"\"\" param indir{1,2}: Input directories containing the first and second annotators .ann",
"in idxs for j in mask] v[idxs] = i return v def summary(results:",
"anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__",
"labels) v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement: How often the two",
"p_e == 1: k = 0.0 else: k = (p_o - p_e) /",
"set of brat annotated files from two annotators for a sequence labeling task",
"ira function] [--docdir, Directory containing the documents that were annotated. If not specified,",
"annotation.conf. param ann_conf: Path to annotation.conf returns: set of entity labels. \"\"\" labels",
"= [] for annfile in fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile,",
"List[str]: \"\"\" Reads in the documents. param fnames: List of paths to .txt",
"uses indir1. param disagreements: How disagreements are logged. Possible values are \"suppress\", \"print\"",
"be written to \"disagreements.log\" in the current working directory. \"\"\" # Read in",
"= label self.start = int(start) self.end = int(end) self.text = text @classmethod def",
"p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]],",
"param anns2: List of second annotators annotations, output of read_anns(). param labels: Set",
"\"print\": print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}:",
"files that disagree to the console. If \"log\", files that disagree will be",
"are considering equal iff they have the same label, offset, and text. Equality",
"two annotators for a sequence labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\"",
"number of times # rater j predicted label k, n_j_k: # p_e =",
"of input documents. \"\"\" all_docs = [] for docfile in fnames: doc =",
"read. returns: List of input documents. \"\"\" all_docs = [] for docfile in",
"str, start: int, end: int, text: str): self.num = num self.label = label",
"for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test",
"\"log\"]) args = parser.parse_args(remainder) args.test = False return args def main(indir1: str, indir2:",
"in the documents. if docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames",
"[os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if",
"sat on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent",
"copy is True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]],",
"directories containing the first and second annotators .ann files, respectively. param ann_conf: Path",
"and annotations.\") # Read the entity labels. labels = read_labels(ann_conf) # Compute inter",
"parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False,",
"self.text = text @classmethod def from_string(cls, string: str): (n, l, s, e, t)",
"disagree_idxs_po.append((i, p_o)) # Expected agreement: How often the two annotators are expected to",
"looks in indir1.] --indir1, Directory containing first annotators annotations --indir2, Directory containing second",
"# 0 is reserved for no label idxs = [np.arange(a.start, a.end) for a",
"print(\"All tests passed.\") if __name__ == \"__main__\": args = parse_args() if args.test is",
"anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa",
"read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents",
"v = np.zeros(len(doc)) # For each character for (i, lab) in enumerate(labels): i",
"labels = set() with open(ann_conf, 'r') as infile: copy = False for line",
"summary(agreement, \"Percentage Agreement\") # Do something with disagreements. if disagreements == \"print\": print(\"===",
"if disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for",
"predicted label k, n_j_k: # p_e = (1/N^2) * sum_k (n_1_k * n_2_k)",
"default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test is True:",
".txt files which were annotated. If None, uses indir1. param disagreements: How disagreements",
"open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all",
"summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with disagreements. if disagreements",
"to BratANN objects. param fnames: List of paths to .ann files to read.",
"annotations.\") # Read the entity labels. labels = read_labels(ann_conf) # Compute inter rater",
"open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the",
"p_e) / (1 - p_e) p_os[i] = p_o kappas[i] = k return (kappas,",
"= p_o kappas[i] = k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns:",
"str): self.num = num self.label = label self.start = int(start) self.end = int(end)",
"Set[str]: \"\"\" Reads the entity labels from annotation.conf. param ann_conf: Path to annotation.conf",
"each character for (i, lab) in enumerate(labels): i += 1 # 0 is",
"= os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF:",
"def __str__(self) -> str: return f\"{self.num}\\t{self.label} {self.start} {self.end}\\t{self.text}\" # noqa def __repr__(self) ->",
">>> b1 == b3 False \"\"\" def __init__(self, num: str, label: str, start:",
"an annotation task with 3 annotation types would have a vector of 0s,",
"--disagreements, Whether to suppress, print, or log files in which annotators disagree. Possible",
"output of read_labels(). returns: Kappa and percentage agreement for each document. \"\"\" n_docs",
"else: k = (p_o - p_e) / (1 - p_e) p_os[i] = p_o",
"labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat annotation. >>> ann",
"for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str])",
"print, or log files in which annotators disagree. Possible values are \"suppress\", \"print\",",
"all .ann files and converts their annotations to BratANN objects. param fnames: List",
"files and converts their annotations to BratANN objects. param fnames: List of paths",
"str, indir2: str, ann_conf: str, docdir: str = None, disagreements: str = \"suppress\"):",
"tests passed.\") if __name__ == \"__main__\": args = parse_args() if args.test is True:",
"BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1 == b3 False \"\"\" def",
"in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2, labels)",
"summary statistics for the supplied results. param results: Numeric array of results (e.g.",
"{self.end}\\t{self.text}\" # noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end},",
"int, text: str): self.num = num self.label = label self.start = int(start) self.end",
"\"__main__\": args = parse_args() if args.test is True: import doctest doctest.testmod() test() else:",
"of read_anns(). param anns2: List of second annotators annotations, output of read_anns(). param",
"np.array: \"\"\" Converts the document into an integer vector. The value of each",
"anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with",
"= read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1,",
"to \"disagreements.log\" in the current working directory. \"\"\" # Read in the documents.",
"\"\"\" if varname is not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else:",
"\"suppress\", \"print\" and \"log\". If \"suppress\", do nothing. If \"print\", prints files that",
"(1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2 == k) for k in range(len(labels)+1)])",
"help message and exit] [--test, Test the ira function] [--docdir, Directory containing the",
"usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args() if",
"will be written to \"disagreements.log\" in the current working directory. \"\"\" # Read",
"with 0 indicating no annotation. So an annotation task with 3 annotation types",
"[] for annfile in fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')]",
"20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent 4",
"= [j for mask in idxs for j in mask] v[idxs] = i",
"for a set of brat annotated files from two annotators for a sequence",
"docdir is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs =",
"task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args,",
"args.test is True: import doctest doctest.testmod() test() else: main(args.indir1, args.indir2, args.annotation_conf, docdir=args.docdir, disagreements=args.disagreements)",
"that disagree to the console. If \"log\", files that disagree will be written",
"labels k, and the number of times # rater j predicted label k,",
"for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements ==",
"4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 == b2 True >>> b3",
"a sequence labeling task (e.g. NER). \"\"\" class BratANN(object): \"\"\" A brat annotation.",
"= open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads",
"label idxs = [np.arange(a.start, a.end) for a in anns if a.label == lab]",
"== len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents and annotations.\") # Read",
"\"\"\" labels = set() with open(ann_conf, 'r') as infile: copy = False for",
"1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results) rmin = np.min(results) rstd",
"returns: Vector of character level annotations. \"\"\" v = np.zeros(len(doc)) # For each",
"output of read_docs(). param anns1: List of first annotators annotations, output of read_anns().",
"4\\tcat\" >>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann)",
"== \"[entities]\": copy = True elif line.strip() == \"[relations]\": copy = False elif",
"was annotated. param anns: Annotations for each document. param labels: Set of entity",
"\"\"\" Overrides the default implementation Two BratANNs are considering equal iff they have",
"in indir1.] --indir1, Directory containing first annotators annotations --indir2, Directory containing second annotators",
"BratANNs are considering equal iff they have the same label, offset, and text.",
"used for this annotation task --disagreements, Whether to suppress, print, or log files",
"== \"[relations]\": copy = False elif copy is True: labels.add(line.strip()) return labels def",
"False elif copy is True: labels.add(line.strip()) return labels def ira(docs: List[str], anns1: List[List[BratANN]],",
"kappa and percentage agreement between two annotators. param docs: List of documents, output",
"(<EMAIL>) Computes character-level Cohen's kappa and percentage agreement for a set of brat",
"anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf:",
"argparse import datetime import numpy as np from glob import glob from typing",
"glob from typing import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level",
"i += 1 # 0 is reserved for no label idxs = [np.arange(a.start,",
"all([self.label == other.label, self.start == other.start, self.end == other.end, self.text == other.text]) else:",
"all_anns = [] for annfile in fnames: anns = [BratANN.from_string(a.strip()) for a in",
"b1 == b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \")",
"labels from annotation.conf. param ann_conf: Path to annotation.conf returns: set of entity labels.",
"datetime import numpy as np from glob import glob from typing import List,",
"== \"print\": print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx])",
"def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int,",
"value of each element corresponds to the entity type of the annotation at",
"parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\",",
"agreement: How often the two annotators are expected to # agree. For number",
"= [np.arange(a.start, a.end) for a in anns if a.label == lab] idxs =",
"List of input documents. \"\"\" all_docs = [] for docfile in fnames: doc",
"How often the two annotators are expected to # agree. For number of",
"if isinstance(other, BratANN): return all([self.label == other.label, self.start == other.start, self.end == other.end,",
"k) * np.sum(v2 == k) for k in range(len(labels)+1)]) if p_e == 1:",
"annotation task with 3 annotation types would have a vector of 0s, 1s,",
"from two annotators for a sequence labeling task (e.g. NER). \"\"\" class BratANN(object):",
"Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage agreement for",
"ann_conf: Path to the annotation.conf file. param docdir: Directory containing the .txt files",
"[[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements = ira(docs,",
"of read_docs(). param anns1: List of first annotators annotations, output of read_anns(). param",
"len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for i in",
"disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx,",
"= parser.parse_args(remainder) args.test = False return args def main(indir1: str, indir2: str, ann_conf:",
"BratANN.from_string(ann) >>> b1 == b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5,",
"output of read_anns(). param anns2: List of second annotators annotations, output of read_anns().",
"this help message and exit] [--test, Test the ira function] [--docdir, Directory containing",
"annotators disagree. Possible values are \"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\",",
"mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1",
"from typing import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's",
"documents. \"\"\" all_docs = [] for docfile in fnames: doc = open(docfile, 'r').read()",
"for each document. param labels: Set of entity labels for this task. returns:",
"9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2",
"t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def __str__(self) -> str:",
"isinstance(other, BratANN): return all([self.label == other.label, self.start == other.start, self.end == other.end, self.text",
"annotations --indir2, Directory containing second annotators annotations --annotation_conf, The brat annotation.conf that was",
"\"\"\" v = np.zeros(len(doc)) # For each character for (i, lab) in enumerate(labels):",
"for the supplied results. param results: Numeric array of results (e.g. kappas). param",
"cats sat on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\",",
"for no label idxs = [np.arange(a.start, a.end) for a in anns if a.label",
"Directory containing the documents that were annotated. If not specified, looks in indir1.]",
"a in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\"",
"second annotators annotations --annotation_conf, The brat annotation.conf that was used for this annotation",
"str = None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input directories containing",
"-> List[str]: \"\"\" Reads in the documents. param fnames: List of paths to",
"# rater j predicted label k, n_j_k: # p_e = (1/N^2) * sum_k",
"List of documents, output of read_docs(). param anns1: List of first annotators annotations,",
"types would have a vector of 0s, 1s, 2s, and 3s. param doc:",
"labels = read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement, disagree_idxs = ira(docs,",
"= np.max(results) rmin = np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\")",
"\"\"\" all_docs = [] for docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc)",
"if not line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy = True",
"not line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy = True elif",
"annotations to BratANN objects. param fnames: List of paths to .ann files to",
"with 3 annotation types would have a vector of 0s, 1s, 2s, and",
"paths to .ann files to read. returns: List of annotations. \"\"\" all_anns =",
"s in ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2",
"noqa def __eq__(self, other) -> bool: \"\"\" Overrides the default implementation Two BratANNs",
"= os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the",
"ira(). \"\"\" docs = [\"The cats sat on the mat\"] ann_strs1 = [\"T1\\tent",
"between two annotators. param docs: List of documents, output of read_docs(). param anns1:",
"task with 3 annotation types would have a vector of 0s, 1s, 2s,",
"import os import argparse import datetime import numpy as np from glob import",
"\"print\", prints files that disagree to the console. If \"log\", files that disagree",
"not specified, looks in indir1.] --indir1, Directory containing first annotators annotations --indir2, Directory",
"So an annotation task with 3 annotation types would have a vector of",
"param varname: (Optional) Name of the variable being summarized. \"\"\" if varname is",
"List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: #",
"np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa and percentage agreement between",
"variable being summarized. \"\"\" if varname is not None: print(varname) if len(results) ==",
"BratANN): return all([self.label == other.label, self.start == other.start, self.end == other.end, self.text ==",
"str = \"suppress\"): \"\"\" param indir{1,2}: Input directories containing the first and second",
"[--help, Show this help message and exit] [--test, Test the ira function] [--docdir,",
"args = parser.parse_args(remainder) args.test = False return args def main(indir1: str, indir2: str,",
"parse_args() if args.test is True: import doctest doctest.testmod() test() else: main(args.indir1, args.indir2, args.annotation_conf,",
"disagreements == \"print\": print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs: bn =",
"files from two annotators for a sequence labeling task (e.g. NER). \"\"\" class",
"def from_string(cls, string: str): (n, l, s, e, t) = string.split(maxsplit=4) return cls(n,",
"to .ann files to read. returns: List of annotations. \"\"\" all_anns = []",
"= ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629, atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests",
"os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now()",
"sum_k (n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k) * np.sum(v2",
"for annfile in fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns)",
"\"\"\" Computes Cohen's kappa and percentage agreement between two annotators. param docs: List",
"varname: (Optional) Name of the variable being summarized. \"\"\" if varname is not",
"\"log\", files that disagree will be written to \"disagreements.log\" in the current working",
"token level for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\",",
"required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\",",
"fnames: List of paths to .ann files to read. returns: List of annotations.",
"for i in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2",
"= np.min(results) rstd = np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def",
"a in anns if a.label == lab] idxs = [j for mask in",
"--indir1, Directory containing first annotators annotations --indir2, Directory containing second annotators annotations --annotation_conf,",
".txt files to read. returns: List of input documents. \"\"\" all_docs = []",
"results. param results: Numeric array of results (e.g. kappas). param varname: (Optional) Name",
"start: int, end: int, text: str): self.num = num self.label = label self.start",
"suppress, print, or log files in which annotators disagree. Possible values are \"suppress\",",
"for each document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs)",
"not consider the annotation number, e.g. T1 \"\"\" if isinstance(other, BratANN): return all([self.label",
"List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the document into an",
"of annotations. \"\"\" all_anns = [] for annfile in fnames: anns = [BratANN.from_string(a.strip())",
"= 0.0 else: k = (p_o - p_e) / (1 - p_e) p_os[i]",
"5, \"cat \") >>> b1 == b3 False \"\"\" def __init__(self, num: str,",
"agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement,",
">>> b1 == b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat",
"self.end == other.end, self.text == other.text]) else: return False def parse_args(): def usage():",
"passed.\") if __name__ == \"__main__\": args = parse_args() if args.test is True: import",
"line in infile: # Skip blank lines and comments. if not line.strip() or",
"N, labels k, and the number of times # rater j predicted label",
"kappas[i] = k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels:",
"mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"] kappas, agreements,",
"n_j_k: # p_e = (1/N^2) * sum_k (n_1_k * n_2_k) p_e = (1/denom**2)",
"str) -> Set[str]: \"\"\" Reads the entity labels from annotation.conf. param ann_conf: Path",
"if __name__ == \"__main__\": args = parse_args() if args.test is True: import doctest",
"parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\") args, remainder = parser.parse_known_args() if args.test",
"__eq__(self, other) -> bool: \"\"\" Overrides the default implementation Two BratANNs are considering",
"[] for i in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels)",
"'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity",
"b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1",
"character for (i, lab) in enumerate(labels): i += 1 # 0 is reserved",
"= True elif line.strip() == \"[relations]\": copy = False elif copy is True:",
"= glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the",
"labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes Cohen's kappa",
"as infile: copy = False for line in infile: # Skip blank lines",
"param doc: Document that was annotated. param anns: Annotations for each document. param",
"type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False return",
"agree. For number of items N, labels k, and the number of times",
"denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 = label_vector(docs[i], anns2[i], labels)",
"annotation at that character position, with 0 indicating no annotation. So an annotation",
"annotated files from two annotators for a sequence labeling task (e.g. NER). \"\"\"",
"desc = \"\"\"Computes Cohen's kappa at the token level for a sequence labeling",
"annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for",
"of documents and annotations.\") # Read the entity labels. labels = read_labels(ann_conf) #",
"read_anns(). param labels: Set of labels annotated, output of read_labels(). returns: Kappa and",
"= np.std(results) print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A",
"agreement, disagree_idxs = ira(docs, anns1, anns2, labels) summary(kappa, \"Cohen's Kappa\") summary(agreement, \"Percentage Agreement\")",
"or log files in which annotators disagree. Possible values are \"suppress\", \"print\", \"log\".",
"document. param labels: Set of entity labels for this task. returns: Vector of",
"print(f\"\"\"Mean: {rmean:.3f} +/-{rstd:.3f}\\nRange: ({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small example",
"== b2 True >>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>>",
"docdir: Directory containing the .txt files which were annotated. If None, uses indir1.",
"return all_anns def read_labels(ann_conf: str) -> Set[str]: \"\"\" Reads the entity labels from",
"[BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) ->",
"position, with 0 indicating no annotation. So an annotation task with 3 annotation",
"written to \"disagreements.log\" in the current working directory. \"\"\" # Read in the",
"of entity labels for this task. returns: Vector of character level annotations. \"\"\"",
"sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira",
"objects. param fnames: List of paths to .ann files to read. returns: List",
"anns: Annotations for each document. param labels: Set of entity labels for this",
"4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s",
"\") >>> b1 == b3 False \"\"\" def __init__(self, num: str, label: str,",
"do nothing. If \"print\", prints files that disagree to the console. If \"log\",",
">>> b3 = BratANN(\"T3\", \"ent\", 1, 5, \"cat \") >>> b1 == b3",
"first annotators annotations, output of read_anns(). param anns2: List of second annotators annotations,",
"parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args =",
"<NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage agreement for a set of",
"labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the ira function.\"\"\")",
"read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the documents. param fnames: List of",
"each document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po",
"23 mat\"] anns2 = [[BratANN.from_string(s) for s in ann_strs2]] labels = [\"ent\"] kappas,",
"import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and",
"containing second annotators annotations --annotation_conf, The brat annotation.conf that was used for this",
"in the current working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa at the",
"def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the document",
"from glob import glob from typing import List, Set, Tuple \"\"\" Author: <NAME>",
"# Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1",
"parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\",",
"if not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers of documents and",
"+= 1 # 0 is reserved for no label idxs = [np.arange(a.start, a.end)",
"8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in",
"= glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0]",
"file names to \"disagreements.log\" in the current working directory. \"\"\" desc = \"\"\"Computes",
"NER). \"\"\" class BratANN(object): \"\"\" A brat annotation. >>> ann = \"T1\\tent 1",
"remainder = parser.parse_known_args() if args.test is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\",",
"disagreements. if disagreements == \"print\": print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs:",
"the variable being summarized. \"\"\" if varname is not None: print(varname) if len(results)",
"the console. If \"log\", files that disagree will be written to \"disagreements.log\" in",
"Document that was annotated. param anns: Annotations for each document. param labels: Set",
"argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True) parser.add_argument(\"--docdir\", type=str, required=False,",
"ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]:",
"[\"The cats sat on the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9",
"len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results) rmin =",
"statistics for the supplied results. param results: Numeric array of results (e.g. kappas).",
"Vector of character level annotations. \"\"\" v = np.zeros(len(doc)) # For each character",
"the mat\"] ann_strs1 = [\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"]",
"atol=1e-03)) assert(np.isclose(agreements[0], 0.826, atol=1e-03)) print(\"All tests passed.\") if __name__ == \"__main__\": args =",
"often the two annotators are expected to # agree. For number of items",
"labels: Set[str]) -> np.array: \"\"\" Converts the document into an integer vector. The",
"element corresponds to the entity type of the annotation at that character position,",
"param docs: List of documents, output of read_docs(). param anns1: List of first",
"disagree_idxs_po = [] for i in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i],",
"import argparse import datetime import numpy as np from glob import glob from",
"outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}:",
"Set of entity labels for this task. returns: Vector of character level annotations.",
"to read. returns: List of annotations. \"\"\" all_anns = [] for annfile in",
"parser.parse_known_args() if args.test is True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True)",
"Two BratANNs are considering equal iff they have the same label, offset, and",
"enumerate(labels): i += 1 # 0 is reserved for no label idxs =",
"same label, offset, and text. Equality does not consider the annotation number, e.g.",
"\"Percentage Agreement\") # Do something with disagreements. if disagreements == \"print\": print(\"=== Disagreements",
"the two annotators are expected to # agree. For number of items N,",
"glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in the annotations. basenames = [os.path.splitext(os.path.basename(fn))[0] for",
"({rmin:.3f}, {rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small example to test ira().",
"= [] for docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs",
"the entity labels. labels = read_labels(ann_conf) # Compute inter rater agreement. kappa, agreement,",
"each document. param labels: Set of entity labels for this task. returns: Vector",
"other) -> bool: \"\"\" Overrides the default implementation Two BratANNs are considering equal",
"True: return args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\",",
"of read_anns(). param labels: Set of labels annotated, output of read_labels(). returns: Kappa",
"entity labels. \"\"\" labels = set() with open(ann_conf, 'r') as infile: copy =",
"the two annotators actually agreed. # Equivalent to accuracy. p_o = np.sum(v1 ==",
"text @classmethod def from_string(cls, string: str): (n, l, s, e, t) = string.split(maxsplit=4)",
"--annotation_conf, The brat annotation.conf that was used for this annotation task --disagreements, Whether",
"v def summary(results: np.array, varname: str = None): \"\"\" Prints summary statistics for",
"* sum_k (n_1_k * n_2_k) p_e = (1/denom**2) * np.sum([np.sum(v1 == k) *",
"iff they have the same label, offset, and text. Equality does not consider",
"with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs:",
"\"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 == b2 True",
"\"ent\", 1, 5, \"cat \") >>> b1 == b3 False \"\"\" def __init__(self,",
"import glob from typing import List, Set, Tuple \"\"\" Author: <NAME> (<EMAIL>) Computes",
"of 0s, 1s, 2s, and 3s. param doc: Document that was annotated. param",
"anns2: List of second annotators annotations, output of read_anns(). param labels: Set of",
"j in mask] v[idxs] = i return v def summary(results: np.array, varname: str",
"The brat annotation.conf that was used for this annotation task --disagreements, Whether to",
"to read. returns: List of input documents. \"\"\" all_docs = [] for docfile",
"parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test = False",
"if line.strip() == \"[entities]\": copy = True elif line.strip() == \"[relations]\": copy =",
"accuracy. p_o = np.sum(v1 == v2) / denom if p_o != 1.0: disagree_idxs_po.append((i,",
"Disagreements ===\") for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if",
"print(\"=== Disagreements ===\") for (idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\")",
"is not None: doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames)",
"working directory. \"\"\" # Read in the documents. if docdir is not None:",
"level annotations. \"\"\" v = np.zeros(len(doc)) # For each character for (i, lab)",
"fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in basenames] ann_fnames2 =",
"-> bool: \"\"\" Overrides the default implementation Two BratANNs are considering equal iff",
"v2) / denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement: How",
"ann_strs2]] labels = [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0],",
"and the number of times # rater j predicted label k, n_j_k: #",
"a.label == lab] idxs = [j for mask in idxs for j in",
"are \"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\", writes file names to",
"str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other)",
"annotators .ann files, respectively. param ann_conf: Path to the annotation.conf file. param docdir:",
"returns: Kappa and percentage agreement for each document. \"\"\" n_docs = len(docs) p_os",
"p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts",
"fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return all_anns def",
"= \"suppress\"): \"\"\" param indir{1,2}: Input directories containing the first and second annotators",
"0 indicating no annotation. So an annotation task with 3 annotation types would",
"# Expected agreement: How often the two annotators are expected to # agree.",
"--indir2, Directory containing second annotators annotations --annotation_conf, The brat annotation.conf that was used",
"read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files and converts their annotations",
"doc_fnames = glob(f\"{docdir}/*.txt\") else: doc_fnames = glob(f\"{indir1}/*.txt\") docs = read_docs(doc_fnames) # Read in",
"== b3 False \"\"\" def __init__(self, num: str, label: str, start: int, end:",
"labels = [\"ent\"] kappas, agreements, disagreements = ira(docs, anns1, anns2, labels) assert(np.isclose(kappas[0], 0.629,",
"return all_docs def read_anns(fnames: List[str]) -> List[List[BratANN]]: \"\"\" Reads all .ann files and",
"the documents that were annotated. If not specified, looks in indir1.] --indir1, Directory",
"Possible values are \"suppress\", \"print\", \"log\". Default is \"suppress\". If \"log\", writes file",
"lines and comments. if not line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\":",
"mask in idxs for j in mask] v[idxs] = i return v def",
"None): \"\"\" Prints summary statistics for the supplied results. param results: Numeric array",
"results: Numeric array of results (e.g. kappas). param varname: (Optional) Name of the",
"e, t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def __str__(self) ->",
"integer vector. The value of each element corresponds to the entity type of",
"log files in which annotators disagree. Possible values are \"suppress\", \"print\", \"log\". Default",
"Cohen's kappa and percentage agreement between two annotators. param docs: List of documents,",
"(e.g. kappas). param varname: (Optional) Name of the variable being summarized. \"\"\" if",
"level for a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False,",
"len(anns2): raise ValueError(\"Different numbers of documents and annotations.\") # Read the entity labels.",
"Path to the annotation.conf file. param docdir: Directory containing the .txt files which",
"k = 0.0 else: k = (p_o - p_e) / (1 - p_e)",
"\"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]] ann_strs2 = [\"T1\\tent",
"p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with",
"copy = True elif line.strip() == \"[relations]\": copy = False elif copy is",
"== v2) / denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) # Expected agreement:",
"Possible values are \"suppress\", \"print\" and \"log\". If \"suppress\", do nothing. If \"print\",",
"the entity labels from annotation.conf. param ann_conf: Path to annotation.conf returns: set of",
"# Compute inter rater agreement. kappa, agreement, disagree_idxs = ira(docs, anns1, anns2, labels)",
"if varname is not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean",
"return labels def ira(docs: List[str], anns1: List[List[BratANN]], anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array,",
"List[List[BratANN]], labels: Set[str]) -> np.array: \"\"\" Converts the document into an integer vector.",
"docdir: str = None, disagreements: str = \"suppress\"): \"\"\" param indir{1,2}: Input directories",
"and comments. if not line.strip() or line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy",
"str = None): \"\"\" Prints summary statistics for the supplied results. param results:",
"number of items N, labels k, and the number of times # rater",
"for docfile in fnames: doc = open(docfile, 'r').read() all_docs.append(doc) return all_docs def read_anns(fnames:",
"return args def main(indir1: str, indir2: str, ann_conf: str, docdir: str = None,",
"to \"disagreements.log\" in the current working directory. \"\"\" desc = \"\"\"Computes Cohen's kappa",
"array of results (e.g. kappas). param varname: (Optional) Name of the variable being",
"two annotators actually agreed. # Equivalent to accuracy. p_o = np.sum(v1 == v2)",
"numbers of documents and annotations.\") # Read the entity labels. labels = read_labels(ann_conf)",
"For number of items N, labels k, and the number of times #",
"not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax",
"was used for this annotation task --disagreements, Whether to suppress, print, or log",
"i in range(n_docs): denom = len(docs[i]) v1 = label_vector(docs[i], anns1[i], labels) v2 =",
"Author: <NAME> (<EMAIL>) Computes character-level Cohen's kappa and percentage agreement for a set",
"for a in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str) -> Set[str]:",
"converts their annotations to BratANN objects. param fnames: List of paths to .ann",
"small example to test ira(). \"\"\" docs = [\"The cats sat on the",
"basenames] ann_fnames2 = [os.path.join(indir2, f\"{bn}.ann\") for bn in basenames] anns1 = read_anns(ann_fnames1) anns2",
"annotations --annotation_conf, The brat annotation.conf that was used for this annotation task --disagreements,",
"vector. The value of each element corresponds to the entity type of the",
"(n, l, s, e, t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e), t)",
"summarized. \"\"\" if varname is not None: print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\")",
"= [os.path.splitext(os.path.basename(fn))[0] for fn in doc_fnames] ann_fnames1 = [os.path.join(indir1, f\"{bn}.ann\") for bn in",
"args parser = argparse.ArgumentParser(usage=usage()) parser.add_argument(\"--indir1\", type=str, required=True) parser.add_argument(\"--indir2\", type=str, required=True) parser.add_argument(\"--annotation_conf\", type=str, required=True)",
"= [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return all_anns def read_labels(ann_conf: str)",
"in fnames: anns = [BratANN.from_string(a.strip()) for a in open(annfile, 'r')] all_anns.append(anns) return all_anns",
"disagree to the console. If \"log\", files that disagree will be written to",
"Cohen's kappa and percentage agreement for a set of brat annotated files from",
"type=str, required=False, default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder)",
"os.path.basename(doc_fnames[idx]) outF.write(f\"{bn}: Agreement={p_o:.3f}\\n\") def read_docs(fnames: List[str]) -> List[str]: \"\"\" Reads in the documents.",
"input documents. \"\"\" all_docs = [] for docfile in fnames: doc = open(docfile,",
"The value of each element corresponds to the entity type of the annotation",
"\"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for s in ann_strs1]]",
"a sequence labeling task.\"\"\" parser = argparse.ArgumentParser(description=desc, usage=usage()) parser.add_argument(\"--test\", action=\"store_true\", default=False, help=\"\"\"Test the",
"{rmax:.3f})\"\"\") # noqa def test(): \"\"\" A small example to test ira(). \"\"\"",
"in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\": with open(\"disagreements.log\",",
"elif line.strip() == \"[relations]\": copy = False elif copy is True: labels.add(line.strip()) return",
"float]]]: # noqa \"\"\" Computes Cohen's kappa and percentage agreement between two annotators.",
"bool: \"\"\" Overrides the default implementation Two BratANNs are considering equal iff they",
"if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results) rmin",
"param results: Numeric array of results (e.g. kappas). param varname: (Optional) Name of",
"num self.label = label self.start = int(start) self.end = int(end) self.text = text",
"(idx, p_o) in disagree_idxs: bn = os.path.basename(doc_fnames[idx]) print(f\"{bn}: Agreement={p_o:.3f}\") if disagreements == \"log\":",
"return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self, other) ->",
"labels annotated, output of read_labels(). returns: Kappa and percentage agreement for each document.",
"print(varname) if len(results) == 1: print(f\"{results[0]:.3f}\") else: rmean = np.mean(results) rmax = np.max(results)",
"= read_anns(ann_fnames2) if not len(docs) == len(anns1) == len(anns2): raise ValueError(\"Different numbers of",
">>> b1 = BratANN(\"T3\", \"ent\", 1, 4, \"cat\") >>> b2 = BratANN.from_string(ann) >>>",
"int, end: int, text: str): self.num = num self.label = label self.start =",
"label_vector(docs[i], anns2[i], labels) # Observed agreement: How often the two annotators actually agreed.",
"k in range(len(labels)+1)]) if p_e == 1: k = 0.0 else: k =",
"annotations, output of read_anns(). param anns2: List of second annotators annotations, output of",
"the .txt files which were annotated. If None, uses indir1. param disagreements: How",
"with open(ann_conf, 'r') as infile: copy = False for line in infile: #",
"file. param docdir: Directory containing the .txt files which were annotated. If None,",
"returns: set of entity labels. \"\"\" labels = set() with open(ann_conf, 'r') as",
"A small example to test ira(). \"\"\" docs = [\"The cats sat on",
"k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str]) ->",
"[\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s) for s in",
"-> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\" # noqa def __eq__(self,",
"v2 = label_vector(docs[i], anns2[i], labels) # Observed agreement: How often the two annotators",
"args.test = False return args def main(indir1: str, indir2: str, ann_conf: str, docdir:",
"\"log\", writes file names to \"disagreements.log\" in the current working directory. \"\"\" desc",
"Kappa\") summary(agreement, \"Percentage Agreement\") # Do something with disagreements. if disagreements == \"print\":",
"idxs = [np.arange(a.start, a.end) for a in anns if a.label == lab] idxs",
"param ann_conf: Path to annotation.conf returns: set of entity labels. \"\"\" labels =",
"for bn in basenames] anns1 = read_anns(ann_fnames1) anns2 = read_anns(ann_fnames2) if not len(docs)",
"# noqa def __repr__(self) -> str: return f\"<ira.BratANN '{self.num}, {self.label}, {self.start}, {self.end}, {self.text}'>\"",
"indir2: str, ann_conf: str, docdir: str = None, disagreements: str = \"suppress\"): \"\"\"",
"Skip blank lines and comments. if not line.strip() or line.strip().startswith('#'): continue if line.strip()",
"open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o) in disagree_idxs: bn",
"annotators annotations, output of read_anns(). param labels: Set of labels annotated, output of",
"= np.sum(v1 == v2) / denom if p_o != 1.0: disagree_idxs_po.append((i, p_o)) #",
"== \"log\": with open(\"disagreements.log\", 'w') as outF: outF.write(str(datetime.datetime.now() + '\\n')) for (idx, p_o)",
"that was used for this annotation task --disagreements, Whether to suppress, print, or",
"s, e, t) = string.split(maxsplit=4) return cls(n, l, int(s), int(e), t) def __str__(self)",
"\"cat\") >>> b2 = BratANN.from_string(ann) >>> b1 == b2 True >>> b3 =",
"anns2: List[List[BratANN]], labels: Set[str]) -> Tuple[np.array, np.array, List[Tuple[int, float]]]: # noqa \"\"\" Computes",
"of character level annotations. \"\"\" v = np.zeros(len(doc)) # For each character for",
"default=None) parser.add_argument(\"--disagreements\", type=str, required=False, default=\"suppress\", choices=[\"suppress\", \"print\", \"log\"]) args = parser.parse_args(remainder) args.test =",
"[\"T1\\tent 4 8\\tcats\", \"T2\\tent 9 12\\tsat\", \"T3\\tent 20 23\\tmat\"] anns1 = [[BratANN.from_string(s) for",
"= k return (kappas, p_os, disagree_idxs_po) def label_vector(doc: List[str], anns: List[List[BratANN]], labels: Set[str])",
"* np.sum([np.sum(v1 == k) * np.sum(v2 == k) for k in range(len(labels)+1)]) if",
"= np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po = [] for i in range(n_docs): denom",
"line.strip().startswith('#'): continue if line.strip() == \"[entities]\": copy = True elif line.strip() == \"[relations]\":",
"ann_strs1]] ann_strs2 = [\"T1\\tent 4 7\\tcat\", \"T2\\tent 20 23 mat\"] anns2 = [[BratANN.from_string(s)",
"args = parse_args() if args.test is True: import doctest doctest.testmod() test() else: main(args.indir1,",
"def main(indir1: str, indir2: str, ann_conf: str, docdir: str = None, disagreements: str",
"Read the entity labels. labels = read_labels(ann_conf) # Compute inter rater agreement. kappa,",
"annotators annotations --annotation_conf, The brat annotation.conf that was used for this annotation task",
"document. \"\"\" n_docs = len(docs) p_os = np.zeros(n_docs) kappas = np.zeros(n_docs) disagree_idxs_po ="
] |
[
"verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address',",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations =",
"[ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the",
"help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration',",
"Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True,",
"Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian",
"models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]",
"class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [",
"of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True,",
"verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last",
"Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')),",
"models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT",
"<gh_stars>1-10 # Generated by Django 2.0.1 on 2018-02-10 08:11 from django.conf import settings",
"the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15,",
"('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last",
"to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter",
"Generated by Django 2.0.1 on 2018-02-10 08:11 from django.conf import settings from django.db",
"null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True,",
"Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian",
"the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15,",
"models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15,",
"max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')),",
"2.0.1 on 2018-02-10 08:11 from django.conf import settings from django.db import migrations, models",
"null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter",
"True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id',",
"models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone",
"of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number',",
"null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"Django 2.0.1 on 2018-02-10 08:11 from django.conf import settings from django.db import migrations,",
"verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First",
"max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name',",
"models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address',",
"OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True,",
"serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the",
"('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),",
"migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50,",
"the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')),",
"Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True,",
"help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN",
"Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the",
"= [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter",
"verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),",
"the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15,",
"max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id',",
"Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time',",
"models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth',",
"django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0',",
"verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter",
"initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance',",
"the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8,",
"('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name',",
"], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the",
"help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details',",
"models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number',",
"verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],",
"verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter",
"max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')),",
"# Generated by Django 2.0.1 on 2018-02-10 08:11 from django.conf import settings from",
"max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id',",
"the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')),",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name',",
"verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter",
"migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date',",
"verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter",
"IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True,",
"max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1,",
"verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN",
"max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15,",
"('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian",
"max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone',",
"Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"2018-02-10 08:11 from django.conf import settings from django.db import migrations, models import django.db.models.deletion",
"the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[",
"('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),",
"], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True,",
"= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],",
"Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id',",
"null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')),",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')),",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations",
"] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date',",
"('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True,",
"by Django 2.0.1 on 2018-02-10 08:11 from django.conf import settings from django.db import",
"Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id',",
"Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True,",
"name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15,",
"Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter",
"[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True,",
"migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50,",
"max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')),",
"08:11 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]",
"serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the",
"('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name',",
"Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id',",
"import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[",
"Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel(",
"verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration',",
"Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT",
"Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date",
"primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter",
"Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details',",
"to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter",
"models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the",
"null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob',",
"max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True,",
"), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name',",
"dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True,",
"max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name',",
"Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian",
"of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student",
"from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"Name')), ('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00',",
"('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time',",
"the Date', max_length=15, verbose_name='Date')), ('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')),",
"('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name',",
"max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')),",
"null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter",
"operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00',",
"name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True,",
"Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')),",
"on 2018-02-10 08:11 from django.conf import settings from django.db import migrations, models import",
"max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Student_Details', fields=[ ('id', models.AutoField(auto_created=True,",
"), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name',",
"models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50,",
"models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel(",
"Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True, verbose_name='Last Name')), ('dob', models.DateField(help_text='Enter Date",
"help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the OUT Time',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.CharField(default='00/00/00', help_text='Enter the Date', max_length=15, verbose_name='Date')), ('in_time',",
"Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50,",
"('out_time', models.CharField(blank=True, help_text='Enter the OUT Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter",
"verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('phone', models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),",
"verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the Address', max_length=50, null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone",
"null=True, verbose_name='Address')), ('phone', models.CharField(help_text='Enter Phone Number', max_length=15, null=True, verbose_name='Phone No')), ('t_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),",
"Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Teacher_Details', fields=[",
"('in_time', models.CharField(default='00:00:00', help_text='Enter the IN Time', max_length=15, verbose_name='IN Time')), ('out_time', models.CharField(blank=True, help_text='Enter the",
"the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50, null=True,",
"models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter the Last Name', max_length=50,",
"null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student Status')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),",
"help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status', max_length=1, verbose_name='Student",
"primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter the First-Name', max_length=50, null=True, verbose_name='First Name')), ('last_name', models.CharField(help_text='Enter",
"settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"('dob', models.DateField(help_text='Enter Date of Birth', max_length=8, null=True, verbose_name='Date of Birth')), ('address', models.CharField(help_text='Enter the",
"models.CharField(help_text='Enter Guardian Number', max_length=15, null=True, verbose_name='Guardian Phone')), ('st_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel(",
"null=True, verbose_name='Address')), ('g_name', models.CharField(help_text='Enter the Student Guardian Name', max_length=50, null=True, verbose_name='Guardian Name')), ('phone',",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Student_Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"Time', max_length=15, null=True, verbose_name='OUT Time')), ('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')),",
"('duration', models.CharField(blank=True, help_text='Enter the Duration', max_length=15, null=True, verbose_name='Duration')), ('status', models.CharField(default='0', help_text='Enter the Status',"
] |
[
"string file. - Loss - Epochs - Time taken \"\"\" raise NotImplementedError def",
"= config self.container = container self.hist = None if create_empty: self.core = None",
"keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence,",
"return model def update_config( self, new_config: dict ) -> None: \"\"\" Update the",
"to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def load_model( self, folder_dir: str",
"self.file_name # Try to create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\")",
"Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core",
"directly. return y_hat def save_model( self, file_dir: str=None ) -> None: if file_dir",
")) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model)",
"import datetime import os import keras import numpy as np import pandas as",
"def summarize_training(self): \"\"\" Summarize training result to string file. - Loss - Epochs",
"print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\",",
"optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to string file. - Loss -",
"= keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model =",
"weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not found.",
"-> None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized:",
"arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\") model",
"self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png file. print(\"Saving model visualization...\") try:",
"units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM:",
"name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\",",
"verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) -> None: start_time = datetime.datetime.now()",
"self, config: dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct the Stacked lstm",
"-> None: \"\"\" Update the neural network configuration, and re-construct, re-compile the core.",
"\"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime",
"def __init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization",
"file_dir is None: # If no file directory specified, use the default one.",
"print(\"Model illustration cannot be saved.\") # Save training history (if any) if self.hist",
"neural network configuration...\") self.prev_config = self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False)",
"validation_split=0.1 if self.config is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken =",
"#TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should",
"units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense(",
"finish_time = datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for",
"file_dir = self.file_name # Try to create record folder. try: folder = f\"./saved_models/{file_dir}/\"",
"found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") #",
"illustration to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True)",
"pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to",
"cannot be saved.\") # Save training history (if any) if self.hist is not",
"Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container = container self.hist = None",
"show_layer_names=True) except: print(\"Model illustration cannot be saved.\") # Save training history (if any)",
"except: print(\"Model illustration cannot be saved.\") # Save training history (if any) if",
"model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png file. print(\"Saving model",
"Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container = container",
"json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading model weights...\")",
"dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model",
"\"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should be folder_dir",
"-> None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct",
"{str(time_taken)}\") def predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1)",
"is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time - start_time",
"print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container =",
"folder {folder_dir}\") # construct model from json print(\"Reconstruct model from Json file...\") try:",
"{folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to string",
"None: # If no file directory specified, use the default one. file_dir =",
"to create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory",
"dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct the Stacked lstm model, Note:",
"sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\")",
"check configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config self.config",
"the default one. file_dir = self.file_name # Try to create record folder. try:",
"h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png file.",
"print(\"Done.\") # Save model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") #",
"not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should be folder_dir += \"/\"",
"to compare with self.container.*_X directly. return y_hat def save_model( self, file_dir: str=None )",
"specified, use the default one. file_dir = self.file_name # Try to create record",
"{folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create",
"keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose:",
"Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training result: -",
"_construct_lstm_model( self, config: dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct the Stacked",
") model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from",
"as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to h5 print(\"Saving model weights...\")",
"def update_config( self, new_config: dict ) -> None: \"\"\" Update the neural network",
"from json print(\"Reconstruct model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except",
"save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True ) -> keras.Model:",
"add check configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config",
"history is saved to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def load_model(",
"\"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training result: - Plot training",
"to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except:",
"from folder {folder_dir}\") # construct model from json print(\"Reconstruct model from Json file...\")",
"Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None",
"with self.container.*_X directly. return y_hat def save_model( self, file_dir: str=None ) -> None:",
"multivariate_container import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def __init__( self, container:",
"base_model import BaseModel from multivariate_container import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel):",
"print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def",
"__init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method.",
"validation set loss. \"\"\" # TODO: move visualize training to general methods. raise",
"configuration, and re-construct, re-compile the core. \"\"\" # TODO: add check configuration method",
"using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence)",
"None: \"\"\" Update the neural network configuration, and re-construct, re-compile the core. \"\"\"",
"{self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container = container self.hist = None if",
"directory ./saved_models/\") # Save model structure to JSON print(\"Saving model structure...\") model_json =",
"folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\") # construct model from json",
"any) if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined",
"model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with",
"print(\"Done.\") # load weights from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True)",
"result: - Plot training set loss and validation set loss. \"\"\" # TODO:",
"config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked lstm model,",
"update_config( self, new_config: dict ) -> None: \"\"\" Update the neural network configuration,",
"os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please create directory ./saved_models/\") # Save",
"keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm)",
"correct format, folder_dir should be folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\")",
"- start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray",
"else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now()",
"def _construct_lstm_model( self, config: dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct the",
"Plot training set loss and validation set loss. \"\"\" # TODO: move visualize",
"be folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\") # construct model from",
"model def update_config( self, new_config: dict ) -> None: \"\"\" Update the neural",
")(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed",
"default one. file_dir = self.file_name # Try to create record folder. try: folder",
"Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm",
"not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined",
"bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea =",
"keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\",",
"API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm =",
"and re-construct, re-compile the core. \"\"\" # TODO: add check configuration method here.",
"self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to",
"format, folder_dir should be folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\") #",
"# TODO: add check configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config",
"with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\"",
"name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM",
"self.config is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time -",
"MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\"",
"is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"] ) finish_time",
"container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\" _,",
"TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential",
"self.hist = None if create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name()",
"compare with self.container.*_X directly. return y_hat def save_model( self, file_dir: str=None ) ->",
"= new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 )",
"\"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir",
"= open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\"",
"\") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict, verbose: bool=True ) ->",
"\"Failed to create directory, please create directory ./saved_models/\") # Save model structure to",
"= keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose:",
"+= \"/\" print(f\"Load model from folder {folder_dir}\") # construct model from json print(\"Reconstruct",
"Update the neural network configuration, and re-construct, re-compile the core. \"\"\" # TODO:",
"Generating LSTM model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\")",
"from base_model import BaseModel from multivariate_container import MultivariateContainer from typing import Union class",
"pd from base_model import BaseModel from multivariate_container import MultivariateContainer from typing import Union",
"directory, please create directory ./saved_models/\") # Save model structure to JSON print(\"Saving model",
"-> None: if file_dir is None: # If no file directory specified, use",
"to create directory, please create directory ./saved_models/\") # Save model structure to JSON",
"lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions",
"self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading model weights...\") try:",
"= finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict( self,",
"bool=False) -> None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM",
"visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\")",
"the correct format, folder_dir should be folder_dir += \"/\" print(f\"Load model from folder",
"model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add(",
"configuration...\") self.prev_config = self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def",
"hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\",",
"model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True",
"record directory created: {folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError(",
"name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \")",
"construct model from json print(\"Reconstruct model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\",",
"\"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea),",
"model def _construct_lstm_sequential( self, config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct",
")) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\")",
"str ) -> None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert",
"is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss])",
"Epochs - Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training",
"print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray ) ->",
"lstm model, Note: Modify this method to change model configurations. # TODO: Add",
"to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png",
"np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"]",
"\\n\\tFeature: {self.num_fea}\") self.config = config self.container = container self.hist = None if create_empty:",
"Note: Modify this method to change model configurations. # TODO: Add arbitray layer",
"by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\")",
"bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked lstm model, Note: Modify this",
"self, config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked lstm",
"keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False",
"open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to h5 print(\"Saving",
"- Loss - Epochs - Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\"",
"return y_hat def save_model( self, file_dir: str=None ) -> None: if file_dir is",
"arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence =",
"-> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y,",
"(if any) if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"]))",
"training result to string file. - Loss - Epochs - Time taken \"\"\"",
"None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save",
"try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file not found.",
"def save_model( self, file_dir: str=None ) -> None: if file_dir is None: #",
"Stacked lstm model, Note: Modify this method to change model configurations. # TODO:",
"one. file_dir = self.file_name # Try to create record folder. try: folder =",
"except FileNotFoundError: raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file =",
"configuration: \") keras.utils.print_summary(model) return model def update_config( self, new_config: dict ) -> None:",
"verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked lstm model, Note: Modify",
"json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading model",
"keras.utils.print_summary(model) return model def update_config( self, new_config: dict ) -> None: \"\"\" Update",
"Construct the Stacked lstm model, Note: Modify this method to change model configurations.",
"self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model(",
"= None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be",
"None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"] ) finish_time =",
"= os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please create directory ./saved_models/\") #",
"shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization)",
"is None: # If no file directory specified, use the default one. file_dir",
"units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1,",
"to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\") # Save training history",
"# Assert the correct format, folder_dir should be folder_dir += \"/\" print(f\"Load model",
"None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined =",
"self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if",
"# Save model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save",
"\"\"\" Construct the Stacked lstm model, Note: Modify this method to change model",
"dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 =",
"else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save to",
"datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config",
"model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not",
"start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32",
"epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat =",
"combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns =",
"= pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved",
"f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core =",
"model structure to JSON print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\")",
"Save model structure to JSON print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\",",
"use the default one. file_dir = self.file_name # Try to create record folder.",
"df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No training history found.\")",
"please create directory ./saved_models/\") # Save model structure to JSON print(\"Saving model structure...\")",
"df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is",
"\"\"\" Visualize the training result: - Plot training set loss and validation set",
"= keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading model weights...\") try: self.core.load_weights(",
"self.config = config self.container = container self.hist = None if create_empty: self.core =",
"change model configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM",
"if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def",
"self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"],",
"config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea",
"try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not found. Expected:",
"# load weights from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except",
"saved.\") # Save training history (if any) if self.hist is not None: hist_loss",
"np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used",
"re-compile the core. \"\"\" # TODO: add check configuration method here. print(\"MultivariateLSTM: Updating",
"{epochs} epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat",
"container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container",
"np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) #",
"epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None",
"combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\")",
") finish_time = datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs",
"= keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\"",
"finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict( self, X_feed:",
"FileNotFoundError: raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read()",
"record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\")",
"raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close()",
"self.container = container self.hist = None if create_empty: self.core = None else: self.core",
"raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training result: - Plot training set",
"int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit(",
"save_model( self, file_dir: str=None ) -> None: if file_dir is None: # If",
"except: print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory,",
"model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") #",
"from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json",
"= self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1",
"print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is",
"folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory:",
"directory created: {folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed",
"verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential(",
"{folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def load_model( self, folder_dir: str )",
"if create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current",
"model constructed with configuration: \") keras.utils.print_summary(model) return model def update_config( self, new_config: dict",
"= self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) -> None: start_time",
"-> keras.Sequential: \"\"\" Construct the Stacked lstm model, Note: Modify this method to",
"found.\") print(\"Done.\") def load_model( self, folder_dir: str ) -> None: \"\"\" #TODO: doc",
"Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\")",
"here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config self.config = new_config self.core",
"MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\" _, self.time_steps,",
"units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" ))",
"self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\"",
"illustration cannot be saved.\") # Save training history (if any) if self.hist is",
"configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with",
"try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\") #",
"for {str(time_taken)}\") def predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed,",
"weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png file. print(\"Saving model visualization...\")",
"input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM(",
"self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs}",
"datetime import os import keras import numpy as np import pandas as pd",
"Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self):",
"json print(\"Reconstruct model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError:",
"dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked lstm model, Note:",
"model, Note: Modify this method to change model configurations. # TODO: Add arbitray",
"keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" ))",
"Updating neural network configuration...\") self.prev_config = self.config self.config = new_config self.core = self._construct_lstm_model(self.config,",
"= [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No",
"= self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with self.container.*_X directly. return y_hat",
"# y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with self.container.*_X directly.",
"TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\")",
"= keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions =",
"with configuration: \") keras.utils.print_summary(model) return model def update_config( self, new_config: dict ) ->",
"set loss and validation set loss. \"\"\" # TODO: move visualize training to",
"summarize_training(self): \"\"\" Summarize training result to string file. - Loss - Epochs -",
"str=None ) -> None: if file_dir is None: # If no file directory",
"to change model configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating",
"= f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory: \")",
"container self.hist = None if create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config)",
"folder_dir should be folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\") # construct",
") -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat",
"- Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training result:",
"np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns",
"be saved.\") # Save training history (if any) if self.hist is not None:",
"import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer,",
"keras.Model: \"\"\" Construct the Stacked lstm model, Note: Modify this method to change",
"self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs:",
"JSON print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json)",
"else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished,",
"keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with",
"created: {folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to",
"print(f\"Load model from folder {folder_dir}\") # construct model from json print(\"Reconstruct model from",
"\"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM(",
"import BaseModel from multivariate_container import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def",
"\"\"\" Summarize training result to string file. - Loss - Epochs - Time",
"structure to JSON print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as",
"new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) ->",
"print(\"Reconstruct model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise",
"None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct format,",
"If no file directory specified, use the default one. file_dir = self.file_name #",
"create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model",
"configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict, verbose: bool=True )",
"self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\"",
"class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) -> None:",
"model from folder {folder_dir}\") # construct model from json print(\"Reconstruct model from Json",
"model illustration to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True,",
"model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5",
"model with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True,",
"set loss. \"\"\" # TODO: move visualize training to general methods. raise NotImplementedError",
"be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True ) ->",
")(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\")",
"{folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\")",
"loss and validation set loss. \"\"\" # TODO: move visualize training to general",
"Modify this method to change model configurations. # TODO: Add arbitray layer support.",
") -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X,",
"name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model",
"this method to change model configurations. # TODO: Add arbitray layer support. \"\"\"",
"print(\"No training history found.\") print(\"Done.\") def load_model( self, folder_dir: str ) -> None:",
"= keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"],",
"network configuration, and re-construct, re-compile the core. \"\"\" # TODO: add check configuration",
"# Try to create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment",
"method to change model configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM:",
"verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def update_config(",
"keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict, verbose: bool=True ) -> keras.Sequential:",
"history (if any) if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss =",
")) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model",
"print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self,",
"\"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature:",
"doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should be",
"./saved_models/\") # Save model structure to JSON print(\"Saving model structure...\") model_json = self.core.to_json()",
"self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss,",
"will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True )",
"raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def",
"if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined =",
"constructed with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict, verbose:",
"None if create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM:",
"print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM:",
"= self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare",
"structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save",
"as pd from base_model import BaseModel from multivariate_container import MultivariateContainer from typing import",
"raise FileNotFoundError( \"Failed to create directory, please create directory ./saved_models/\") # Save model",
"should be folder_dir += \"/\" print(f\"Load model from folder {folder_dir}\") # construct model",
"f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory: \") _",
"constructed with configuration: \") keras.utils.print_summary(model) return model def update_config( self, new_config: dict )",
"time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict(",
"dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\")",
"= self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\") def",
"LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def update_config( self, new_config:",
"load_model( self, folder_dir: str ) -> None: \"\"\" #TODO: doc \"\"\" if not",
"keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \")",
"method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config self.config = new_config",
"to string file. - Loss - Epochs - Time taken \"\"\" raise NotImplementedError",
"Loss - Epochs - Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize",
"LSTM model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization",
"support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\") model = keras.Sequential()",
"\") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please create directory",
"os import keras import numpy as np import pandas as pd from base_model",
"= keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\"",
"file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file not",
"file. - Loss - Epochs - Time taken \"\"\" raise NotImplementedError def visualize_training(self):",
"from multivariate_container import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def __init__( self,",
"self.prev_config = self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model(",
"model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1,",
"model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps, self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization =",
"print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to string file. -",
"def visualize_training(self): \"\"\" Visualize the training result: - Plot training set loss and",
"keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\") # Save",
"finished, {epochs} epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray ) -> np.ndarray:",
"epochs: int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist =",
"f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict,",
"weights from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise",
"self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config =",
"= container self.hist = None if create_empty: self.core = None else: self.core =",
"= datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if",
"# y_hat returned used to compare with self.container.*_X directly. return y_hat def save_model(",
"FileNotFoundError: raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\")",
"is saved to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def load_model( self,",
"# TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras",
"new_config: dict ) -> None: \"\"\" Update the neural network configuration, and re-construct,",
"model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if",
"bool=True ) -> keras.Model: \"\"\" Construct the Stacked lstm model, Note: Modify this",
"config self.container = container self.hist = None if create_empty: self.core = None else:",
"file directory specified, use the default one. file_dir = self.file_name # Try to",
"self, epochs: int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist",
"Save model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model",
"self.num_fea), dtype=\"float32\", name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1",
"np import pandas as pd from base_model import BaseModel from multivariate_container import MultivariateContainer",
") -> keras.Sequential: \"\"\" Construct the Stacked lstm model, Note: Modify this method",
"load weights from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError:",
"training history (if any) if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss",
"model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"],",
"core. \"\"\" # TODO: add check configuration method here. print(\"MultivariateLSTM: Updating neural network",
"keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM:",
"model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return",
"saved to {folder}hist.csv...\") else: print(\"No training history found.\") print(\"Done.\") def load_model( self, folder_dir:",
"y_hat returned used to compare with self.container.*_X directly. return y_hat def save_model( self,",
"Try to create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record",
"fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else",
"df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else:",
"print(\"Done.\") def load_model( self, folder_dir: str ) -> None: \"\"\" #TODO: doc \"\"\"",
"with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to h5",
"except FileNotFoundError: raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\",",
"\"\"\" # TODO: add check configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\")",
"self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\") # Save training",
") -> keras.Model: \"\"\" Construct the Stacked lstm model, Note: Modify this method",
"def predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) #",
"Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add(",
"import keras import numpy as np import pandas as pd from base_model import",
"f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\"",
"units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions)",
"predict( self, X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat",
"show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be saved.\") # Save training history (if",
"_, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\")",
"BaseModel from multivariate_container import MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def __init__(",
"predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if",
")(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\" )(dense1)",
"{folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights",
"Summarize training result to string file. - Loss - Epochs - Time taken",
"\\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container = container self.hist =",
"directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please create",
"model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning(",
"print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file",
"\"\"\" Update the neural network configuration, and re-construct, re-compile the core. \"\"\" #",
"network configuration...\") self.prev_config = self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\")",
"= np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32)",
"not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training",
"training set loss and validation set loss. \"\"\" # TODO: move visualize training",
"config: dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct the Stacked lstm model,",
"the Stacked lstm model, Note: Modify this method to change model configurations. #",
"self, file_dir: str=None ) -> None: if file_dir is None: # If no",
"MultivariateContainer from typing import Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config:",
"self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken",
"= np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df",
"not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\")",
"optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model",
"import Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False)",
")) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense(",
"re-construct, re-compile the core. \"\"\" # TODO: add check configuration method here. print(\"MultivariateLSTM:",
"model from json print(\"Reconstruct model from Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\")",
"= json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load weights from h5 print(\"Loading",
"dict ) -> None: \"\"\" Update the neural network configuration, and re-construct, re-compile",
"Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to",
"LSTM model with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea),",
"file_dir: str=None ) -> None: if file_dir is None: # If no file",
"None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\",
"batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else",
"folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except:",
"create directory, please create directory ./saved_models/\") # Save model structure to JSON print(\"Saving",
"name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add(",
"hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined,",
"\"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to h5 print(\"Saving model",
"layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence = keras.layers.Input(",
"normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"],",
"self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config",
"np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df =",
"print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to png file. print(\"Saving",
"print(\"Done\") # Save model illustration to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model(",
"= self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model weight",
"# Save training history (if any) if self.hist is not None: hist_loss =",
"h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5",
"model constructed with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict,",
"NotImplementedError def visualize_training(self): \"\"\" Visualize the training result: - Plot training set loss",
"import pandas as pd from base_model import BaseModel from multivariate_container import MultivariateContainer from",
"print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"],",
"Assert the correct format, folder_dir should be folder_dir += \"/\" print(f\"Load model from",
"None: if file_dir is None: # If no file directory specified, use the",
"folder_dir: str ) -> None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): #",
"create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created:",
"= datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\")",
"used to compare with self.container.*_X directly. return y_hat def save_model( self, file_dir: str=None",
"self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"] )",
"self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with self.container.*_X directly. return y_hat def",
"Visualize the training result: - Plot training set loss and validation set loss.",
"return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" ))",
"training history found.\") print(\"Done.\") def load_model( self, folder_dir: str ) -> None: \"\"\"",
"= self.file_name # Try to create record folder. try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir",
"directory specified, use the default one. file_dir = self.file_name # Try to create",
"file not found. Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file)",
"# construct model from json print(\"Reconstruct model from Json file...\") try: json_file =",
"= keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration:",
"file not found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize",
"\"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No training history",
"return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense( 1, name=\"Prediction\"",
"open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" )",
"method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\",
"png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model",
"taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the training result: - Plot",
"configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using",
"def _construct_lstm_sequential( self, config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the",
"print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def update_config( self,",
"{self.num_fea}\") self.config = config self.container = container self.hist = None if create_empty: self.core",
"the neural network configuration, and re-construct, re-compile the core. \"\"\" # TODO: add",
"np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history",
"LSTM model constructed with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config:",
"with configuration: \") keras.utils.print_summary(model) return model def _construct_lstm_sequential( self, config: dict, verbose: bool=True",
"support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence = keras.layers.Input( shape=(self.time_steps,",
"folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should be folder_dir += \"/\" print(f\"Load",
"from typing import Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None,",
"self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10",
"API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM(",
"model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot be",
"self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with",
"print(\"Current directory: \") _ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please",
"[\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training history is saved to {folder}hist.csv...\") else: print(\"No training",
"Generating LSTM model with Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps,",
"to JSON print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file:",
"y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to",
"datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def",
"hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"])) hist_val_loss = np.squeeze(np.array(self.hist.history[\"val_loss\"])) combined = np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined)",
"Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step:",
"Expected: {folder_dir}model_structure.json\" ) model_file = json_file.read() json_file.close() self.core = keras.models.model_from_json(model_file) print(\"Done.\") # load",
"\") keras.utils.print_summary(model) return model def update_config( self, new_config: dict ) -> None: \"\"\"",
"FileNotFoundError( \"Failed to create directory, please create directory ./saved_models/\") # Save model structure",
"create directory ./saved_models/\") # Save model structure to JSON print(\"Saving model structure...\") model_json",
"numpy as np import pandas as pd from base_model import BaseModel from multivariate_container",
"return model def _construct_lstm_sequential( self, config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\"",
") -> None: if file_dir is None: # If no file directory specified,",
"result to string file. - Loss - Epochs - Time taken \"\"\" raise",
"self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is",
"X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat)",
"from h5 print(\"Loading model weights...\") try: self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning(",
"self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) -> None: start_time =",
"configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config self.config =",
"if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config is None else self.config[\"validation_split\"]",
"the core. \"\"\" # TODO: add check configuration method here. print(\"MultivariateLSTM: Updating neural",
"# Save model structure to JSON print(\"Saving model structure...\") model_json = self.core.to_json() with",
"def fit_model( self, epochs: int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start",
"-> keras.Model: \"\"\" Construct the Stacked lstm model, Note: Modify this method to",
"if not folder_dir.endswith(\"/\"): # Assert the correct format, folder_dir should be folder_dir +=",
"= np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\", \"val_loss\"] df.to_csv(f\"{folder}hist.csv\", sep=\",\") print(f\"Training",
"self.container.train_X, self.container.train_y, epochs=epochs, batch_size=32 if self.config is None else self.config[\"batch_size\"], validation_split=0.1 if self.config",
"None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time - start_time print(f\"\\tFitting",
"units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration:",
"history found.\") print(\"Done.\") def load_model( self, folder_dir: str ) -> None: \"\"\" #TODO:",
"self.core.load_weights( f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\"",
"self, new_config: dict ) -> None: \"\"\" Update the neural network configuration, and",
"= None if create_empty: self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print(",
"self, X_feed: np.ndarray ) -> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat =",
"Current model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose:",
"returned used to compare with self.container.*_X directly. return y_hat def save_model( self, file_dir:",
"- Plot training set loss and validation set loss. \"\"\" # TODO: move",
"print( f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config:",
"\\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config self.container = container self.hist",
"typing import Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None, create_empty:",
"verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with self.container.*_X",
"try: folder = f\"./saved_models/{file_dir}/\" os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current",
"Save training history (if any) if self.hist is not None: hist_loss = np.squeeze(np.array(self.hist.history[\"loss\"]))",
"model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\") # Save model",
"name=\"input_sequence\") normalization = keras.layers.BatchNormalization()(input_sequence) lstm = keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense(",
"# Save model illustration to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core,",
"# If no file directory specified, use the default one. file_dir = self.file_name",
"json_file.write(model_json) print(\"Done.\") # Save model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\")",
"= container.train_X.shape print(f\"MultivariateLSTM Initialized: \\ \\n\\tTime Step: {self.time_steps}\\ \\n\\tFeature: {self.num_fea}\") self.config = config",
"os.system(f\"mkdir {folder}\") print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory: \") _ =",
"Keras Sequential API\") model = keras.Sequential() model.add(keras.layers.LSTM( units=config[\"nn.lstm1\"], input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" ))",
"model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed",
"neural network configuration, and re-construct, re-compile the core. \"\"\" # TODO: add check",
"input_shape=(self.time_steps, self.num_fea), return_sequences=True, name=\"LSTM1\" )) model.add( keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"],",
"print(f\"Experiment record directory created: {folder}\") except: print(\"Current directory: \") _ = os.system(\"pwd\") raise",
"keras import numpy as np import pandas as pd from base_model import BaseModel",
"else: print(\"No training history found.\") print(\"Done.\") def load_model( self, folder_dir: str ) ->",
"# TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model",
"if self.config is None else self.config[\"validation_split\"] ) finish_time = datetime.datetime.now() time_taken = finish_time",
"file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration",
"./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True ) -> keras.Model: \"\"\" Construct",
"self, folder_dir: str ) -> None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"):",
") print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to string file.",
"y_hat def save_model( self, file_dir: str=None ) -> None: if file_dir is None:",
"fit_model( self, epochs: int=10 ) -> None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\")",
"self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self, epochs: int=10 ) -> None:",
"json_file: json_file.write(model_json) print(\"Done.\") # Save model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\")",
"TODO: add check configuration method here. print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config =",
"= self.config self.config = new_config self.core = self._construct_lstm_model(self.config, verbose=False) print(\"\\tDone.\") def fit_model( self,",
"and validation set loss. \"\"\" # TODO: move visualize training to general methods.",
"name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\" )) model.compile(loss=\"mse\",",
"Union class MultivariateLSTM(BaseModel): def __init__( self, container: MultivariateContainer, config: bool=None, create_empty: bool=False) ->",
"model weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration",
"1, name=\"Prediction\" )(dense1) model = keras.Model(inputs=input_sequence, outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM",
"the training result: - Plot training set loss and validation set loss. \"\"\"",
"visualize_training(self): \"\"\" Visualize the training result: - Plot training set loss and validation",
"y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned used to compare with self.container.*_X directly. return",
") -> None: \"\"\" #TODO: doc \"\"\" if not folder_dir.endswith(\"/\"): # Assert the",
"\"/\" print(f\"Load model from folder {folder_dir}\") # construct model from json print(\"Reconstruct model",
"outputs=predictions) model.compile(loss=\"mse\", optimizer=\"adam\") if verbose: print(\"\\tMultivariateLSTM: LSTM model constructed with configuration: \") keras.utils.print_summary(model)",
"training result: - Plot training set loss and validation set loss. \"\"\" #",
"None: start_time = datetime.datetime.now() print(\"MultivariateLSTM: Start fitting.\") self.hist = self.core.fit( self.container.train_X, self.container.train_y, epochs=epochs,",
"print(\"Saving model structure...\") model_json = self.core.to_json() with open(f\"{folder}model_structure.json\", \"w\") as json_file: json_file.write(model_json) print(\"Done.\")",
"keras.Sequential: \"\"\" Construct the Stacked lstm model, Note: Modify this method to change",
"{folder_dir}\") # construct model from json print(\"Reconstruct model from Json file...\") try: json_file",
"-> np.ndarray: y_hat = self.core.predict(X_feed, verbose=1) # y_hat = self.container.scaler_y.inverse_transform(y_hat) # y_hat returned",
"import os import keras import numpy as np import pandas as pd from",
"json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file not found. Expected:",
"_construct_lstm_sequential( self, config: dict, verbose: bool=True ) -> keras.Sequential: \"\"\" Construct the Stacked",
"print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\", show_shapes=True, show_layer_names=True) except: print(\"Model illustration cannot",
"self.container.*_X directly. return y_hat def save_model( self, file_dir: str=None ) -> None: if",
"import numpy as np import pandas as pd from base_model import BaseModel from",
"if file_dir is None: # If no file directory specified, use the default",
"found. Expected: {folder_dir}model_weights.h5\" ) print(\"Done.\") self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result",
"layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model with Keras Sequential API\") model =",
"self.core = None else: self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will",
"_ = os.system(\"pwd\") raise FileNotFoundError( \"Failed to create directory, please create directory ./saved_models/\")",
") -> None: \"\"\" Update the neural network configuration, and re-construct, re-compile the",
"to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self, config: dict, verbose: bool=True ) -> keras.Model: \"\"\"",
"start_time print(f\"\\tFitting finished, {epochs} epochs for {str(time_taken)}\") def predict( self, X_feed: np.ndarray )",
"Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model using Model API.\") input_sequence",
"Save model illustration to png file. print(\"Saving model visualization...\") try: keras.utils.plot_model( self.core, to_file=f\"{folder}model.png\",",
"self.core = self._construct_lstm_model(self.config) self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\")",
"as np import pandas as pd from base_model import BaseModel from multivariate_container import",
"model configurations. # TODO: Add arbitray layer support. \"\"\" print(\"MultivariateLSTM: Generating LSTM model",
"= np.stack([hist_loss, hist_val_loss]) combined = np.transpose(combined) df = pd.DataFrame(combined, dtype=np.float32) df.columns = [\"loss\",",
"Json file...\") try: json_file = open(f\"{folder_dir}model_structure.json\", \"r\") except FileNotFoundError: raise Warning( f\"Json file",
"verbose: bool=True ) -> keras.Model: \"\"\" Construct the Stacked lstm model, Note: Modify",
"\"r\") except FileNotFoundError: raise Warning( f\"Json file not found. Expected: {folder_dir}model_structure.json\" ) model_file",
"print(\"MultivariateLSTM: Updating neural network configuration...\") self.prev_config = self.config self.config = new_config self.core =",
"no file directory specified, use the default one. file_dir = self.file_name # Try",
"create_empty: bool=False) -> None: \"\"\" Initialization method. \"\"\" _, self.time_steps, self.num_fea = container.train_X.shape",
"self._gen_file_name() print( f\"\\tMultivariateLSTM: Current model will be save to ./saved_models/f{self.file_name}/\") def _construct_lstm_model( self,",
"- Epochs - Time taken \"\"\" raise NotImplementedError def visualize_training(self): \"\"\" Visualize the",
"weight to h5 print(\"Saving model weights...\") self.core.save_weights(f\"{folder}model_weights.h5\") print(\"Done\") # Save model illustration to",
"self.core.compile(loss=\"mse\", optimizer=\"adam\") def summarize_training(self): \"\"\" Summarize training result to string file. - Loss",
"def load_model( self, folder_dir: str ) -> None: \"\"\" #TODO: doc \"\"\" if",
"keras.layers.LSTM( units=config[\"nn.lstm2\"], name=\"LSTM2\" )) model.add( keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )) model.add( keras.layers.Dense( units=1, name=\"Dense_output\"",
"keras.layers.LSTM( units=config[\"nn.lstm1\"], return_sequences=False )(normalization) dense1 = keras.layers.Dense( units=config[\"nn.dense1\"], name=\"Dense1\" )(lstm) predictions = keras.layers.Dense(",
"f\"{folder_dir}model_weights.h5\", by_name=True) except FileNotFoundError: raise Warning( f\"h5 file not found. Expected: {folder_dir}model_weights.h5\" )",
"pandas as pd from base_model import BaseModel from multivariate_container import MultivariateContainer from typing"
] |
[
"<filename>dreamerv2/training/__init__.py from .trainer import Trainer from .config import Config from .evaluator import Evaluator"
] |
[
"list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris)",
"] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt",
"source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file)",
"occurred while processing.\\n' + \\ 'The error was: %s: %s\\n' % (exceptiontype, str(e))",
"options.has_key('instant'): msg = 'When using --instant, exactly 1 source doc URI and 1",
"isinstance(prefixes, list): prefixes = [prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p) if",
"wrapper for SourceArgToInputSource(). If an InputSource cannot be created from the source argument,",
"= args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude,",
"Set up XSLT processor (without stylesheets) ------------------- # gather alt base URIs for",
"resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time()",
"will be an InputSource source_isrc = None # list of InputSources for stylesheets",
"'The output file %s would be a directory.' % path elif os.path.isdir(path): msg",
"{} for d in defs: match = g_paramBindingPattern.match(d) if match is None: raise",
"= os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr # --",
"sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in e.message])) else:",
"base URIs (if any) until an InputSource is successfully created or the list",
"unexpected error occurred while processing.\\n' + \\ 'The error was: %s: %s\\n' %",
"options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr # -- Set up XSLT processor",
"defs = options.get('define', []) if not isinstance(defs, list): defs = [defs] top_level_params =",
"-- Prepare for any transform ------------------------------------- # source document will be an InputSource",
"the # 1st stylesheet in the case of --compile. It is never OK",
"'noxinclude', 'Do not expand XIncludes in source document and stylesheet'), Options.Option( None, 'trace',",
"sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output streams",
"RtfWriter to make each result be a Domlette document, # for speed, and",
"OK to have # zero args. For --reflex, there must be only one",
"argslen > 1: if options.has_key('reflex'): msg = 'When using --reflex, only 1 source/stylesheet",
"for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for",
"Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform --------------------------------- else: xinclude",
"Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace",
"None, 'trace-file=FILE', 'Trace file for execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option(",
"name = match.group(1) prefix, local = SplitQName(name) if prefix in nsmappings: name =",
"destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush() return # -- Prepare",
"+ \\ 'Use the -e (--stacktrace-on-error) option for a full stack trace.' if",
"SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath",
"Options.Option( None, 'compile', 'Compile an instant stylesheet. The result is written to' '",
"-------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try:",
"\\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(),",
"Domlette validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader",
"sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri)",
"tree (not the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc,",
"in prefixes: match = g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in -P/--prefix",
"None: raise TypeError('Error in -D/--define arguments') name = match.group(1) prefix, local = SplitQName(name)",
"will cache the doc in a reusable # stream in memory. stream =",
"if validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior",
"time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except",
"'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and",
"info.' % (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\"",
"= [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'):",
"%s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error) option for",
"hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest =",
"path.endswith(os.sep): msg = 'The trace file %s would be a directory.' % path",
"using --reflex, it is also the stylesheet.' ' If using --compile, it is",
"when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet as",
"doc normally, or the # source doc & stylesheet in the case of",
"uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile')",
"the one case that matters elif path.endswith(os.sep): msg = 'The trace file %s",
"arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if not isinstance(defs, list): defs",
"'ignore') or \"&#%d;\" % ord(c) for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000,",
"source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform ---------------------------------",
"else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile)",
"Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs",
"parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used in a",
"prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r',",
"for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE (file",
"and 1 stylesheet URI are required.' elif argslen < 3 and options.has_key('chain'): msg",
"% dest) sys.stderr.flush() return # -- Prepare for any transform ------------------------------------- # source",
"'\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle compile operation",
"except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be a compiled stylesheet object.'",
"trace file %s is a directory.' % path if msg: raise SystemExit('%s\\n See",
"of URIs is exhausted. \"\"\" isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'):",
"parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media",
"try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass",
"StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) #",
"path in (outputfile, outputfile_abspath): if not path: pass # we already handled the",
"start = time.time() i = 0 for sty_isrc in sty_chain[:-1]: i += 1",
"more. msg = '' argslen = len(arguments) if argslen != 2 and options.has_key('instant'):",
"or file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution",
"= '' if not outputfile and not tracefile: msg = 'When using --trace,",
"'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix",
"if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'):",
"reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if",
"= 'The output file %s is a directory.' % path for path in",
"NAME as project_name, VERSION as project_version, URL as project_url name = '4xslt' summary",
"directory.' % path elif os.path.isdir(path): msg = 'The trace file %s is a",
"a directory.' % path elif os.path.isdir(path): msg = 'The output file %s is",
"p in prefixes: match = g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in",
"in the case of --reflex, or the # 1st stylesheet in the case",
"import re, os, sys, traceback, cPickle, time from cStringIO import StringIO from Ft",
"= re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from",
"\\ 'The error was: %s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use the",
"= prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix =",
"import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH)",
"cache the doc in a reusable # stream in memory. stream = StringIO(isrc.read())",
"xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg",
"args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output streams (will die if",
"if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n',",
"tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor =",
"e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush()",
"error message. So we will cache the doc in a reusable # stream",
"import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern",
"for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break",
"'trace', 'Send execution trace output to stderr or file set by' ' --trace-file'),",
"elif os.path.isdir(path): msg = 'The trace file %s is a directory.' % path",
"c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype",
"suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle compile operation --------------------------------------",
"source document and stylesheet'), Options.Option( None, 'trace', 'Send execution trace output to stderr",
"% (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A",
"& column # won't show up # in the error message. So we",
"None, 'instant', 'The stylesheet is \"instant\" (compiled). Only one stylesheet' ' can be",
"prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix",
"Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE (file will be overwritten' '",
"top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"), Options.Option(",
"\\ NAME as project_name, VERSION as project_version, URL as project_url name = '4xslt'",
"variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris]",
"from the source argument, then the argument is resolved against alternative stylesheet base",
"cannot be created from the source argument, then the argument is resolved against",
"if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if",
"match = g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in -D/--define arguments') name",
"the error message. So we will cache the doc in a reusable #",
"used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses",
"must be exactly two. For --chain, three or more. msg = '' argslen",
"of absolute URIs is derived from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml",
"= None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name =",
"transformation result (-o or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None",
"validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader)",
"of the XML document to transform, or \"-\" to indicate' ' standard input.",
"try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and",
"alternative stylesheet base URIs (if any) until an InputSource is successfully created or",
"processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc =",
"!= list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths]",
"CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'):",
"' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace output when using",
"a namespace to a prefix used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH',",
"Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource",
"1 source document or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\" for",
"sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs)",
"checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\" out_file",
"column # won't show up # in the error message. So we will",
"# list of InputSources for stylesheets (only if chaining) sty_chain = None #",
"must specify an output' \\ ' file for the trace info (--trace-file) and/or'",
"isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass if not isrc: raise error",
"checktime: start = time.time() i = 0 for sty_isrc in sty_chain[:-1]: i +=",
"sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e,",
"for stylesheets (only if chaining) sty_chain = None # -- Prepare for reflexive",
"options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to",
"result (-o or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath",
"\"\"\" A wrapper for SourceArgToInputSource(). If an InputSource cannot be created from the",
"= 'The trace file %s would be a directory.' % path elif os.path.isdir(path):",
"= out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled",
"if match is None: raise TypeError('Error in -D/--define arguments') name = match.group(1) prefix,",
"not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0]",
"reusable # stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc =",
"isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception,",
"StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings()",
"1: if options.has_key('reflex'): msg = 'When using --reflex, only 1 source/stylesheet URI may",
"-o is used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled). Only one",
"a directory.' % path elif os.path.isdir(path): msg = 'The trace file %s is",
"for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format in",
"= not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg:",
"cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError(",
"kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error: if",
"be the source doc normally, or the # source doc & stylesheet in",
"SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in e.message])) else: if stacktrace_on_error:",
"sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory,",
"= Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None)",
"processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error)",
"= prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix =",
"by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace output when",
"source document for transforming with the second, and' ' so on). Without this",
"list of absolute URIs is derived from these sources: # 1. command-line option(s)",
"StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1: sty_chain =",
"-- Gather transformation-time options ---------------------------- # top-level params nsmappings = {} prefixes =",
"UriException): pass if not isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\"",
"trace and result output destinations must differ.' for path in (outputfile, outputfile_abspath): if",
"media prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) # register extension",
"line & column # won't show up # in the error message. So",
"if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when an error",
"case of --reflex, or the # 1st stylesheet in the case of --compile.",
"raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if",
"'\\t') processor.msgSuffix = suffix # -- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude",
"21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt' command (functions defined here are",
"stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype",
"%s\\n' % (exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error) option for a",
"'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'), ] def validate_options(self, options): if",
"streams (will die if files unwritable) ---------- # (assumes output destinations have been",
"stylesheet'), Options.Option( None, 'trace', 'Send execution trace output to stderr or file set",
"source document reader from Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag: reader",
"quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d'",
"or \"-\" to indicate' ' standard input. If using --reflex, it is also",
"except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ---------------------------- # top-level",
"msg = 'When using --instant, exactly 1 source doc URI and 1 stylesheet",
"out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet",
"Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI',",
"in a reusable # stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset()",
"ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e:",
"xsl:include/import resolution # # An ordered list of absolute URIs is derived from",
"# 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list:",
"stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error)",
"# 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment",
"--trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace output when using --trace'),",
"stylesheet written to %s.\\n' % dest) sys.stderr.flush() return # -- Prepare for any",
"processing.\\n' + \\ 'The error was: %s: %s\\n' % (exceptiontype, str(e)) + \\",
"\\ ' file for the trace info (--trace-file) and/or' \\ ' for the",
"% ord(c) for c in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error =",
"try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in",
"= time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True)",
"stylesheets (only if chaining) sty_chain = None # -- Prepare for reflexive transform",
"specified with this option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result of transforming",
"modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document",
"raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in msg])) else: sys.exit()",
"usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): #",
"import GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments",
"\"Define an add'l base URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct",
"Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used in a top-level",
"processor.appendStylesheetNode(), # but if there are XSLT errors, the line & column #",
"'Set media to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level",
"break except (OSError, UriException): pass if not isrc: raise error return isrc def",
"output file %s is a directory.' % path for path in (tracefile, tracefile_abspath):",
"for execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform",
"(result of transforming with the first' ' is the source document for transforming",
"] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document to",
"in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format in Python 2.3",
"options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain",
"previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset()",
"least 2 stylesheet URIs are required.' elif argslen > 1: if options.has_key('reflex'): msg",
"may be given.' elif arguments.values().count('-') > 1: msg = 'Standard input may be",
"for a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" %",
"being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set",
"None, 'chain', 'Chain the stylesheets (result of transforming with the first' ' is",
"and options.has_key('instant'): msg = 'When using --instant, exactly 1 source doc URI and",
"argslen = len(arguments) if argslen != 2 and options.has_key('instant'): msg = 'When using",
"--instant, exactly 1 source doc URI and 1 stylesheet URI are required.' elif",
"set up the source document reader from Ft.Xml import Domlette validate_flag = options.has_key('validate')",
"Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If",
"(--trace-file) and/or' \\ ' for the transformation result (-o or --outfile).' else: outputfile_abspath",
"# -- Set up output streams (will die if files unwritable) ---------- #",
"= 'When using --chain, 1 source doc URI and at least 2 stylesheet",
"CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri =",
"PI selection processor.mediaPref = options.get('media', None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\")",
"in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype =",
"the input to each chained stylesheet # is the previous transformation's result tree",
"processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs",
"one stylesheet' ' can be specified with this option.'), Options.Option( None, 'chain', 'Chain",
"doc and use processor.appendStylesheetNode(), # but if there are XSLT errors, the line",
"[alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris",
"'Suppress xsl:message output and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI",
"quiet=True) else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime:",
"' for the transformation result (-o or --outfile).' else: outputfile_abspath = outputfile and",
"StringIO from Ft import GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import",
"info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st",
"stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain')",
"A wrapper for SourceArgToInputSource(). If an InputSource cannot be created from the source",
"msg = 'When using --trace, you must specify an output' \\ ' file",
"URIs is exhausted. \"\"\" isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris",
"command (functions defined here are used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought,",
"the trace info (--trace-file) and/or' \\ ' for the transformation result (-o or",
"isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format in Python",
"stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg,",
"an output' \\ ' file for the trace info (--trace-file) and/or' \\ '",
"must be only one arg. For # --instant, there must be exactly two.",
"apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file')",
"--chain, 1 source doc URI and at least 2 stylesheet URIs are required.'",
"return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never returns.",
"is successfully created or the list of URIs is exhausted. \"\"\" isrc =",
"'\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix #",
"XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths",
"# (assumes output destinations have been checked for uniqueness) if options.has_key('compile'): output_flags =",
"DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ----------------------------",
"'The stylesheet is \"instant\" (compiled). Only one stylesheet' ' can be specified with",
"1st stylesheet in the case of --compile. It is never OK to have",
"or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile",
"options ---------------------------- # top-level params nsmappings = {} prefixes = options.get('prefix', []) if",
"list of InputSources for stylesheets (only if chaining) sty_chain = None # --",
"is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define',",
"(tracefile, tracefile_abspath): if not path: pass # we already handled the one case",
"processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media',",
"(use the stylesheet as the source' ' document).'), Options.Option( None, 'compile', 'Compile an",
"options = [ Options.Option( 'v', 'validate', 'Validate the input file as it is",
"\\ and open(options['trace-file'], 'w') or sys.stderr # -- Set up XSLT processor (without",
"an instant stylesheet. The result is written to' ' stdout, unless -o is",
"!= 2 and options.has_key('instant'): msg = 'When using --instant, exactly 1 source doc",
"given.' elif arguments.values().count('-') > 1: msg = 'Standard input may be used for",
"args. For --reflex, there must be only one arg. For # --instant, there",
"' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when an",
"stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append",
"against alternative stylesheet base URIs (if any) until an InputSource is successfully created",
"None, 'no-messages', 'Suppress xsl:message output and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri',",
"XML document to transform, or \"-\" to indicate' ' standard input. If using",
"is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to",
"sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name)",
"sty_chain = None # -- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude",
"for c in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') #",
"'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used in a top-level parameter'),",
"overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when",
"e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ---------------------------- # top-level params nsmappings",
"args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc",
"parse the doc and use processor.appendStylesheetNode(), # but if there are XSLT errors,",
"stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle",
"directory.' % path elif os.path.isdir(path): msg = 'The output file %s is a",
"trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet",
"top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used in",
"may be used for only 1 source document or stylesheet.' if msg: raise",
"'Reflexive transform (use the stylesheet as the source' ' document).'), Options.Option( None, 'compile',",
"unless -o is used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled). Only",
"parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"), Options.Option( None,",
"top-level params nsmappings = {} prefixes = options.get('prefix', []) if not isinstance(prefixes, list):",
"stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except",
"1 stylesheet URI are required.' elif argslen < 3 and options.has_key('chain'): msg =",
"= StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc,",
"this option, each extra stylesheet is' ' imported by the preceding one.'), ]),",
"or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath:",
"= {} prefixes = options.get('prefix', []) if not isinstance(prefixes, list): prefixes = [prefixes]",
"if chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for isrc in",
"from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml",
"Options.Option( None, 'time', 'Display the elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING',",
"file %s is a directory.' % path if msg: raise SystemExit('%s\\n See \"%s",
"%s is a directory.' % path for path in (tracefile, tracefile_abspath): if not",
"directory.' % path for path in (tracefile, tracefile_abspath): if not path: pass #",
"'Send execution trace output to stderr or file set by' ' --trace-file'), Options.Option(",
"an InputSource is successfully created or the list of URIs is exhausted. \"\"\"",
"= map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) >",
"-h\" for usage info.' % (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory,",
"# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/_4xslt.py,v 1.50.2.1 2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt'",
"chaining) sty_chain = None # -- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'):",
"Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file",
"= g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] =",
"'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor",
"not appear to be a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception,",
"# use RtfWriter to make each result be a Domlette document, # for",
"up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception,",
"is sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'): dest = out_file.name elif",
"source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to",
"is a directory.' % path for path in (tracefile, tracefile_abspath): if not path:",
"if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error:",
"'An unexpected error occurred while processing.\\n' + \\ 'The error was: %s: %s\\n'",
"source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could",
"Without this option, each extra stylesheet is' ' imported by the preceding one.'),",
"result output destinations must differ.' for path in (outputfile, outputfile_abspath): if not path:",
"e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform --------------------------------- else: xinclude =",
"--reflex, it is also the stylesheet.' ' If using --compile, it is the",
"directory.' % path if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.'",
"written to %s.\\n' % dest) sys.stderr.flush() return # -- Prepare for any transform",
"prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'):",
"# -- Gather transformation-time options ---------------------------- # top-level params nsmappings = {} prefixes",
"uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI for imports",
"in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if not isinstance(defs,",
"in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set",
"for speed, and so that the input to each chained stylesheet # is",
"------------------------------------- # source document will be an InputSource source_isrc = None # list",
"# source doc & stylesheet in the case of --reflex, or the #",
"transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri']",
"(nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore') checktime",
"elif argslen > 1: if options.has_key('reflex'): msg = 'When using --reflex, only 1",
"'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush() return # --",
"= factory.fromUri(new_uri) break except (OSError, UriException): pass if not isrc: raise error return",
"------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc =",
"outputfile_abspath): if not path: pass # we already handled the one case that",
"defs = [defs] top_level_params = {} for d in defs: match = g_paramBindingPattern.match(d)",
"documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle, time from cStringIO",
"% path elif os.path.isdir(path): msg = 'The trace file %s is a directory.'",
"(OSError, UriException): pass if not isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False):",
"used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license and",
"FILE (file will be overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display",
"Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions:",
"Formats various exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or \\",
"options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1)",
"chained stylesheet # is the previous transformation's result tree (not the # previous",
"2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt' command (functions defined here",
"trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name",
"= len(arguments) if argslen != 2 and options.has_key('instant'): msg = 'When using --instant,",
"as project_url name = '4xslt' summary = ('command-line tool for performing XSLT transformations",
"stylesheet. The result is written to' ' stdout, unless -o is used.'), Options.Option(",
"only one arg. For # --instant, there must be exactly two. For --chain,",
"isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris']",
"trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name",
"a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"),",
"be a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error)",
"\"\"\" Formats various exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or",
"as the source' ' document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet. The",
"StringIO() if checktime: start = time.time() i = 0 for sty_isrc in sty_chain[:-1]:",
"prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) # register extension modules",
"= '4xslt' summary = ('command-line tool for performing XSLT transformations on XML' 'documents')",
"flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # -- Do the transformation -----------------------------------------",
"\"-\" to indicate' ' standard input. If using --reflex, it is also the",
"SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return Run(options, arguments)",
"'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used in a top-level parameter'), Options.Option(",
"else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush()",
"message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix",
"to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option(",
"None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory,",
"prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix",
"MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name, VERSION as",
"isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc and",
"UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from",
"options.get('trace-file') msg = '' if not outputfile and not tracefile: msg = 'When",
"there must be exactly two. For --chain, three or more. msg = ''",
"if there are XSLT errors, the line & column # won't show up",
"is the source document for transforming with the second, and' ' so on).",
"args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris),",
"chain = options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args)",
"the input file as it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet",
"(not the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis,",
"'outfile=FILE', 'Direct transformation output to FILE (file will be overwritten' ' if it",
"open(options['outfile'], output_flags) or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name:",
"--reflex, there must be only one arg. For # --instant, there must be",
"also the stylesheet.' ' If using --compile, it is the stylesheet to compile.'),",
"1 source doc URI and at least 2 stylesheet URIs are required.' elif",
"gather alt base URIs for xsl:include/import resolution # # An ordered list of",
"None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', [])",
"if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or",
"path for path in (tracefile, tracefile_abspath): if not path: pass # we already",
"alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths =",
"sty_isrc in sty_chain[:-1]: i += 1 # FIXME: # use RtfWriter to make",
"'instant', 'The stylesheet is \"instant\" (compiled). Only one stylesheet' ' can be specified",
"output' \\ ' file for the trace info (--trace-file) and/or' \\ ' for",
"Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT",
"suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle compile",
"The result is written to' ' stdout, unless -o is used.'), Options.Option( None,",
"factory, *v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris:",
"# -- Prepare for regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant",
"raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in e.message])) else: if",
"= None # list of InputSources for stylesheets (only if chaining) sty_chain =",
"using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet as the",
"special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace",
"'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define",
"del more_sty_uris # tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements,",
"source doc normally, or the # source doc & stylesheet in the case",
"or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\"",
"' so on). Without this option, each extra stylesheet is' ' imported by",
"'source-uri', 'The URI of the XML document to transform, or \"-\" to indicate'",
"if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris)",
"---------------------------- # top-level params nsmappings = {} prefixes = options.get('prefix', []) if not",
"up # in the error message. So we will cache the doc in",
"% (exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error) option for a full",
"Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ---------------------------- # top-level params",
"differ.' for path in (outputfile, outputfile_abspath): if not path: pass # we already",
"and' ' so on). Without this option, each extra stylesheet is' ' imported",
"source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) #",
"for the transformation result (-o or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile)",
"more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris =",
"--chain, three or more. msg = '' argslen = len(arguments) if argslen !=",
"= [ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document to transform, or",
"= options.get('media', None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\"))",
"'w') or sys.stderr # -- Set up XSLT processor (without stylesheets) ------------------- #",
"-- Prepare for regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant =",
"expand XIncludes in source document and stylesheet'), Options.Option( None, 'trace', 'Send execution trace",
"msg = '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg",
"An ordered list of absolute URIs is derived from these sources: # 1.",
"OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires",
"(msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st arg ('source-uri')",
"stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in",
"sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name, VERSION as project_version,",
"it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s)",
"processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r',",
"= options.get('outfile') tracefile = options.get('trace-file') msg = '' if not outputfile and not",
"'Validate the input file as it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore",
"tool for performing XSLT transformations on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\"",
"description = \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate the",
"= Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1)",
"document reader from Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag: reader =",
"XSLT errors, the line & column # won't show up # in the",
"CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s",
"document and stylesheet'), Options.Option( None, 'trace', 'Send execution trace output to stderr or",
"' can be specified with this option.'), Options.Option( None, 'chain', 'Chain the stylesheets",
"(--stacktrace-on-error) option for a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or",
"stylesheets) ------------------- # gather alt base URIs for xsl:include/import resolution # # An",
"output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet",
"CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) #",
"stylesheets (result of transforming with the first' ' is the source document for",
"dest = 'standard output' elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest",
"quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try:",
"returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException):",
"URI are required.' elif argslen < 3 and options.has_key('chain'): msg = 'When using",
"except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try: if",
"the second, and' ' so on). Without this option, each extra stylesheet is'",
"# but if there are XSLT errors, the line & column # won't",
"if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in msg]))",
"(only if chaining) sty_chain = None # -- Prepare for reflexive transform -------------------------------",
"'stacktrace-on-error', 'Display a stack trace when an error occurs'), Options.Option( None, 'noxinclude', 'Do",
"stylesheet # is the previous transformation's result tree (not the # previous transformation's",
"(if any) until an InputSource is successfully created or the list of URIs",
"VERSION as project_version, URL as project_url name = '4xslt' summary = ('command-line tool",
"SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options",
"will be overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack",
"would be a directory.' % path elif os.path.isdir(path): msg = 'The trace file",
"each chained stylesheet # is the previous transformation's result tree (not the #",
"is derived from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line",
"msg = 'The trace and result output destinations must differ.' for path in",
"isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000,",
"of the stylesheet(s) to apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile =",
"project_name, VERSION as project_version, URL as project_url name = '4xslt' summary = ('command-line",
"(file will be overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a",
"only 1 source document or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\"",
"None, 'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind",
"using --instant, exactly 1 source doc URI and 1 stylesheet URI are required.'",
"See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def",
"SourceArgToInputSource(). If an InputSource cannot be created from the source argument, then the",
"indicate' ' standard input. If using --reflex, it is also the stylesheet.' '",
"= 0 for sty_isrc in sty_chain[:-1]: i += 1 # FIXME: # use",
"processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not",
"(will die if files unwritable) ---------- # (assumes output destinations have been checked",
"msg])) else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up",
"sys, traceback, cPickle, time from cStringIO import StringIO from Ft import GetConfigVars from",
"to each chained stylesheet # is the previous transformation's result tree (not the",
"\"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or",
"'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an",
"DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use",
"in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but uses OS",
"sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format in Python 2.3 and",
"# top-level params nsmappings = {} prefixes = options.get('prefix', []) if not isinstance(prefixes,",
"transform ------------------------------------- # source document will be an InputSource source_isrc = None #",
"sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush() return # -- Prepare for",
"cPickle, time from cStringIO import StringIO from Ft import GetConfigVars from Ft.Lib import",
"cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be a compiled stylesheet object.' %",
"if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True",
"= os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file')",
"stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for",
"# -- Prepare for any transform ------------------------------------- # source document will be an",
"Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor,",
"# use better pickle format in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'):",
"traceback, cPickle, time from cStringIO import StringIO from Ft import GetConfigVars from Ft.Lib",
"Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']]",
"transforming with the second, and' ' so on). Without this option, each extra",
"xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None, 'no-messages',",
"outputfile and not tracefile: msg = 'When using --trace, you must specify an",
"result is written to' ' stdout, unless -o is used.'), Options.Option( None, 'instant',",
"'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor in",
"% path elif os.path.isdir(path): msg = 'The output file %s is a directory.'",
"import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\")",
"you must specify an output' \\ ' file for the trace info (--trace-file)",
"from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import",
"(functions defined here are used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc.",
"input may be used for only 1 source document or stylesheet.' if msg:",
"# source document will be an InputSource source_isrc = None # list of",
"raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self,",
"out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr",
"the transformation ----------------------------------------- try: if source_isrc is None: raise TypeError('No source document to",
"msg = 'The trace file %s would be a directory.' % path elif",
"import Domlette validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader =",
"= [prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p) if match is None:",
"= \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file =",
"TypeError('No source document to transform!') if sty_chain: resultstream = StringIO() if checktime: start",
"if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r')",
"processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc and use processor.appendStylesheetNode(), # but",
"= Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'):",
"matters elif path.endswith(os.sep): msg = 'The output file %s would be a directory.'",
"resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream =",
"OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI for imports and",
"None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set",
"= args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc,",
"Domlette document, # for speed, and so that the input to each chained",
"options.has_key('stacktrace-on-error') # -- Set up output streams (will die if files unwritable) ----------",
"elif arguments.values().count('-') > 1: msg = 'Standard input may be used for only",
"jkloth Exp $ \"\"\" Implementation of '4xslt' command (functions defined here are used",
"error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never",
"output destinations must differ.' for path in (outputfile, outputfile_abspath): if not path: pass",
"StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True)",
"None # list of InputSources for stylesheets (only if chaining) sty_chain = None",
"= options.get('prefix', []) if not isinstance(prefixes, list): prefixes = [prefixes] for p in",
"local) top_level_params[name] = match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore') checktime =",
"use RtfWriter to make each result be a Domlette document, # for speed,",
"msg = '' argslen = len(arguments) if argslen != 2 and options.has_key('instant'): msg",
"'The trace and result output destinations must differ.' for path in (outputfile, outputfile_abspath):",
"# We could parse the doc and use processor.appendStylesheetNode(), # but if there",
"else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end",
"be a directory.' % path elif os.path.isdir(path): msg = 'The trace file %s",
"ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e,",
"ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest = 'standard output' elif",
"xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign",
"are XSLT errors, the line & column # won't show up # in",
"Set up output streams (will die if files unwritable) ---------- # (assumes output",
"[args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args)",
"never returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e,",
"re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__",
"= match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') #",
"i = 0 for sty_isrc in sty_chain[:-1]: i += 1 # FIXME: #",
"+= 1 # FIXME: # use RtfWriter to make each result be a",
"= cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError:",
"derived from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s)",
"output streams (will die if files unwritable) ---------- # (assumes output destinations have",
"(IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000 * (end -",
"e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest = 'standard output'",
"if files unwritable) ---------- # (assumes output destinations have been checked for uniqueness)",
"match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # --",
"topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri)",
"and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import re, os,",
"CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st arg ('source-uri') will be the",
"source doc URI and at least 2 stylesheet URIs are required.' elif argslen",
"the first' ' is the source document for transforming with the second, and'",
"1st arg ('source-uri') will be the source doc normally, or the # source",
"for path in (tracefile, tracefile_abspath): if not path: pass # we already handled",
"trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file =",
"file %s would be a directory.' % path elif os.path.isdir(path): msg = 'The",
"= not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris)",
"raise TypeError('No source document to transform!') if sty_chain: resultstream = StringIO() if checktime:",
"URI may be given.' elif arguments.values().count('-') > 1: msg = 'Standard input may",
"= [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths]",
"xsl:message output and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of",
"base URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to",
"the stylesheets (result of transforming with the first' ' is the source document",
"trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the",
"processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs else:",
"won't show up # in the error message. So we will cache the",
"options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile') \\ and",
"alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ]",
"raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit,",
"= options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file = None if options.has_key('trace'):",
"the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright information:",
"Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) #",
"transform (use the stylesheet as the source' ' document).'), Options.Option( None, 'compile', 'Compile",
"requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris)",
"pass if not isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats",
"attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1)",
"more_sty_uris # tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler",
"on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v',",
"nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime flags ignore_pis",
"= SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time",
"from Ft.__config__ import \\ NAME as project_name, VERSION as project_version, URL as project_url",
"os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\",
"stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'), ]",
"sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:]",
"= [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris),",
"Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try: if out_file.isatty():",
"[]) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if",
"URI of the XML document to transform, or \"-\" to indicate' ' standard",
"if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj",
"(assumes output destinations have been checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\"",
"prefixes = options.get('prefix', []) if not isinstance(prefixes, list): prefixes = [prefixes] for p",
"# won't show up # in the error message. So we will cache",
"= [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris #",
"command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if",
"2 and options.has_key('instant'): msg = 'When using --instant, exactly 1 source doc URI",
"processor.mediaPref = options.get('media', None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList:",
"input file as it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?>",
"an InputSource cannot be created from the source argument, then the argument is",
"g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import",
"trace file %s would be a directory.' % path elif os.path.isdir(path): msg =",
"unwritable) ---------- # (assumes output destinations have been checked for uniqueness) if options.has_key('compile'):",
"exhausted. \"\"\" isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris']",
"project_version, URL as project_url name = '4xslt' summary = ('command-line tool for performing",
"= suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle compile operation -------------------------------------- if",
"file %s is a directory.' % path for path in (tracefile, tracefile_abspath): if",
"For --reflex, there must be only one arg. For # --instant, there must",
"trace info (--trace-file) and/or' \\ ' for the transformation result (-o or --outfile).'",
"If using --reflex, it is also the stylesheet.' ' If using --compile, it",
"or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' %",
"'o', 'outfile=FILE', 'Direct transformation output to FILE (file will be overwritten' ' if",
"in (outputfile, outputfile_abspath): if not path: pass # we already handled the one",
"Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/",
"and not tracefile: msg = 'When using --trace, you must specify an output'",
"StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception,",
"not isinstance(defs, list): defs = [defs] top_level_params = {} for d in defs:",
"= prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix =",
"'standard output' elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest = options['outfile']",
"to a prefix used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as",
"trace output to stderr or file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE',",
"= True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) #",
"be used for only 1 source document or stylesheet.' if msg: raise SystemExit('%s\\n",
"stylesheet(s) to apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile",
"[prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p) if match is None: raise",
"not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg,",
"doc URI and at least 2 stylesheet URIs are required.' elif argslen >",
"can be specified with this option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result",
"created from the source argument, then the argument is resolved against alternative stylesheet",
"but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI for",
"options.has_key('ignore') checktime = options.has_key('time') # -- Do the transformation ----------------------------------------- try: if source_isrc",
"(outputfile, outputfile_abspath): if not path: pass # we already handled the one case",
"topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e,",
"XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr)",
"that matters elif path.endswith(os.sep): msg = 'The trace file %s would be a",
"= None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try:",
"options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message",
"Options.Option( None, 'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE',",
"for regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg",
"in source document and stylesheet'), Options.Option( None, 'trace', 'Send execution trace output to",
"For # --instant, there must be exactly two. For --chain, three or more.",
"= ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor",
"return # -- Prepare for any transform ------------------------------------- # source document will be",
"for xsl:include/import resolution # # An ordered list of absolute URIs is derived",
"'validate', 'Validate the input file as it is being parsed'), Options.Option( 'i', 'ignore',",
"name = '4xslt' summary = ('command-line tool for performing XSLT transformations on XML'",
"RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or",
"suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # --",
"= 'When using --reflex, only 1 source/stylesheet URI may be given.' elif arguments.values().count('-')",
"arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document to transform,",
"XSLT transformations on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options = [",
"%s would be a directory.' % path elif os.path.isdir(path): msg = 'The trace",
"# 1st arg ('source-uri') will be the source doc normally, or the #",
"stylesheet as the source' ' document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet.",
"handled the one case that matters elif path.endswith(os.sep): msg = 'The trace file",
"the case of --compile. It is never OK to have # zero args.",
"for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup.",
"any transform ------------------------------------- # source document will be an InputSource source_isrc = None",
"= options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path',",
"we already handled the one case that matters elif path.endswith(os.sep): msg = 'The",
"and so that the input to each chained stylesheet # is the previous",
"Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to",
"not tracefile: msg = 'When using --trace, you must specify an output' \\",
"not isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions;",
"\"&#%d;\" % ord(c) for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg",
"in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup. if options.has_key('trace'):",
"= args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude,",
"'Direct transformation output to FILE (file will be overwritten' ' if it exists)'),",
"from cStringIO import StringIO from Ft import GetConfigVars from Ft.Lib import UriException, CloseStream",
"Prepare for any transform ------------------------------------- # source document will be an InputSource source_isrc",
"from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as",
"sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" %",
"c in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # --",
"'The output file %s is a directory.' % path for path in (tracefile,",
"http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle, time from cStringIO import StringIO",
"processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader from Ft.Xml import Domlette validate_flag",
"use processor.appendStylesheetNode(), # but if there are XSLT errors, the line & column",
"InputSources for stylesheets (only if chaining) sty_chain = None # -- Prepare for",
"XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name, VERSION as project_version, URL as",
"not expand XIncludes in source document and stylesheet'), Options.Option( None, 'trace', 'Send execution",
"source document will be an InputSource source_isrc = None # list of InputSources",
"is' ' imported by the preceding one.'), ]), Options.Option( None, 'time', 'Display the",
"options.get('outfile') tracefile = options.get('trace-file') msg = '' if not outputfile and not tracefile:",
"stylesheet in the case of --compile. It is never OK to have #",
"memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc)",
"to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'), ] arguments",
"required.' elif argslen > 1: if options.has_key('reflex'): msg = 'When using --reflex, only",
"= kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError,",
"g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2)",
"defs: match = g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in -D/--define arguments')",
"'e', 'stacktrace-on-error', 'Display a stack trace when an error occurs'), Options.Option( None, 'noxinclude',",
"# misc runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # -- Do",
"be only one arg. For # --instant, there must be exactly two. For",
"but if there are XSLT errors, the line & column # won't show",
"prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix =",
"be an InputSource source_isrc = None # list of InputSources for stylesheets (only",
"Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI for imports and includes\"), Options.Option(",
"each result be a Domlette document, # for speed, and so that the",
"quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # --",
"path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI for imports and includes\"),",
"of '4xslt' command (functions defined here are used by the Ft.Lib.CommandLine framework) Copyright",
"os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg = 'The trace and result",
"'' if not outputfile and not tracefile: msg = 'When using --trace, you",
"using --reflex, only 1 source/stylesheet URI may be given.' elif arguments.values().count('-') > 1:",
"if sty_chain: resultstream = StringIO() if checktime: start = time.time() i = 0",
"ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING =",
"quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e,",
"from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import",
"out_file is sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'): dest = out_file.name",
"import \\ NAME as project_name, VERSION as project_version, URL as project_url name =",
"str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected error occurred while",
"= [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [",
"options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name:",
"os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr # -- Set",
"source doc URI and 1 stylesheet URI are required.' elif argslen < 3",
"\\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" %",
"for transforming with the second, and' ' so on). Without this option, each",
"at least 2 stylesheet URIs are required.' elif argslen > 1: if options.has_key('reflex'):",
"time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks",
"CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for",
"tracefile_abspath): if not path: pass # we already handled the one case that",
"arguments): # 1st arg ('source-uri') will be the source doc normally, or the",
"' file for the trace info (--trace-file) and/or' \\ ' for the transformation",
"a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c)",
"behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix =",
"= time.time() i = 0 for sty_isrc in sty_chain[:-1]: i += 1 #",
"1 source/stylesheet URI may be given.' elif arguments.values().count('-') > 1: msg = 'Standard",
"stylesheet is \"instant\" (compiled). Only one stylesheet' ' can be specified with this",
"that the input to each chained stylesheet # is the previous transformation's result",
"# -- Set up XSLT processor (without stylesheets) ------------------- # gather alt base",
"up XSLT processor (without stylesheets) ------------------- # gather alt base URIs for xsl:include/import",
"to have # zero args. For --reflex, there must be only one arg.",
"processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be a compiled stylesheet",
"= 'The trace and result output destinations must differ.' for path in (outputfile,",
"match.group(1) prefix, local = SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix], local)",
"stylesheet URI are required.' elif argslen < 3 and options.has_key('chain'): msg = 'When",
"processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if",
"del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for",
"[]) if not isinstance(defs, list): defs = [defs] top_level_params = {} for d",
"information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback,",
"SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris: for alt_uri in",
"import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name, VERSION",
"\"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file = None",
"options, arguments): # 1st arg ('source-uri') will be the source doc normally, or",
"Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string",
"path: pass # we already handled the one case that matters elif path.endswith(os.sep):",
"destinations must differ.' for path in (outputfile, outputfile_abspath): if not path: pass #",
"processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else:",
"for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else:",
"(without stylesheets) ------------------- # gather alt base URIs for xsl:include/import resolution # #",
"Exp $ \"\"\" Implementation of '4xslt' command (functions defined here are used by",
"\\ ' for the transformation result (-o or --outfile).' else: outputfile_abspath = outputfile",
"license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import re,",
"import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException",
"arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True)",
"source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather",
"None, 'noxinclude', 'Do not expand XIncludes in source document and stylesheet'), Options.Option( None,",
"import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from",
"the argument is resolved against alternative stylesheet base URIs (if any) until an",
"options.get('define', []) if not isinstance(defs, list): defs = [defs] top_level_params = {} for",
"for path in (outputfile, outputfile_abspath): if not path: pass # we already handled",
"from Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else:",
"and/or' \\ ' for the transformation result (-o or --outfile).' else: outputfile_abspath =",
"out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file = None if",
"except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest =",
"the source document reader from Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag:",
"--outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and",
"source_isrc = None # list of InputSources for stylesheets (only if chaining) sty_chain",
"StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc =",
"an error occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes in source document",
"Project home, documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle, time",
"'Trace file for execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex',",
"two. For --chain, three or more. msg = '' argslen = len(arguments) if",
"try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc",
"UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri)",
"' is the source document for transforming with the second, and' ' so",
"one.'), ]), Options.Option( None, 'time', 'Display the elapsed transformation time on stderr'), Options.Option(",
"options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t')",
"If an InputSource cannot be created from the source argument, then the argument",
"GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from",
"= StringIO() if checktime: start = time.time() i = 0 for sty_isrc in",
"'The trace file %s would be a directory.' % path elif os.path.isdir(path): msg",
"transform, or \"-\" to indicate' ' standard input. If using --reflex, it is",
"InputSource is successfully created or the list of URIs is exhausted. \"\"\" isrc",
"except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform --------------------------------- else:",
"def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg =",
"for SourceArgToInputSource(). If an InputSource cannot be created from the source argument, then",
"= str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected error occurred",
"suffix # -- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude')",
"previous transformation's result tree (not the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc)",
"to' ' stdout, unless -o is used.'), Options.Option( None, 'instant', 'The stylesheet is",
"case of --compile. It is never OK to have # zero args. For",
"try: if source_isrc is None: raise TypeError('No source document to transform!') if sty_chain:",
"isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises",
"more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris",
"else: out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000",
"or \"&#%d;\" % ord(c) for c in msg])) else: sys.exit() def Run(options, args):",
"<?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'),",
"= tracefile and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg = 'The",
"to stderr or file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file",
"try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris:",
"if options.has_key('reflex'): msg = 'When using --reflex, only 1 source/stylesheet URI may be",
"case that matters elif path.endswith(os.sep): msg = 'The output file %s would be",
"stylesheet base URIs (if any) until an InputSource is successfully created or the",
"'The error was: %s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use the -e",
"options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name =",
"does not appear to be a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except",
"Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri,",
"if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0]))",
"cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file,",
"= match.group(1) prefix, local = SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix],",
"None, 'time', 'Display the elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend",
"document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet. The result is written to'",
"be given.' elif arguments.values().count('-') > 1: msg = 'Standard input may be used",
"be overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace",
"is resolved against alternative stylesheet base URIs (if any) until an InputSource is",
"SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class",
"= SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be",
"already handled the one case that matters elif path.endswith(os.sep): msg = 'The trace",
"an InputSource source_isrc = None # list of InputSources for stylesheets (only if",
"the stylesheet(s) to apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile')",
"'' argslen = len(arguments) if argslen != 2 and options.has_key('instant'): msg = 'When",
"processor.msgSuffix = suffix # -- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude =",
"tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream",
"Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'), ] arguments = [ Arguments.RequiredArgument(",
"InputSource cannot be created from the source argument, then the argument is resolved",
"transform!') if sty_chain: resultstream = StringIO() if checktime: start = time.time() i =",
"using --chain, 1 source doc URI and at least 2 stylesheet URIs are",
"msg = 'The output file %s is a directory.' % path for path",
"if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected error occurred while processing.\\n'",
"transformation's result tree (not the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc,",
"= map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc)",
"% i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis,",
"source argument, then the argument is resolved against alternative stylesheet base URIs (if",
"honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P',",
"if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc =",
"len(arguments) if argslen != 2 and options.has_key('instant'): msg = 'When using --instant, exactly",
"topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start",
"error occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes in source document and",
"Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc,",
"options.has_key('reflex'): msg = 'When using --reflex, only 1 source/stylesheet URI may be given.'",
"Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt",
"transformation ----------------------------------------- try: if source_isrc is None: raise TypeError('No source document to transform!')",
"'Standard input may be used for only 1 source document or stylesheet.' if",
"source/stylesheet URI may be given.' elif arguments.values().count('-') > 1: msg = 'Standard input",
"Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled). Only one stylesheet' ' can",
"sty_chain: resultstream = StringIO() if checktime: start = time.time() i = 0 for",
"path if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg,",
"output and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of the",
"('source-uri') will be the source doc normally, or the # source doc &",
"format in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else:",
"# for speed, and so that the input to each chained stylesheet #",
"in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in",
"processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix =",
"msg = 'When using --chain, 1 source doc URI and at least 2",
"# register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up",
"object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri']",
"For --chain, three or more. msg = '' argslen = len(arguments) if argslen",
"for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except",
"already handled the one case that matters elif path.endswith(os.sep): msg = 'The output",
"'Display the elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to",
"alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep)",
"top_level_params = {} for d in defs: match = g_paramBindingPattern.match(d) if match is",
"resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream,",
"\"\"\" Implementation of '4xslt' command (functions defined here are used by the Ft.Lib.CommandLine",
"error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc",
"' imported by the preceding one.'), ]), Options.Option( None, 'time', 'Display the elapsed",
"Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'), ] def validate_options(self, options):",
"'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'),",
"if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name)",
"else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection processor.mediaPref =",
"processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris)",
"'name'): dest = out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown",
"full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for",
"instant = options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc",
"stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output streams (will die if files",
"is used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled). Only one stylesheet'",
"None, 'trace', 'Send execution trace output to stderr or file set by' '",
"ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime:",
"= sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg,",
"]), Options.Option( None, 'time', 'Display the elapsed transformation time on stderr'), Options.Option( None,",
"arg. For # --instant, there must be exactly two. For --chain, three or",
"\\ 'Use the -e (--stacktrace-on-error) option for a full stack trace.' if msg:",
"stacktrace_on_error) # -- Gather transformation-time options ---------------------------- # top-level params nsmappings = {}",
"is None: raise TypeError('Error in -D/--define arguments') name = match.group(1) prefix, local =",
"in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root,",
"in -D/--define arguments') name = match.group(1) prefix, local = SplitQName(name) if prefix in",
"If using --compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s)",
"xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) # register extension modules moduleList =",
"CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\")",
"processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' %",
"--compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the",
"URI(s) of the stylesheet(s) to apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile",
"processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better",
"URI and at least 2 stylesheet URIs are required.' elif argslen > 1:",
"outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if",
"quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does",
"' If using --compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The",
"# we already handled the one case that matters elif path.endswith(os.sep): msg =",
"sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3.",
"return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st arg ('source-uri') will be",
"URL as project_url name = '4xslt' summary = ('command-line tool for performing XSLT",
"2 stylesheet URIs are required.' elif argslen > 1: if options.has_key('reflex'): msg =",
"try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if checktime:",
"msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in msg])) else:",
"if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg = '' if not",
"dest = options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n'",
"----------------------------------------- try: if source_isrc is None: raise TypeError('No source document to transform!') if",
"not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) #",
"'Use the -e (--stacktrace-on-error) option for a full stack trace.' if msg: raise",
"= SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris: for alt_uri",
"isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris: for",
"have # zero args. For --reflex, there must be only one arg. For",
"and len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc)",
"if not isrc: raise error return isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various",
"URI and 1 stylesheet URI are required.' elif argslen < 3 and options.has_key('chain'):",
"stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc =",
"transforming with the first' ' is the source document for transforming with the",
"dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush() return",
"only 1 source/stylesheet URI may be given.' elif arguments.values().count('-') > 1: msg =",
"= \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate the input",
"stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException):",
"the # source doc & stylesheet in the case of --reflex, or the",
"is None: raise TypeError('No source document to transform!') if sty_chain: resultstream = StringIO()",
"absolute URIs is derived from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml #",
"' document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet. The result is written",
"the source doc normally, or the # source doc & stylesheet in the",
"SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) #",
"stack trace when an error occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes",
"% ord(c) for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg =",
"a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else:",
"pickle format in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL)",
"stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException)",
"SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options)",
"CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------",
"CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri",
"outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc",
"'alt-sty-uri=URI', \"Define an add'l base URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE',",
"if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end =",
"transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset()",
"tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass",
"xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude,",
"URIs is derived from these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2.",
"a prefix used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri",
"option for a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\"",
"if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path",
"import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource",
"d in defs: match = g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in",
"stdout, unless -o is used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled).",
"if chaining) sty_chain = None # -- Prepare for reflexive transform ------------------------------- if",
"and open(options['trace-file'], 'w') or sys.stderr # -- Set up XSLT processor (without stylesheets)",
"= factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass if not",
"--reflex, or the # 1st stylesheet in the case of --compile. It is",
"be specified with this option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result of",
"or the # 1st stylesheet in the case of --compile. It is never",
"transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc",
"the list of URIs is exhausted. \"\"\" isrc = None stylesheetAltUris = None",
"('command-line tool for performing XSLT transformations on XML' 'documents') description = \"\"\"4XSLT command-line",
"type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in",
"out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True)",
"StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc and use processor.appendStylesheetNode(),",
"1 source doc URI and 1 stylesheet URI are required.' elif argslen <",
"preceding one.'), ]), Options.Option( None, 'time', 'Display the elapsed transformation time on stderr'),",
"result tree (not the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True)",
"argslen < 3 and options.has_key('chain'): msg = 'When using --chain, 1 source doc",
"We could parse the doc and use processor.appendStylesheetNode(), # but if there are",
"misc runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # -- Do the",
"# is the previous transformation's result tree (not the # previous transformation's serialized",
"out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time:",
"CloseStream(isrc, quiet=True) # use better pickle format in Python 2.3 and up if",
"else: output_flags = \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout",
"1: sty_chain = sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc",
"to make each result be a Domlette document, # for speed, and so",
"= options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' %",
"sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc)",
"options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg = '' if not outputfile",
"out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\"",
"options) def run(self, options, arguments): # 1st arg ('source-uri') will be the source",
"arguments') name = match.group(1) prefix, local = SplitQName(name) if prefix in nsmappings: name",
"= match.group(2) defs = options.get('define', []) if not isinstance(defs, list): defs = [defs]",
"= exceptiontype[11:] msg = 'An unexpected error occurred while processing.\\n' + \\ 'The",
"to transform!') if sty_chain: resultstream = StringIO() if checktime: start = time.time() i",
"make each result be a Domlette document, # for speed, and so that",
"Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix",
"if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths)",
"factory.fromUri(new_uri) break except (OSError, UriException): pass if not isrc: raise error return isrc",
"...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'), Options.Option(",
"traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in e.message]))",
"in defs: match = g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in -D/--define",
"affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) # register extension modules moduleList",
"i += 1 # FIXME: # use RtfWriter to make each result be",
"trace when an error occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes in",
"None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to",
"outputfile = options.get('outfile') tracefile = options.get('trace-file') msg = '' if not outputfile and",
"[ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document to transform, or \"-\"",
"to be a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e,",
"= prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix",
"%s is a directory.' % path if msg: raise SystemExit('%s\\n See \"%s -h\"",
"argument, then the argument is resolved against alternative stylesheet base URIs (if any)",
"output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress",
"args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris)",
"is written to' ' stdout, unless -o is used.'), Options.Option( None, 'instant', 'The",
"Options.Option( None, 'noxinclude', 'Do not expand XIncludes in source document and stylesheet'), Options.Option(",
"exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected error",
"if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r')",
"= 'When using --trace, you must specify an output' \\ ' file for",
"prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime",
"been checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\"",
"XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft",
"Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from",
"StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI",
"PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a",
"source document to transform!') if sty_chain: resultstream = StringIO() if checktime: start =",
"setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace =",
"-- Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except",
"URIs (if any) until an InputSource is successfully created or the list of",
"%s would be a directory.' % path elif os.path.isdir(path): msg = 'The output",
"processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform",
"kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args)",
"prefix used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same as --alt-sty-uri but",
"checktime = options.has_key('time') # -- Do the transformation ----------------------------------------- try: if source_isrc is",
"namespace to a prefix used in a top-level parameter'), Options.Option( 'I', 'alt-sty-path=PATH', \"Same",
"option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris",
"factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an InputSource cannot be",
"for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments):",
"a directory.' % path for path in (tracefile, tracefile_abspath): if not path: pass",
"= args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse",
"the previous transformation's result tree (not the # previous transformation's serialized result tree)",
"path elif os.path.isdir(path): msg = 'The trace file %s is a directory.' %",
"output_flags = \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file",
"quiet=True) # use better pickle format in Python 2.3 and up if hasattr(cPickle,",
"reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try:",
"sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain =",
"outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start =",
"used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\" (compiled). Only one stylesheet' '",
"= None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg,",
"= time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation",
"= options.get('trace-file') msg = '' if not outputfile and not tracefile: msg =",
"if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs",
"open(options['trace-file'], 'w') or sys.stderr # -- Set up XSLT processor (without stylesheets) -------------------",
"second, and' ' so on). Without this option, each extra stylesheet is' '",
"or the # source doc & stylesheet in the case of --reflex, or",
"project_url name = '4xslt' summary = ('command-line tool for performing XSLT transformations on",
"file as it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'),",
"raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return Run(options,",
"compile operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] +",
"if not outputfile and not tracefile: msg = 'When using --trace, you must",
"these sources: # 1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml #",
"start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc,",
"extra stylesheet is' ' imported by the preceding one.'), ]), Options.Option( None, 'time',",
"Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest = 'standard",
"for the trace info (--trace-file) and/or' \\ ' for the transformation result (-o",
"> 1: if options.has_key('reflex'): msg = 'When using --reflex, only 1 source/stylesheet URI",
"that matters elif path.endswith(os.sep): msg = 'The output file %s would be a",
"= resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream",
"a reusable # stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc",
"arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an",
"'When using --chain, 1 source doc URI and at least 2 stylesheet URIs",
"'The URI of the XML document to transform, or \"-\" to indicate' '",
"specify an output' \\ ' file for the trace info (--trace-file) and/or' \\",
"######################################################################## # $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/_4xslt.py,v 1.50.2.1 2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of",
"2006 Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation,",
"msg = '' if not outputfile and not tracefile: msg = 'When using",
"3 and options.has_key('chain'): msg = 'When using --chain, 1 source doc URI and",
"e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs =",
"ReportFatalException(e, stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n')",
"> 1: msg = 'Standard input may be used for only 1 source",
"except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try:",
"elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest",
"summary = ('command-line tool for performing XSLT transformations on XML' 'documents') description =",
"import StringIO from Ft import GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine",
"= 'When using --instant, exactly 1 source doc URI and 1 stylesheet URI",
"up the source document reader from Ft.Xml import Domlette validate_flag = options.has_key('validate') if",
"resolved against alternative stylesheet base URIs (if any) until an InputSource is successfully",
"DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs",
"options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try:",
"$ \"\"\" Implementation of '4xslt' command (functions defined here are used by the",
"options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix",
"alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris =",
"if not isinstance(prefixes, list): prefixes = [prefixes] for p in prefixes: match =",
"Options.Option( 'v', 'validate', 'Validate the input file as it is being parsed'), Options.Option(",
"InputSource source_isrc = None # list of InputSources for stylesheets (only if chaining)",
"msg = 'When using --reflex, only 1 source/stylesheet URI may be given.' elif",
"if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) #",
"suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix",
"instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj =",
"# 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri',",
"the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'),",
"in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc",
"in (tracefile, tracefile_abspath): if not path: pass # we already handled the one",
"by the preceding one.'), ]), Options.Option( None, 'time', 'Display the elapsed transformation time",
"= 'Standard input may be used for only 1 source document or stylesheet.'",
"options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w')",
"elif options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written",
"if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args,",
"else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude)",
"options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t')",
"tracefile and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg = 'The trace",
"out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout:",
"output destinations have been checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else:",
"file for the trace info (--trace-file) and/or' \\ ' for the transformation result",
"prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n',",
"xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda",
"Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader",
"TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if not",
"os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if outputfile_abspath ==",
"'' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An",
"then the argument is resolved against alternative stylesheet base URIs (if any) until",
"= outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None",
"is also the stylesheet.' ' If using --compile, it is the stylesheet to",
"re, os, sys, traceback, cPickle, time from cStringIO import StringIO from Ft import",
"Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName",
"\"%s -h\" for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self,",
"transformations on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option(",
"imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE (file will",
"with the first' ' is the source document for transforming with the second,",
"media to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'),",
"prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix =",
"execution trace output to stderr or file set by' ' --trace-file'), Options.Option( None,",
"= StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except",
"= options.has_key('stacktrace-on-error') # -- Set up output streams (will die if files unwritable)",
"be a Domlette document, # for speed, and so that the input to",
"stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri)",
"= ('command-line tool for performing XSLT transformations on XML' 'documents') description = \"\"\"4XSLT",
"in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError,",
"[defs] top_level_params = {} for d in defs: match = g_paramBindingPattern.match(d) if match",
"'When using --instant, exactly 1 source doc URI and 1 stylesheet URI are",
"[ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing",
"'\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n')",
"handled the one case that matters elif path.endswith(os.sep): msg = 'The output file",
"compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args",
"'Display a stack trace when an error occurs'), Options.Option( None, 'noxinclude', 'Do not",
"URIs are required.' elif argslen > 1: if options.has_key('reflex'): msg = 'When using",
"of transforming with the first' ' is the source document for transforming with",
"sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs:",
"SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\",
"command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml",
"appear to be a compiled stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e:",
"source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory,",
"the one case that matters elif path.endswith(os.sep): msg = 'The output file %s",
"here are used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed",
"{} prefixes = options.get('prefix', []) if not isinstance(prefixes, list): prefixes = [prefixes] for",
"info (--trace-file) and/or' \\ ' for the transformation result (-o or --outfile).' else:",
"local = SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] =",
"the source argument, then the argument is resolved against alternative stylesheet base URIs",
"stacktrace_on_error) # -- Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else:",
"stylesheet.' ' If using --compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri',",
"'The URI(s) of the stylesheet(s) to apply.'), ] def validate_options(self, options): if options.has_key('trace'):",
"error occurred while processing.\\n' + \\ 'The error was: %s: %s\\n' % (exceptiontype,",
"stylesheetAltUris=alt_sty_uris) # We could parse the doc and use processor.appendStylesheetNode(), # but if",
"msg = 'An unexpected error occurred while processing.\\n' + \\ 'The error was:",
"*v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an InputSource cannot be created",
"--trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet as the source'",
"and options.has_key('chain'): msg = 'When using --chain, 1 source doc URI and at",
"'4xslt' command (functions defined here are used by the Ft.Lib.CommandLine framework) Copyright 2006",
"[]) if not isinstance(prefixes, list): prefixes = [prefixes] for p in prefixes: match",
"isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore')",
"# An ordered list of absolute URIs is derived from these sources: #",
"= options.has_key('time') # -- Do the transformation ----------------------------------------- try: if source_isrc is None:",
"could parse the doc and use processor.appendStylesheetNode(), # but if there are XSLT",
"alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass if not isrc: raise",
"Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern =",
"'%s does not appear to be a compiled stylesheet object.' % sty_arg), stacktrace_on_error)",
"'The trace file %s is a directory.' % path if msg: raise SystemExit('%s\\n",
"def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never returns. \"\"\" if",
"the elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message",
"sty_chain = sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc =",
"all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude,",
"and open(options['outfile'], output_flags) or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if",
"validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg = ''",
"1. command-line option(s) alt-sty-uri=../../foo.xml # 2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable",
"= [defs] top_level_params = {} for d in defs: match = g_paramBindingPattern.match(d) if",
"CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e:",
"= ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection",
"and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except",
"it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None,",
"None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output",
"del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException), error:",
"if out_file is sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'): dest =",
"prefixes: match = g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in -P/--prefix arguments')",
"end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis,",
"!= list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list:",
"if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader from Ft.Xml import",
"-- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args =",
"source' ' document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet. The result is",
"1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest",
"= options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'],",
"Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH",
"runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # -- Do the transformation",
"from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import",
"as it is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option(",
"this option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result of transforming with the",
"with the second, and' ' so on). Without this option, each extra stylesheet",
"% path for path in (tracefile, tracefile_abspath): if not path: pass # we",
"if options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile') \\",
"input. If using --reflex, it is also the stylesheet.' ' If using --compile,",
"stylesheet' ' can be specified with this option.'), Options.Option( None, 'chain', 'Chain the",
"# tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor",
"alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths =",
"nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if not isinstance(defs, list): defs =",
"os, sys, traceback, cPickle, time from cStringIO import StringIO from Ft import GetConfigVars",
"if prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc",
"using --compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of",
"--reflex, only 1 source/stylesheet URI may be given.' elif arguments.values().count('-') > 1: msg",
"arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1: sty_chain",
"Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace output when using --trace'), Options.ExclusiveOptions([",
"message. So we will cache the doc in a reusable # stream in",
"'documents') description = \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate",
"' stdout, unless -o is used.'), Options.Option( None, 'instant', 'The stylesheet is \"instant\"",
"= options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t',",
"regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg =",
"Gather transformation-time options ---------------------------- # top-level params nsmappings = {} prefixes = options.get('prefix',",
"document, # for speed, and so that the input to each chained stylesheet",
"the doc in a reusable # stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc,",
"else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0)",
"and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML",
"while processing.\\n' + \\ 'The error was: %s: %s\\n' % (exceptiontype, str(e)) +",
"= options.get('define', []) if not isinstance(defs, list): defs = [defs] top_level_params = {}",
"an add'l base URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation",
"from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import",
"on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING',",
"a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a prefix used",
"Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message",
"'When using --reflex, only 1 source/stylesheet URI may be given.' elif arguments.values().count('-') >",
"by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright",
"msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return",
"& stylesheet in the case of --reflex, or the # 1st stylesheet in",
"outputfile_abspath == tracefile_abspath: msg = 'The trace and result output destinations must differ.'",
"1: msg = 'Standard input may be used for only 1 source document",
"Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import",
"if not path: pass # we already handled the one case that matters",
"application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate the input file as it",
"or None if outputfile_abspath == tracefile_abspath: msg = 'The trace and result output",
"% (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st arg",
"stylesheet URIs are required.' elif argslen > 1: if options.has_key('reflex'): msg = 'When",
"% sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain",
"until an InputSource is successfully created or the list of URIs is exhausted.",
"# 1st stylesheet in the case of --compile. It is never OK to",
"for sty_isrc in sty_chain[:-1]: i += 1 # FIXME: # use RtfWriter to",
"elif path.endswith(os.sep): msg = 'The output file %s would be a directory.' %",
"# in the error message. So we will cache the doc in a",
"warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document",
"$Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/_4xslt.py,v 1.50.2.1 2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt' command",
"match is None: raise TypeError('Error in -D/--define arguments') name = match.group(1) prefix, local",
"written to' ' stdout, unless -o is used.'), Options.Option( None, 'instant', 'The stylesheet",
"# -- Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close()",
"os.path.isdir(path): msg = 'The output file %s is a directory.' % path for",
"Handle post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError,",
"stacktrace_on_error) # -- Prepare for regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude')",
"processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else:",
"= isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # --",
"-- Set up XSLT processor (without stylesheets) ------------------- # gather alt base URIs",
"ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect xsl:stylesheet PI selection processor.mediaPref",
"'v', 'validate', 'Validate the input file as it is being parsed'), Options.Option( 'i',",
"= 'The output file %s would be a directory.' % path elif os.path.isdir(path):",
"from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil",
"out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr #",
"= suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle",
"for performing XSLT transformations on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options",
"better pickle format in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file,",
"various exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e,",
"a stack trace when an error occurs'), Options.Option( None, 'noxinclude', 'Do not expand",
"if outputfile_abspath == tracefile_abspath: msg = 'The trace and result output destinations must",
"as project_version, URL as project_url name = '4xslt' summary = ('command-line tool for",
"# set up the source document reader from Ft.Xml import Domlette validate_flag =",
"the line & column # won't show up # in the error message.",
"\"instant\" (compiled). Only one stylesheet' ' can be specified with this option.'), Options.Option(",
"Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home,",
"there must be only one arg. For # --instant, there must be exactly",
"OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from",
"None, 'alt-sty-uri=URI', \"Define an add'l base URI for imports and includes\"), Options.Option( 'o',",
"= 'An unexpected error occurred while processing.\\n' + \\ 'The error was: %s:",
"= options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr # -- Set up XSLT",
"Only one stylesheet' ' can be specified with this option.'), Options.Option( None, 'chain',",
"Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file,",
"g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp):",
"stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is sys.stdout: dest = 'standard output' elif hasattr(out_file,",
"post-transformation tasks ------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError):",
"= suffix # -- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude = not",
"of --compile. It is never OK to have # zero args. For --reflex,",
"top_level_params[name] = match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore') checktime = options.has_key('time')",
"each extra stylesheet is' ' imported by the preceding one.'), ]), Options.Option( None,",
"-h\" for usage info.' % (msg, sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options,",
"compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'), ] def validate_options(self,",
"the source document for transforming with the second, and' ' so on). Without",
"Arguments.RequiredArgument( 'source-uri', 'The URI of the XML document to transform, or \"-\" to",
"ord(c) for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = ''",
"DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml",
"exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected error occurred while processing.\\n' +",
"1.50.2.1 2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt' command (functions defined",
"usage info.' % (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args):",
"three or more. msg = '' argslen = len(arguments) if argslen != 2",
"show up # in the error message. So we will cache the doc",
"exactly 1 source doc URI and 1 stylesheet URI are required.' elif argslen",
"outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or",
"= 'The trace file %s is a directory.' % path if msg: raise",
"/var/local/cvsroot/4Suite/Ft/Xml/Xslt/_4xslt.py,v 1.50.2.1 2006/10/16 21:52:39 jkloth Exp $ \"\"\" Implementation of '4xslt' command (functions",
"attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special",
"resolution # # An ordered list of absolute URIs is derived from these",
"output file %s would be a directory.' % path elif os.path.isdir(path): msg =",
"file for execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive",
"option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result of transforming with the first'",
"= \"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'], output_flags)",
"= None # -- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude =",
"in the error message. So we will cache the doc in a reusable",
"Ft import GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp, Options,",
"(OSError, UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg,",
"'compile', 'Compile an instant stylesheet. The result is written to' ' stdout, unless",
"so on). Without this option, each extra stylesheet is' ' imported by the",
"It is never OK to have # zero args. For --reflex, there must",
"for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags = \"w\" out_file =",
"nsmappings = {} prefixes = options.get('prefix', []) if not isinstance(prefixes, list): prefixes =",
"out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000 *",
"Options.Option( None, 'trace', 'Send execution trace output to stderr or file set by'",
"processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix",
"# zero args. For --reflex, there must be only one arg. For #",
"None, 'compile', 'Compile an instant stylesheet. The result is written to' ' stdout,",
"\"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if",
"= (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime flags ignore_pis = options.has_key('ignore')",
"options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix",
"options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg = '' if",
"performing XSLT transformations on XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options =",
"XSLT processor (without stylesheets) ------------------- # gather alt base URIs for xsl:include/import resolution",
"alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) !=",
"else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if instant:",
"would be a directory.' % path elif os.path.isdir(path): msg = 'The output file",
"'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to",
"------------------------------ try: if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if",
"Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet as the source' ' document).'),",
"new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO()",
"os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup. if options.has_key('trace'): from",
"os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader from Ft.Xml",
"(USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\"",
"else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type) if",
"the source' ' document).'), Options.Option( None, 'compile', 'Compile an instant stylesheet. The result",
"output' elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest = options['outfile'] else:",
"the -e (--stacktrace-on-error) option for a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(),",
"= options.has_key('ignore') checktime = options.has_key('time') # -- Do the transformation ----------------------------------------- try: if",
"CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from",
"is never OK to have # zero args. For --reflex, there must be",
"includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE (file will be overwritten'",
"result be a Domlette document, # for speed, and so that the input",
"source_isrc is None: raise TypeError('No source document to transform!') if sty_chain: resultstream =",
"zero args. For --reflex, there must be only one arg. For # --instant,",
"#Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix']",
"sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri)",
"end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Handle",
"for p in prefixes: match = g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error",
"type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) !=",
"stderr or file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for",
"occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes in source document and stylesheet'),",
"'Compile an instant stylesheet. The result is written to' ' stdout, unless -o",
"e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type)",
"is \"instant\" (compiled). Only one stylesheet' ' can be specified with this option.'),",
"0 for sty_isrc in sty_chain[:-1]: i += 1 # FIXME: # use RtfWriter",
"path in (tracefile, tracefile_abspath): if not path: pass # we already handled the",
"resultstream = StringIO() if checktime: start = time.time() i = 0 for sty_isrc",
"stylesheet is' ' imported by the preceding one.'), ]), Options.Option( None, 'time', 'Display",
"os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del",
"1 # FIXME: # use RtfWriter to make each result be a Domlette",
"or the list of URIs is exhausted. \"\"\" isrc = None stylesheetAltUris =",
"output to stderr or file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace",
"'Assign a namespace to a prefix used in a top-level parameter'), Options.Option( 'I',",
"selection processor.mediaPref = options.get('media', None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\") if",
"options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', [])",
"= [ Options.Option( 'v', 'validate', 'Validate the input file as it is being",
"\"%s -h\" for usage info.' % (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg,",
"elif os.path.isdir(path): msg = 'The output file %s is a directory.' % path",
"match = g_prefixBindingPattern.match(p) if match is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)]",
"and os.path.abspath(outputfile) or None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if outputfile_abspath",
"= SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2)",
"+ args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for",
"except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000 * (end",
"and result output destinations must differ.' for path in (outputfile, outputfile_abspath): if not",
"raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException) or",
"be a directory.' % path elif os.path.isdir(path): msg = 'The output file %s",
"return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource().",
"stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda arg:",
"# FIXME: # use RtfWriter to make each result be a Domlette document,",
"-D/--define arguments') name = match.group(1) prefix, local = SplitQName(name) if prefix in nsmappings:",
"not path: pass # we already handled the one case that matters elif",
"Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg =",
"or \\ isinstance(e, RuntimeException) or \\ isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise",
"= StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc",
"it is also the stylesheet.' ' If using --compile, it is the stylesheet",
"'time', 'Display the elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string",
"None: raise TypeError('No source document to transform!') if sty_chain: resultstream = StringIO() if",
"refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear",
"See \"%s -h\" for usage info.' % (msg, sys.argv[0])) return Run(options, arguments) def",
"isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular",
"\"\"\" isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del",
"Prepare for regular transform --------------------------------- else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant')",
"CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if",
"exceptions; raises SystemExit, never returns. \"\"\" if isinstance(e, XsltException) or \\ isinstance(e, RuntimeException)",
"in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI',",
"match.group(2) defs = options.get('define', []) if not isinstance(defs, list): defs = [defs] top_level_params",
"never OK to have # zero args. For --reflex, there must be only",
"(-o or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or None tracefile_abspath =",
"ignore_pis = options.has_key('ignore') checktime = options.has_key('time') # -- Do the transformation ----------------------------------------- try:",
"if source_isrc is None: raise TypeError('No source document to transform!') if sty_chain: resultstream",
"except (OSError, UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri =",
"factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass if not isrc:",
"**kw_args) except (OSError, UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try: new_uri",
"else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output",
"else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg = 'An unexpected",
"prefixes = [prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p) if match is",
"'4xslt' summary = ('command-line tool for performing XSLT transformations on XML' 'documents') description",
"source document or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\" for usage",
"will be the source doc normally, or the # source doc & stylesheet",
"for only 1 source document or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s",
"'\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if",
"stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del",
"suffix.replace('\\\\t', '\\t') processor.msgSuffix = suffix # -- Handle compile operation -------------------------------------- if options.has_key('compile'):",
"'\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix if options.has_key('msg-suffix'): suffix = options['msg-suffix']",
"len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc,",
"source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end",
"as --alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base",
"\"\"\" import re, os, sys, traceback, cPickle, time from cStringIO import StringIO from",
"isinstance(defs, list): defs = [defs] top_level_params = {} for d in defs: match",
"# -- Do the transformation ----------------------------------------- try: if source_isrc is None: raise TypeError('No",
"\"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate the input file",
"was: %s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error) option",
"errors, the line & column # won't show up # in the error",
"'Do not expand XIncludes in source document and stylesheet'), Options.Option( None, 'trace', 'Send",
"stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude)",
"options.has_key('time') # -- Do the transformation ----------------------------------------- try: if source_isrc is None: raise",
"2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1)",
"cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file is",
"sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except",
"= options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize",
"isinstance(e, CompiletimeException): if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c)",
"ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor =",
"checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error) # --",
"http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle,",
"defined here are used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA).",
"document will be an InputSource source_isrc = None # list of InputSources for",
"Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output streams (will die",
"True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media",
"from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream =",
"Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException,",
"kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc = SourceArgToInputSource(arg, factory, *v_args, **kw_args) except (OSError, UriException),",
"instant stylesheet. The result is written to' ' stdout, unless -o is used.'),",
"to %s.\\n' % dest) sys.stderr.flush() return # -- Prepare for any transform -------------------------------------",
"the stylesheet as the source' ' document).'), Options.Option( None, 'compile', 'Compile an instant",
"one arg. For # --instant, there must be exactly two. For --chain, three",
"Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name,",
"# -- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude')",
"exceptiontype[11:] msg = 'An unexpected error occurred while processing.\\n' + \\ 'The error",
"validate_flag: reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if",
"moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader",
"exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when an error occurs'), Options.Option(",
"= suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix =",
"input to each chained stylesheet # is the previous transformation's result tree (not",
"option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris)",
"argslen != 2 and options.has_key('instant'): msg = 'When using --instant, exactly 1 source",
"= trace_file StylesheetHandler._ELEMENT_MAPPING = ExtendedProcessingElements.GetMappings() else: processor = Processor.Processor(stylesheetAltUris=alt_sty_uris) # media prefs affect",
"in the case of --compile. It is never OK to have # zero",
"Implementation of '4xslt' command (functions defined here are used by the Ft.Lib.CommandLine framework)",
"= time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params,",
"DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg,",
"match is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs =",
"(msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper",
"document to transform, or \"-\" to indicate' ' standard input. If using --reflex,",
"sys.argv[0])) return CommandLineApp.CommandLineApp.validate_options(self, options) def run(self, options, arguments): # 1st arg ('source-uri') will",
"\\ and open(options['outfile'], output_flags) or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file')",
"normally, or the # source doc & stylesheet in the case of --reflex,",
"traceback.print_exc(1000, sys.stderr) msg = '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype =",
"the # previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params,",
"None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris = kw_args['stylesheetAltUris'] del kw_args['stylesheetAltUris'] try: isrc",
"if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e:",
"the transformation result (-o or --outfile).' else: outputfile_abspath = outputfile and os.path.abspath(outputfile) or",
"sty_chain[:-1]: i += 1 # FIXME: # use RtfWriter to make each result",
"copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys,",
"when an error occurs'), Options.Option( None, 'noxinclude', 'Do not expand XIncludes in source",
"it exists)'), Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when an error occurs'),",
"from Ft import GetConfigVars from Ft.Lib import UriException, CloseStream from Ft.Lib.CommandLine import CommandLineApp,",
"= options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t',",
"DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be a compiled",
"Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory",
"alt base URIs for xsl:include/import resolution # # An ordered list of absolute",
"cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if",
"SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in msg])) else: sys.exit() def",
"to compile.'), Arguments.ZeroOrMoreArgument( 'stylesheet-uri', 'The URI(s) of the stylesheet(s) to apply.'), ] def",
"to FILE (file will be overwritten' ' if it exists)'), Options.Option( 'e', 'stacktrace-on-error',",
"\"Same as --alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l",
"--trace, you must specify an output' \\ ' file for the trace info",
"'When using --trace, you must specify an output' \\ ' file for the",
"transformation output to FILE (file will be overwritten' ' if it exists)'), Options.Option(",
"register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the",
"= {} for d in defs: match = g_paramBindingPattern.match(d) if match is None:",
"Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'): processor.messageControl(1) else:",
"output to FILE (file will be overwritten' ' if it exists)'), Options.Option( 'e',",
"transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option(",
"environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris =",
"else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error) CloseStream(out_file, quiet=True) if out_file",
"# -- Handle compile operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args",
"argument is resolved against alternative stylesheet base URIs (if any) until an InputSource",
"we will cache the doc in a reusable # stream in memory. stream",
"--instant, there must be exactly two. For --chain, three or more. msg =",
"XIncludes in source document and stylesheet'), Options.Option( None, 'trace', 'Send execution trace output",
"isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset() except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Prepare",
"< 3 and options.has_key('chain'): msg = 'When using --chain, 1 source doc URI",
"hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e,",
"error was: %s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error)",
"os.path.isdir(path): msg = 'The trace file %s is a directory.' % path if",
"time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file)",
"raise TypeError('Error in -D/--define arguments') name = match.group(1) prefix, local = SplitQName(name) if",
"import InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException",
"------------------- # gather alt base URIs for xsl:include/import resolution # # An ordered",
"== tracefile_abspath: msg = 'The trace and result output destinations must differ.' for",
"--compile. It is never OK to have # zero args. For --reflex, there",
"(exceptiontype, str(e)) + \\ 'Use the -e (--stacktrace-on-error) option for a full stack",
"in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except Exception, e:",
"doc & stylesheet in the case of --reflex, or the # 1st stylesheet",
"None tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg",
"add'l base URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output",
"up output streams (will die if files unwritable) ---------- # (assumes output destinations",
"Ft.__config__ import \\ NAME as project_name, VERSION as project_version, URL as project_url name",
"base URIs for xsl:include/import resolution # # An ordered list of absolute URIs",
"trace_file = options.has_key('trace-file') \\ and open(options['trace-file'], 'w') or sys.stderr # -- Set up",
"moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader from Ft.Xml import Domlette",
"= 'standard output' elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'): dest =",
"and use processor.appendStylesheetNode(), # but if there are XSLT errors, the line &",
"or \"&#%d;\" % ord(c) for c in e.message])) else: if stacktrace_on_error: traceback.print_exc(1000, sys.stderr)",
"= source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime:",
"checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time() processor.run(source_isrc,",
"execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use",
"pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000 * (end - start))) return",
"exceptiontype = exceptiontype[11:] msg = 'An unexpected error occurred while processing.\\n' + \\",
"XML' 'documents') description = \"\"\"4XSLT command-line application\"\"\" options = [ Options.Option( 'v', 'validate',",
"None if outputfile_abspath == tracefile_abspath: msg = 'The trace and result output destinations",
"processor (without stylesheets) ------------------- # gather alt base URIs for xsl:include/import resolution #",
"checktime: start = time.time() processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time()",
"suffix = options['msg-suffix'] suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix =",
"Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import",
"to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option( None,",
"2. command-line option(s) alt-sty-path=C:\\foo.xml # 3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', [])",
"arg ('source-uri') will be the source doc normally, or the # source doc",
"--------------------------------- else: xinclude = not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if",
"document for transforming with the second, and' ' so on). Without this option,",
"else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix =",
"stylesheet in the case of --reflex, or the # 1st stylesheet in the",
"option, each extra stylesheet is' ' imported by the preceding one.'), ]), Options.Option(",
"3. environment variable XSLTINCLUDE=\\a\\b\\foo.xml alt_sty_uris = options.get('alt-sty-uri', []) if type(alt_sty_uris) != list: alt_sty_uris",
"str(e)) + \\ 'Use the -e (--stacktrace-on-error) option for a full stack trace.'",
"sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory,",
"# media prefs affect xsl:stylesheet PI selection processor.mediaPref = options.get('media', None) # register",
"DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc and use processor.appendStylesheetNode(), #",
"to indicate' ' standard input. If using --reflex, it is also the stylesheet.'",
"tracefile: msg = 'When using --trace, you must specify an output' \\ '",
"instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'), Options.Option( 'D',",
"with this option.'), Options.Option( None, 'chain', 'Chain the stylesheets (result of transforming with",
"msg = 'The trace file %s is a directory.' % path if msg:",
"= g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in -D/--define arguments') name =",
"path in os.environ[\"XSLTINCLUDE\"].split(os.pathsep) ] alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup. if",
"trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file",
"the doc and use processor.appendStylesheetNode(), # but if there are XSLT errors, the",
"alt_uri in stylesheetAltUris: try: new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except",
"None, 'reflex', 'Reflexive transform (use the stylesheet as the source' ' document).'), Options.Option(",
"ReportFatalException(ValueError( '%s does not appear to be a compiled stylesheet object.' % sty_arg),",
"'reflex', 'Reflexive transform (use the stylesheet as the source' ' document).'), Options.Option( None,",
"outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception, e: ReportFatalException(e, stacktrace_on_error)",
"RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern =",
"[]) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for",
"[OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path,",
"is being parsed'), Options.Option( 'i', 'ignore', 'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA',",
"time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None,",
"if match is None: raise TypeError('Error in -P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs",
"prefix.replace('\\\\n', '\\n') prefix = prefix.replace('\\\\r', '\\r') prefix = prefix.replace('\\\\t', '\\t') processor.msgPrefix = prefix",
"'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root, out_file, cPickle.HIGHEST_PROTOCOL) else: cPickle.dump(processor.stylesheet.root, out_file, 1) except Exception, e: ReportFatalException(e, stacktrace_on_error)",
"from Ft.Lib.CommandLine import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import",
"map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if chain and len(sty_isrcs) > 1:",
"quiet=True) if out_file is sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'): dest",
"from Ft.Xml.Xslt import Processor, XsltException from Ft.Xml import SplitQName g_paramBindingPattern = re.compile(r\"([\\d\\D_\\.\\-]*:?[\\d\\D_\\.\\-]+)=(.*)\") g_prefixBindingPattern",
"string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'), ]",
"dest) sys.stderr.flush() return # -- Prepare for any transform ------------------------------------- # source document",
"one case that matters elif path.endswith(os.sep): msg = 'The trace file %s would",
"cStringIO import StringIO from Ft import GetConfigVars from Ft.Lib import UriException, CloseStream from",
"import CommandLineApp, Options, Arguments from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize",
"the XML document to transform, or \"-\" to indicate' ' standard input. If",
"exactly two. For --chain, three or more. msg = '' argslen = len(arguments)",
"msg = 'The output file %s would be a directory.' % path elif",
"[alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris",
"ord(c) for c in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error')",
"+ \\ 'The error was: %s: %s\\n' % (exceptiontype, str(e)) + \\ 'Use",
"options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We",
"Options.Option( 'e', 'stacktrace-on-error', 'Display a stack trace when an error occurs'), Options.Option( None,",
"args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the",
"output_flags) or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name",
"trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c in",
"map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc,",
"list: alt_sty_uris = [alt_sty_uris] alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths",
"imported by the preceding one.'), ]), Options.Option( None, 'time', 'Display the elapsed transformation",
"options.has_key('outfile') \\ and open(options['outfile'], output_flags) or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name=",
"Options.Option( None, 'chain', 'Chain the stylesheets (result of transforming with the first' '",
"tracefile = options.get('trace-file') msg = '' if not outputfile and not tracefile: msg",
"are used by the Ft.Lib.CommandLine framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license",
"= options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path,",
"any) until an InputSource is successfully created or the list of URIs is",
"= options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc =",
"So we will cache the doc in a reusable # stream in memory.",
"or sys.stdout trace_file = None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name =",
"if out_file.isatty(): out_file.flush() sys.stderr.write('\\n') else: out_file.close() except (IOError, ValueError): pass if checktime: sys.stderr.write(\"Transformation",
"= not options.has_key('noxinclude') instant = options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg =",
"alt_sty_paths = [alt_sty_paths] more_sty_uris = [OsPathToUri(path, attemptAbsolute=1) for path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if",
"time.time() i = 0 for sty_isrc in sty_chain[:-1]: i += 1 # FIXME:",
"\"&#%d;\" % ord(c) for c in msg])) else: sys.exit() def Run(options, args): stacktrace_on_error",
"tracefile_abspath: msg = 'The trace and result output destinations must differ.' for path",
"source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if",
"out_file_name = options.get('outfile') if out_file_name: out_file_name = os.path.abspath(out_file_name) trace_file = options.has_key('trace-file') \\ and",
"successfully created or the list of URIs is exhausted. \"\"\" isrc = None",
"options.has_key('chain'): msg = 'When using --chain, 1 source doc URI and at least",
"'Append string to xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'),",
"> 1: sty_chain = sty_isrcs else: for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True)",
"' standard input. If using --reflex, it is also the stylesheet.' ' If",
"be created from the source argument, then the argument is resolved against alternative",
"ReportFatalException(e, stacktrace_on_error) else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda",
"options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs =",
"# gather alt base URIs for xsl:include/import resolution # # An ordered list",
"options.get('media', None) # register extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) #",
"Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ \"\"\" import",
"stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c",
"standard input. If using --reflex, it is also the stylesheet.' ' If using",
"None # -- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not",
"suffix = suffix.replace('\\\\n', '\\n') suffix = suffix.replace('\\\\r', '\\r') suffix = suffix.replace('\\\\t', '\\t') processor.msgSuffix",
"tracefile_abspath = tracefile and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg =",
"alt_sty_uris.extend(more_sty_uris) del more_sty_uris # tracing requires special setup. if options.has_key('trace'): from Ft.Xml.Xslt import",
"is the previous transformation's result tree (not the # previous transformation's serialized result",
"re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME",
"new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end =",
"--alt-sty-uri but uses OS path\"), Options.Option( None, 'alt-sty-uri=URI', \"Define an add'l base URI",
"list of URIs is exhausted. \"\"\" isrc = None stylesheetAltUris = None if",
"one case that matters elif path.endswith(os.sep): msg = 'The output file %s would",
"and at least 2 stylesheet URIs are required.' elif argslen > 1: if",
"InputSourceFactory, DefaultFactory from Ft.Xml.XPath import RuntimeException, CompiletimeException from Ft.Xml.Xslt import Processor, XsltException from",
"= 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest) sys.stderr.flush() return #",
"transformation-time options ---------------------------- # top-level params nsmappings = {} prefixes = options.get('prefix', [])",
"list): defs = [defs] top_level_params = {} for d in defs: match =",
"on). Without this option, each extra stylesheet is' ' imported by the preceding",
"URIs for xsl:include/import resolution # # An ordered list of absolute URIs is",
"the preceding one.'), ]), Options.Option( None, 'time', 'Display the elapsed transformation time on",
"must differ.' for path in (outputfile, outputfile_abspath): if not path: pass # we",
"**kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an InputSource cannot be created from",
"framework) Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project",
"name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime flags ignore_pis =",
"there are XSLT errors, the line & column # won't show up #",
"string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message output'), Options.Option(",
"-- Set up output streams (will die if files unwritable) ---------- # (assumes",
"sys.stderr # -- Set up XSLT processor (without stylesheets) ------------------- # gather alt",
"isrc def ReportFatalException(e, stacktrace_on_error=False): \"\"\" Formats various exceptions; raises SystemExit, never returns. \"\"\"",
"file set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace",
"case that matters elif path.endswith(os.sep): msg = 'The trace file %s would be",
"of InputSources for stylesheets (only if chaining) sty_chain = None # -- Prepare",
"so that the input to each chained stylesheet # is the previous transformation's",
"and os.path.abspath(tracefile) or None if outputfile_abspath == tracefile_abspath: msg = 'The trace and",
"in sty_chain[:-1]: i += 1 # FIXME: # use RtfWriter to make each",
"output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'), ] arguments = [",
"ValueError): pass if checktime: sys.stderr.write(\"Transformation time: %dms\\n\" % (1000 * (end - start)))",
"URI for imports and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE",
"the stylesheet.' ' If using --compile, it is the stylesheet to compile.'), Arguments.ZeroOrMoreArgument(",
"-- Do the transformation ----------------------------------------- try: if source_isrc is None: raise TypeError('No source",
"reader from Ft.Xml import Domlette validate_flag = options.has_key('validate') if validate_flag: reader = Domlette.ValidatingReader",
"if checktime: start = time.time() i = 0 for sty_isrc in sty_chain[:-1]: i",
"die if files unwritable) ---------- # (assumes output destinations have been checked for",
"result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream =",
"options.get('prefix', []) if not isinstance(prefixes, list): prefixes = [prefixes] for p in prefixes:",
"'chain', 'Chain the stylesheets (result of transforming with the first' ' is the",
"= Absolutize('chained-transformation-result-%d' % i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1])",
"elif path.endswith(os.sep): msg = 'The trace file %s would be a directory.' %",
"if not isinstance(defs, list): defs = [defs] top_level_params = {} for d in",
"or sys.stderr # -- Set up XSLT processor (without stylesheets) ------------------- # gather",
"or more. msg = '' argslen = len(arguments) if argslen != 2 and",
"def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an InputSource",
"xsl:message output'), Options.Option( None, 'no-messages', 'Suppress xsl:message output and warnings'), ] arguments =",
"reader = Domlette.ValidatingReader else: reader = Domlette.NonvalidatingReader processor.setDocumentReader(reader) #Customize message behavior if options.has_key('no-messages'):",
"doc in a reusable # stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True)",
"be exactly two. For --chain, three or more. msg = '' argslen =",
"---------- # (assumes output destinations have been checked for uniqueness) if options.has_key('compile'): output_flags",
"processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=out_file) if checktime: end = time.time() CloseStream(source_isrc, quiet=True) except Exception,",
"and stylesheet'), Options.Option( None, 'trace', 'Send execution trace output to stderr or file",
"= re.compile(r\"([\\d\\D_\\.\\-]+)=(.+)\") from Ft import MAX_PYTHON_RECURSION_DEPTH sys.setrecursionlimit(MAX_PYTHON_RECURSION_DEPTH) class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\",
"for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri']",
"for usage info.' % (msg, sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args,",
"from Ft.Lib.CommandLine.CommandLineUtil import SourceArgToInputSource from Ft.Lib.Uri import OsPathToUri, Absolutize from Ft.Xml.InputSource import InputSourceFactory,",
"path elif os.path.isdir(path): msg = 'The output file %s is a directory.' %",
"chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for isrc in sty_isrcs:",
"list): prefixes = [prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p) if match",
"elif argslen < 3 and options.has_key('chain'): msg = 'When using --chain, 1 source",
"FIXME: # use RtfWriter to make each result be a Domlette document, #",
"a Domlette document, # for speed, and so that the input to each",
"import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream = trace_file StylesheetHandler._ELEMENT_MAPPING",
"else: sty_args = args['stylesheet-uri'] chain = options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg,",
"extension modules moduleList = os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source",
"params nsmappings = {} prefixes = options.get('prefix', []) if not isinstance(prefixes, list): prefixes",
"ordered list of absolute URIs is derived from these sources: # 1. command-line",
"use better pickle format in Python 2.3 and up if hasattr(cPickle, 'HIGHEST_PROTOCOL'): cPickle.dump(processor.stylesheet.root,",
"-P/--prefix arguments') nsmappings[match.group(1)] = match.group(2) defs = options.get('define', []) if not isinstance(defs, list):",
"processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri",
"processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj, refUri=sty_isrc.uri) source_isrc = SourceArgToInputSource(source_arg, DefaultFactory,",
"all_source_args) for isrc in sty_isrcs: processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format",
"if stacktrace_on_error: traceback.print_exc(1000, sys.stderr) raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore') or \"&#%d;\" % ord(c) for c",
"ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream = resultstream new_uri = Absolutize('chained-transformation-result-%d' % i,",
"g_paramBindingPattern.match(d) if match is None: raise TypeError('Error in -D/--define arguments') name = match.group(1)",
"Do the transformation ----------------------------------------- try: if source_isrc is None: raise TypeError('No source document",
"sys.stderr.flush() return # -- Prepare for any transform ------------------------------------- # source document will",
"= os.environ.get(\"EXTMODULES\") if moduleList: processor.registerExtensionModules(moduleList.split(\":\")) # set up the source document reader from",
"arguments.values().count('-') > 1: msg = 'Standard input may be used for only 1",
"Options.ExclusiveOptions([ Options.Option( None, 'reflex', 'Reflexive transform (use the stylesheet as the source' '",
"# stream in memory. stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream)",
"options.has_key('instant') source_arg = args['source-uri'] if instant: sty_arg = args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg,",
"*v_args, **kw_args) except (OSError, UriException), error: if stylesheetAltUris: for alt_uri in stylesheetAltUris: try:",
"are required.' elif argslen > 1: if options.has_key('reflex'): msg = 'When using --reflex,",
"'trace-file=FILE', 'Trace file for execution trace output when using --trace'), Options.ExclusiveOptions([ Options.Option( None,",
"using --trace, you must specify an output' \\ ' file for the trace",
"(compiled). Only one stylesheet' ' can be specified with this option.'), Options.Option( None,",
"'no-messages', 'Suppress xsl:message output and warnings'), ] arguments = [ Arguments.RequiredArgument( 'source-uri', 'The",
"'media=MEDIA', 'Set media to honor in xml-stylesheet PIs'), Options.Option( 'D', 'define=NAME=VALUE', 'Bind a",
"[ Options.Option( 'v', 'validate', 'Validate the input file as it is being parsed'),",
"destinations have been checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags",
"distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle, time from cStringIO import",
"'msg-prefix=STRING', 'Prepend string to xsl:message output'), Options.Option( None, 'msg-suffix=STRING', 'Append string to xsl:message",
"class XsltCommandLineApp(CommandLineApp.CommandLineApp): from Ft.__config__ import \\ NAME as project_name, VERSION as project_version, URL",
"is exhausted. \"\"\" isrc = None stylesheetAltUris = None if kw_args.has_key('stylesheetAltUris'): stylesheetAltUris =",
"time from cStringIO import StringIO from Ft import GetConfigVars from Ft.Lib import UriException,",
"output_flags = \"wb\" else: output_flags = \"w\" out_file = options.has_key('outfile') \\ and open(options['outfile'],",
"'ignore') or \"&#%d;\" % ord(c) for c in msg])) else: sys.exit() def Run(options,",
"is a directory.' % path if msg: raise SystemExit('%s\\n See \"%s -h\" for",
"sty_args) if chain and len(sty_isrcs) > 1: sty_chain = sty_isrcs else: for isrc",
"sys.stdout: dest = 'standard output' elif hasattr(out_file, 'name'): dest = out_file.name elif options.has_key('outfile'):",
"in nsmappings: name = (nsmappings[prefix], local) top_level_params[name] = match.group(2) # misc runtime flags",
"speed, and so that the input to each chained stylesheet # is the",
"document to transform!') if sty_chain: resultstream = StringIO() if checktime: start = time.time()",
"i, source_isrc.uri) source_isrc = source_isrc.clone(sourcestream, new_uri) resultstream = StringIO() processor.appendStylesheet(sty_chain[-1]) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params,",
"home, documentation, distributions: http://4suite.org/ \"\"\" import re, os, sys, traceback, cPickle, time from",
"if argslen != 2 and options.has_key('instant'): msg = 'When using --instant, exactly 1",
"set by' ' --trace-file'), Options.Option( None, 'trace-file=FILE', 'Trace file for execution trace output",
"= options.has_key('chain') try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris), sty_args) if",
"to apply.'), ] def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile =",
"files unwritable) ---------- # (assumes output destinations have been checked for uniqueness) if",
"stylesheet object.' % sty_arg), stacktrace_on_error) except Exception, e: ReportFatalException(e, stacktrace_on_error) else: sty_args =",
"a directory.' % path if msg: raise SystemExit('%s\\n See \"%s -h\" for usage",
"new_uri = factory.resolver.normalize(arg, alt_uri) isrc = factory.fromUri(new_uri) break except (OSError, UriException): pass if",
"'Chain the stylesheets (result of transforming with the first' ' is the source",
"first' ' is the source document for transforming with the second, and' '",
"run(self, options, arguments): # 1st arg ('source-uri') will be the source doc normally,",
"for any transform ------------------------------------- # source document will be an InputSource source_isrc =",
"= StySourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) # We could parse the doc and use",
"of --reflex, or the # 1st stylesheet in the case of --compile. It",
"for d in defs: match = g_paramBindingPattern.match(d) if match is None: raise TypeError('Error",
"processIncludes=xinclude) except Exception, e: ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ---------------------------- #",
"sys.argv[0])) return Run(options, arguments) def StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for",
"and includes\"), Options.Option( 'o', 'outfile=FILE', 'Direct transformation output to FILE (file will be",
"created or the list of URIs is exhausted. \"\"\" isrc = None stylesheetAltUris",
"dest = out_file.name elif options.has_key('outfile'): dest = options['outfile'] else: dest = 'unknown destination(!)'",
"required.' elif argslen < 3 and options.has_key('chain'): msg = 'When using --chain, 1",
"options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg, DefaultFactory,",
"not outputfile and not tracefile: msg = 'When using --trace, you must specify",
"% path if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.' %",
"if checktime: end = time.time() CloseStream(source_isrc, quiet=True) else: if checktime: start = time.time()",
"options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri'] try: sty_isrcs = map(lambda arg: StySourceArgToInputSource(arg, DefaultFactory,",
"] def validate_options(self, options): if options.has_key('trace'): outputfile = options.get('outfile') tracefile = options.get('trace-file') msg",
"pass # we already handled the one case that matters elif path.endswith(os.sep): msg",
"path in alt_sty_paths] alt_sty_uris.extend(more_sty_uris) if os.environ.has_key('XSLTINCLUDE'): more_sty_uris = [ OsPathToUri(path, attemptAbsolute=1) for path",
"elapsed transformation time on stderr'), Options.Option( None, 'msg-prefix=STRING', 'Prepend string to xsl:message output'),",
"used for only 1 source document or stylesheet.' if msg: raise SystemExit('%s\\n See",
"options.has_key('no-messages'): processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n')",
"'define=NAME=VALUE', 'Bind a top-level parameter'), Options.Option( 'P', 'prefix=PREFIX=NSURI', 'Assign a namespace to a",
"= '' else: exceptiontype = str(sys.exc_type) if exceptiontype.startswith('exceptions.'): exceptiontype = exceptiontype[11:] msg =",
"alt_sty_paths = options.get('alt-sty-path', []) if type(alt_sty_paths) != list: alt_sty_paths = [alt_sty_paths] more_sty_uris =",
"None if options.has_key('trace'): trace_file_name= options.get('trace-file') if trace_file_name: trace_file_name = os.path.abspath(trace_file_name) out_file_name = options.get('outfile')",
"'Ignore <?xml-stylesheet ...?> instructions'), Options.Option( None, 'media=MEDIA', 'Set media to honor in xml-stylesheet",
"not isinstance(prefixes, list): prefixes = [prefixes] for p in prefixes: match = g_prefixBindingPattern.match(p)",
"to transform, or \"-\" to indicate' ' standard input. If using --reflex, it",
"def run(self, options, arguments): # 1st arg ('source-uri') will be the source doc",
"operation -------------------------------------- if options.has_key('compile'): xinclude = not options.has_key('noxinclude') all_source_args = [args['source-uri']] + args['stylesheet-uri']",
"-e (--stacktrace-on-error) option for a full stack trace.' if msg: raise SystemExit(''.join([c.encode(sys.getdefaultencoding(), 'ignore')",
"msg = 'Standard input may be used for only 1 source document or",
"have been checked for uniqueness) if options.has_key('compile'): output_flags = \"wb\" else: output_flags =",
"# # An ordered list of absolute URIs is derived from these sources:",
"the case of --reflex, or the # 1st stylesheet in the case of",
"are required.' elif argslen < 3 and options.has_key('chain'): msg = 'When using --chain,",
"args['stylesheet-uri'][0] try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True)",
"matters elif path.endswith(os.sep): msg = 'The trace file %s would be a directory.'",
"prefix, local = SplitQName(name) if prefix in nsmappings: name = (nsmappings[prefix], local) top_level_params[name]",
"doc URI and 1 stylesheet URI are required.' elif argslen < 3 and",
"as project_name, VERSION as project_version, URL as project_url name = '4xslt' summary =",
"try: sty_isrc = StySourceArgToInputSource(sty_arg, DefaultFactory, processIncludes=xinclude, stylesheetAltUris=alt_sty_uris) sty_obj = cPickle.load(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.appendStylesheetInstance(sty_obj,",
"processor.appendStylesheet(isrc) CloseStream(isrc, quiet=True) # use better pickle format in Python 2.3 and up",
"-- Prepare for reflexive transform ------------------------------- if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg",
"# --instant, there must be exactly two. For --chain, three or more. msg",
"document or stylesheet.' if msg: raise SystemExit('%s\\n See \"%s -h\" for usage info.'",
"command-line application\"\"\" options = [ Options.Option( 'v', 'validate', 'Validate the input file as",
"path.endswith(os.sep): msg = 'The output file %s would be a directory.' % path",
"= '' argslen = len(arguments) if argslen != 2 and options.has_key('instant'): msg =",
"SourceArgToInputSource(source_arg, DefaultFactory, processIncludes=xinclude) except cPickle.UnpicklingError: ReportFatalException(ValueError( '%s does not appear to be a",
"except (OSError, UriException): pass if not isrc: raise error return isrc def ReportFatalException(e,",
"ReportFatalException(e, stacktrace_on_error) # -- Prepare for regular transform --------------------------------- else: xinclude = not",
"source doc & stylesheet in the case of --reflex, or the # 1st",
"options['outfile'] else: dest = 'unknown destination(!)' sys.stderr.write('Compiled stylesheet written to %s.\\n' % dest)",
"if options.has_key('reflex'): xinclude = not options.has_key('noxinclude') source_arg = args['source-uri'] try: isrc = StySourceArgToInputSource(source_arg,",
"options.has_key('trace'): from Ft.Xml.Xslt import ExtendedProcessingElements, StylesheetHandler processor = ExtendedProcessingElements.ExtendedProcessor(stylesheetAltUris=alt_sty_uris) processor._4xslt_trace = True processor._4xslt_traceStream",
"ReportFatalException(e, stacktrace_on_error) # -- Gather transformation-time options ---------------------------- # top-level params nsmappings =",
"processor.messageControl(1) else: processor.messageControl(0) if options.has_key('msg-prefix'): prefix = options['msg-prefix'] prefix = prefix.replace('\\\\n', '\\n') prefix",
"TypeError('Error in -D/--define arguments') name = match.group(1) prefix, local = SplitQName(name) if prefix",
"def Run(options, args): stacktrace_on_error = options.has_key('stacktrace-on-error') # -- Set up output streams (will",
"StySourceArgToInputSource(arg, factory, *v_args, **kw_args): \"\"\" A wrapper for SourceArgToInputSource(). If an InputSource cannot",
"# previous transformation's serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream)",
"%s.\\n' % dest) sys.stderr.flush() return # -- Prepare for any transform ------------------------------------- #",
"serialized result tree) processor.appendStylesheet(sty_isrc) CloseStream(sty_isrc, quiet=True) processor.run(source_isrc, ignore_pis, topLevelParams=top_level_params, outputStream=resultstream) processor.reset() resultstream.reset() sourcestream",
"stream = StringIO(isrc.read()) CloseStream(isrc, quiet=True) stream.reset() source_isrc = isrc.clone(stream) del isrc processor.appendStylesheet(source_isrc) source_isrc.reset()"
] |
[
"<NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from",
"See the NOTICE file distributed with this work for additional information regarding copyright",
"from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.views import View",
"login_required from django.shortcuts import redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter import",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"offer attached to the requests :param request_id: ID of the accepted request :return:",
"'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one",
"2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.views",
"one request from offer, discards all other requests from offer :param offer_id: ID",
"offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return",
"requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators",
"form (offer details view) :param offer_id: ID of the offer attached to the",
"permissions and limitations under the License. RequestView controls activity belonging to requests @author",
"View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel,",
"offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id",
"to the view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req",
"class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from",
"request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3",
"RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id =",
"Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"request to be deleted :return: redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id)",
"creation form (offer details view) :param offer_id: ID of the offer attached to",
"RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({",
"Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request,",
"request creation form (offer details view) :param offer_id: ID of the offer attached",
"None) if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save()",
"to the request :return: renders a page and sends a dictionary to the",
"the offer attached to the request :return: renders a page and sends a",
"the License for the specific language governing permissions and limitations under the License.",
"offer_id, request_id): \"\"\" accepts one request from offer, discards all other requests from",
"@login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request :param request_id: ID of the",
"activity belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21",
"Unless required by applicable law or agreed to in writing, software distributed under",
"attached to the requests :param request_id: ID of the accepted request :return: redirects",
"information regarding copyright ownership. The ASF licenses this file to you under the",
"return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def",
"requests to othS er offers :return: renders a page and sends a dictionary",
"saves data from request creation form (offer details view) :param offer_id: ID of",
"accepted request :return: redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed =",
"object_list.append({ 'request': req, 'offer': offer, }) return render(request, \"my_request_list.html\", { 'objects': object_list })",
"The ASF licenses this file to you under the Apache License, Version 2.0",
"def accept_request(request, offer_id, request_id): \"\"\" accepts one request from offer, discards all other",
"= 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id):",
"a dictionary to the view \"\"\" form = RequestForm(request.POST or None) if form.is_valid():",
"form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage",
"licenses this file to you under the Apache License, Version 2.0 (the \"License\");",
"sends a dictionary to the view \"\"\" form = RequestForm(request.POST or None) if",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"under one or more contributor license agreements. See the NOTICE file distributed with",
"all other requests from offer :param offer_id: ID of the offer attached to",
"regarding copyright ownership. The ASF licenses this file to you under the Apache",
",<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts",
"req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form,",
"if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"other requests from offer :param offer_id: ID of the offer attached to the",
"add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return",
"request :return: renders a page and sends a dictionary to the view \"\"\"",
"req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return",
"of the offer attached to the requests :param request_id: ID of the accepted",
"1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id,",
":param offer_id: ID of the offer attached to the requests :param request_id: ID",
"Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from request creation form (offer",
"request_id: ID of the accepted request :return: redirects to a page \"\"\" offer",
"\"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return",
"for the specific language governing permissions and limitations under the License. RequestView controls",
"to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from",
"@login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from request creation form (offer details",
"ownership. The ASF licenses this file to you under the Apache License, Version",
"= OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return render(request,",
"OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request,",
"with this work for additional information regarding copyright ownership. The ASF licenses this",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\",",
"Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"= 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id,",
"License. RequestView controls activity belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD",
":param request_id: ID of the accepted request :return: redirects to a page \"\"\"",
"page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True req.save()",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\",",
"request_id: ID of the request to be deleted :return: redirects to a page",
"def delete_request(request, request_id): \"\"\" deletes the request :param request_id: ID of the request",
"of the offer attached to the request :return: renders a page and sends",
"in compliance with the License. You may obtain a copy of the License",
"the users requests to othS er offers :return: renders a page and sends",
"request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id,",
"offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return render(request, \"my_request_list.html\", { 'objects': object_list",
"KIND, either express or implied. See the License for the specific language governing",
"= RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\",",
"additional information regarding copyright ownership. The ASF licenses this file to you under",
"offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list')",
"\"\"\" form = RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id =",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"to the Apache Software Foundation (ASF) under one or more contributor license agreements.",
"of the request to be deleted :return: redirects to a page \"\"\" req",
"import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View):",
"= OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\"",
"create_request(request, offer_id): \"\"\" saves data from request creation form (offer details view) :param",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id,",
"and limitations under the License. RequestView controls activity belonging to requests @author <NAME>,",
"specific language governing permissions and limitations under the License. RequestView controls activity belonging",
"form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer =",
"or agreed to in writing, software distributed under the License is distributed on",
"OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves",
"requests :param request_id: ID of the accepted request :return: redirects to a page",
"dictionary to the view \"\"\" form = RequestForm(request.POST or None) if form.is_valid(): req",
"\"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.views import",
"a page and sends a dictionary to the view \"\"\" form = RequestForm(request.POST",
"Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of",
"if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return render(request, \"my_request_list.html\", {",
"renders a page and sends a dictionary to the view \"\"\" object_list =",
":return: redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1:",
"return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request :param request_id: ID",
"offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login')",
"= RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted:",
"<NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True",
"accept_request(request, offer_id, request_id): \"\"\" accepts one request from offer, discards all other requests",
"OF ANY KIND, either express or implied. See the License for the specific",
"offer attached to the request :return: renders a page and sends a dictionary",
":param offer_id: ID of the offer attached to the request :return: renders a",
"the request :return: renders a page and sends a dictionary to the view",
"may not use this file except in compliance with the License. You may",
":return: renders a page and sends a dictionary to the view \"\"\" form",
"request_id): \"\"\" accepts one request from offer, discards all other requests from offer",
"return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of the users requests",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage",
"req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer =",
"offer_id): \"\"\" saves data from request creation form (offer details view) :param offer_id:",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status",
"form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one request",
"req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer':",
"requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not",
"not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return render(request, \"my_request_list.html\", { 'objects':",
"othS er offers :return: renders a page and sends a dictionary to the",
"offer :param offer_id: ID of the offer attached to the requests :param request_id:",
"the License. RequestView controls activity belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt",
"add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\",",
"req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text)",
"offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request :param request_id:",
"req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes",
"(offer details view) :param offer_id: ID of the offer attached to the request",
"See the License for the specific language governing permissions and limitations under the",
"RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id == request_id: req.status = 2 req.save()",
":param request_id: ID of the request to be deleted :return: redirects to a",
"limitations under the License. RequestView controls activity belonging to requests @author <NAME>, <NAME>",
"RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data",
"= form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id,",
"request :return: redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True",
"this file except in compliance with the License. You may obtain a copy",
"RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def",
"from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel",
"be deleted :return: redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status",
"\"License\"); you may not use this file except in compliance with the License.",
"for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req,",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"the specific language governing permissions and limitations under the License. RequestView controls activity",
"you may not use this file except in compliance with the License. You",
"= True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id ==",
"agreed to in writing, software distributed under the License is distributed on an",
"abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request :param",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"to the requests :param request_id: ID of the accepted request :return: redirects to",
"def create_request(request, offer_id): \"\"\" saves data from request creation form (offer details view)",
"erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id })",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"implied. See the License for the specific language governing permissions and limitations under",
"this work for additional information regarding copyright ownership. The ASF licenses this file",
"redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests",
"gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login')",
"to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted =",
"displays a list of the users requests to othS er offers :return: renders",
"= request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text)",
"er offers :return: renders a page and sends a dictionary to the view",
"deletes the request :param request_id: ID of the request to be deleted :return:",
"and sends a dictionary to the view \"\"\" object_list = [] requests =",
"the Apache Software Foundation (ASF) under one or more contributor license agreements. See",
"use this file except in compliance with the License. You may obtain a",
"page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id)",
"req.offer_id = offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"if req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer",
"to the view \"\"\" form = RequestForm(request.POST or None) if form.is_valid(): req =",
"gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of the",
"to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests =",
"distributed with this work for additional information regarding copyright ownership. The ASF licenses",
"personal_request_listing(request): \"\"\" displays a list of the users requests to othS er offers",
"from offer :param offer_id: ID of the offer attached to the requests :param",
"accepts one request from offer, discards all other requests from offer :param offer_id:",
"form = RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id",
"redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request,",
"required by applicable law or agreed to in writing, software distributed under the",
"data from request creation form (offer details view) :param offer_id: ID of the",
"redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import",
"\"\"\" accepts one request from offer, discards all other requests from offer :param",
"angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list')",
"in requests: if req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\",",
"sends a dictionary to the view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by(",
"render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id):",
"\"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\"",
"OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if",
"@login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one request from offer, discards all",
"@login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of the users requests to othS",
"WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"list of the users requests to othS er offers :return: renders a page",
"not use this file except in compliance with the License. You may obtain",
"'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one request from",
"object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer =",
"license agreements. See the NOTICE file distributed with this work for additional information",
"True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id == request_id:",
"req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of the users",
"of the users requests to othS er offers :return: renders a page and",
"RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text)",
"request :param request_id: ID of the request to be deleted :return: redirects to",
"import redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms",
"ANY KIND, either express or implied. See the License for the specific language",
"offer_id: ID of the offer attached to the request :return: renders a page",
"file except in compliance with the License. You may obtain a copy of",
"= OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return",
"attached to the request :return: renders a page and sends a dictionary to",
"requests: if req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title)",
"req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save()",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form':",
"a page and sends a dictionary to the view \"\"\" object_list = []",
"render from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm",
"a dictionary to the view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at')",
"from request creation form (offer details view) :param offer_id: ID of the offer",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"'-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request':",
"= RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id",
"ASF licenses this file to you under the Apache License, Version 2.0 (the",
"file to you under the Apache License, Version 2.0 (the \"License\"); you may",
"add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id':",
"the request to be deleted :return: redirects to a page \"\"\" req =",
"or more contributor license agreements. See the NOTICE file distributed with this work",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id == request_id: req.status",
"(the \"License\"); you may not use this file except in compliance with the",
"OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays",
"under the License. RequestView controls activity belonging to requests @author <NAME>, <NAME> ,<NAME>",
"from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View",
"page and sends a dictionary to the view \"\"\" form = RequestForm(request.POST or",
"Foundation (ASF) under one or more contributor license agreements. See the NOTICE file",
"== 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id)",
"a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at')",
"view) :param offer_id: ID of the offer attached to the request :return: renders",
"== request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status =",
"ID of the offer attached to the requests :param request_id: ID of the",
"delete_request(request, request_id): \"\"\" deletes the request :param request_id: ID of the request to",
"for additional information regarding copyright ownership. The ASF licenses this file to you",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"agreements. See the NOTICE file distributed with this work for additional information regarding",
"ID of the request to be deleted :return: redirects to a page \"\"\"",
"requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id == request_id: req.status =",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"to you under the Apache License, Version 2.0 (the \"License\"); you may not",
"requests from offer :param offer_id: ID of the offer attached to the requests",
"True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\",",
"import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\"",
"controls activity belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe",
"View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from request creation form",
"= offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\",",
"law or agreed to in writing, software distributed under the License is distributed",
"req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"the request :param request_id: ID of the request to be deleted :return: redirects",
"for req in requests: if req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id,",
"from offer, discards all other requests from offer :param offer_id: ID of the",
"License for the specific language governing permissions and limitations under the License. RequestView",
"details view) :param offer_id: ID of the offer attached to the request :return:",
"the NOTICE file distributed with this work for additional information regarding copyright ownership.",
"import login_required from django.shortcuts import redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter",
"from django.shortcuts import redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification",
"deleted :return: redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status ==",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, })",
"either express or implied. See the License for the specific language governing permissions",
"one or more contributor license agreements. See the NOTICE file distributed with this",
"\"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from request creation",
"\"\"\" deletes the request :param request_id: ID of the request to be deleted",
"}) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one request from offer, discards",
"apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel class",
"else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def",
"from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from",
"req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id, \"Anfrage",
"copyright ownership. The ASF licenses this file to you under the Apache License,",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"\"\"\" saves data from request creation form (offer details view) :param offer_id: ID",
"the offer attached to the requests :param request_id: ID of the accepted request",
"= True req.save() add_notification(request.user.id, \"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage",
"OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer, }) return render(request, \"my_request_list.html\",",
"[] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id) if",
"ID of the accepted request :return: redirects to a page \"\"\" offer =",
"def personal_request_listing(request): \"\"\" displays a list of the users requests to othS er",
"this file to you under the Apache License, Version 2.0 (the \"License\"); you",
"dictionary to the view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for",
"file distributed with this work for additional information regarding copyright ownership. The ASF",
"you under the Apache License, Version 2.0 (the \"License\"); you may not use",
"belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\"",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"renders a page and sends a dictionary to the view \"\"\" form =",
"<filename>apps/bazaar/views/RequestView.py \"\"\" Licensed to the Apache Software Foundation (ASF) under one or more",
":return: redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save()",
"to in writing, software distributed under the License is distributed on an \"AS",
"from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request,",
"\"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id",
"\"\"\" Licensed to the Apache Software Foundation (ASF) under one or more contributor",
"(ASF) under one or more contributor license agreements. See the NOTICE file distributed",
"the view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in",
"offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in",
"Licensed to the Apache Software Foundation (ASF) under one or more contributor license",
"except in compliance with the License. You may obtain a copy of the",
"req.text) return redirect('offer_list') return render(request, \"create_request.html\", { 'form': form, 'offer_id': offer_id }) @login_required(login_url='login')",
"Apache Software Foundation (ASF) under one or more contributor license agreements. See the",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"\"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text) return redirect('offer_list') return render(request, \"create_request.html\", {",
"req in requests: if req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage",
"users requests to othS er offers :return: renders a page and sends a",
"add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else: req.status = 3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title)",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"\"Anfrage gelöscht\", req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list')",
":return: renders a page and sends a dictionary to the view \"\"\" object_list",
"\"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"import RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login')",
"\"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted = True req.save() add_notification(request.user.id,",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"to othS er offers :return: renders a page and sends a dictionary to",
"or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id = request.user.id req.offer_id = offer_id",
"\"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list",
"add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the",
"\"\"\" displays a list of the users requests to othS er offers :return:",
"redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a list of the users requests to",
"compliance with the License. You may obtain a copy of the License at",
"contributor license agreements. See the NOTICE file distributed with this work for additional",
"view \"\"\" object_list = [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests:",
"express or implied. See the License for the specific language governing permissions and",
"offers :return: renders a page and sends a dictionary to the view \"\"\"",
"page and sends a dictionary to the view \"\"\" object_list = [] requests",
"in requests: offer = OfferModel.objects.get(id=req.offer_id) if not offer.is_deleted: object_list.append({ 'request': req, 'offer': offer,",
"django.shortcuts import redirect, render from django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from",
"\"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req",
"RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id): \"\"\" saves data from request",
"view \"\"\" form = RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False) req.userowner_id",
"a list of the users requests to othS er offers :return: renders a",
"OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import login_required from django.shortcuts import redirect,",
"if req.id == request_id: req.status = 2 req.save() add_notification(req.userowner_id, \"Anfrage angenommen!\", offer.title) else:",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"offer_id req.save() offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) add_notification(request.user.id, \"Anfrage verschickt\", req.text) add_notification(offer.userowner_id, \"Anfrage erhalten!\", req.text)",
"to be deleted :return: redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if",
"language governing permissions and limitations under the License. RequestView controls activity belonging to",
"redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request :param request_id: ID of",
"offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts one request from offer,",
"of the accepted request :return: redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id)",
"offer, discards all other requests from offer :param offer_id: ID of the offer",
"applicable law or agreed to in writing, software distributed under the License is",
"django.views import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models",
"offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request):",
"3 req.save() add_notification(req.userowner_id, \"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\"",
"request_id): \"\"\" deletes the request :param request_id: ID of the request to be",
"= [] requests = RequestModel.objects.filter(is_deleted=False).filter(userowner_id=request.user.id).order_by( '-created_at') for req in requests: offer = OfferModel.objects.get(id=req.offer_id)",
"@author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit WiSe 2020/21 \"\"\" from django.contrib.auth.decorators import",
"ID of the offer attached to the request :return: renders a page and",
"\"Anfrage abgelehnt\", offer.title) return redirect('personal_offer_list') @login_required(login_url='login') def delete_request(request, request_id): \"\"\" deletes the request",
"apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\"",
"django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.views import View from",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request",
"{ 'form': form, 'offer_id': offer_id }) @login_required(login_url='login') def accept_request(request, offer_id, request_id): \"\"\" accepts",
"redirects to a page \"\"\" req = RequestModel.objects.filter(is_deleted=False).get(id=request_id) if req.status == 1: req.is_deleted",
"the accepted request :return: redirects to a page \"\"\" offer = OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed",
"req.text) offer = OfferModel.objects.filter(is_deleted=False).get(id=req.offer_id) add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def",
"request from offer, discards all other requests from offer :param offer_id: ID of",
"work for additional information regarding copyright ownership. The ASF licenses this file to",
"and sends a dictionary to the view \"\"\" form = RequestForm(request.POST or None)",
"the requests :param request_id: ID of the accepted request :return: redirects to a",
"offer_id: ID of the offer attached to the requests :param request_id: ID of",
"the view \"\"\" form = RequestForm(request.POST or None) if form.is_valid(): req = form.save(commit=False)",
"= RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests: if req.id == request_id: req.status = 2",
"add_notification(offer.userowner_id, \"Eingehende Anfrage gelöscht\", req.text) return redirect('personal_request_list') @login_required(login_url='login') def personal_request_listing(request): \"\"\" displays a",
"import View from apps.bazaar.adapters.notifications_adapter import add_notification from apps.bazaar.forms import RequestForm from apps.bazaar.models import",
"= OfferModel.objects.filter(is_deleted=False).get(id=offer_id) offer.is_closed = True offer.save() requests = RequestModel.objects.filter(is_deleted=False).filter(offer_id=offer_id).order_by('-created_at') for req in requests:",
"more contributor license agreements. See the NOTICE file distributed with this work for",
"apps.bazaar.models import OfferModel, RequestModel class RequestView(View): \"\"\"Request View Class\"\"\" @login_required(login_url='login') def create_request(request, offer_id):",
"discards all other requests from offer :param offer_id: ID of the offer attached",
"governing permissions and limitations under the License. RequestView controls activity belonging to requests",
"RequestView controls activity belonging to requests @author <NAME>, <NAME> ,<NAME> Projekt OOAD Hausarbeit",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"NOTICE file distributed with this work for additional information regarding copyright ownership. The",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software"
] |
[
"Post from . models import Query from .models import Solution # Register your",
"django.contrib import admin from .models import Post from . models import Query from",
"import Query from .models import Solution # Register your models here. admin.site.register(Post) admin.site.register(Query)",
"from django.contrib import admin from .models import Post from . models import Query",
"from .models import Solution # Register your models here. admin.site.register(Post) admin.site.register(Query) # admin.site.register(Services)",
"import Post from . models import Query from .models import Solution # Register",
"models import Query from .models import Solution # Register your models here. admin.site.register(Post)",
". models import Query from .models import Solution # Register your models here.",
"import admin from .models import Post from . models import Query from .models",
"admin from .models import Post from . models import Query from .models import",
".models import Solution # Register your models here. admin.site.register(Post) admin.site.register(Query) # admin.site.register(Services) #",
"from . models import Query from .models import Solution # Register your models",
"import Solution # Register your models here. admin.site.register(Post) admin.site.register(Query) # admin.site.register(Services) # admin.site.register(Contact)",
".models import Post from . models import Query from .models import Solution #",
"Solution # Register your models here. admin.site.register(Post) admin.site.register(Query) # admin.site.register(Services) # admin.site.register(Contact) admin.site.register(Solution)",
"from .models import Post from . models import Query from .models import Solution",
"Query from .models import Solution # Register your models here. admin.site.register(Post) admin.site.register(Query) #"
] |
[
"\"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag( self, offset: int =",
"specified offset from beginning the window. Offsets start at 1. The offset can",
"None: if not isinstance(order_by, list): order_by = [order_by] str_out += 'order by '",
"None or order_by is not None: str_out += ')' if as_ is None:",
"order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] = None ) -> str: \"\"\"",
"'.join(map(str, order_by)) if partition_by is not None or order_by is not None: str_out",
"str_out += ' ' if order_by is not None: if not isinstance(order_by, list):",
"= [order_by] str_out += 'order by ' + ', '.join(map(str, order_by)) if partition_by",
"or order_by is not None: str_out += ' over (' if partition_by is",
"+ ', '.join(map(str, order_by)) if partition_by is not None or order_by is not",
"partition_by = [partition_by] str_out += 'partition by ' + ', '.join(map(str, partition_by)) if",
"the window. Offsets start at 1. The offset can be any scalar expression.",
"')' if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out += f' as {as_}'",
"' over (' if partition_by is not None: if not isinstance(partition_by, list): partition_by",
"'.join(map(str, partition_by)) if partition_by is not None and order_by is not None: str_out",
"order_by is not None: if not isinstance(order_by, list): order_by = [order_by] str_out +=",
"Optional[str] = None ) -> str: \"\"\" Returns the value at the specified",
"order_by is not None: str_out += ' over (' if partition_by is not",
"or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is not None or",
"= None, as_: Optional[str] = None ) -> str: \"\"\" Returns the value",
"is null or greater than the number of values in the window, null",
"is not None or order_by is not None: str_out += ')' if as_",
"of values in the window, null is returned. It is an error for",
"offset to be zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by",
"', '.join(map(str, partition_by)) if partition_by is not None and order_by is not None:",
"if not isinstance(order_by, list): order_by = [order_by] str_out += 'order by ' +",
"order_by is not None: str_out += ')' if as_ is None: as_ =",
"by ' + ', '.join(map(str, order_by)) if partition_by is not None or order_by",
"https://prestodb.io/docs/current/functions/window.html \"\"\" from typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object):",
"offset: int = 1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] =",
"str_out = f'lag({self.name}, {offset})' if partition_by is not None or order_by is not",
"= None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] = None ) ->",
"= [partition_by] str_out += 'partition by ' + ', '.join(map(str, partition_by)) if partition_by",
"or order_by is not None: str_out += ')' if as_ is None: as_",
"import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag(",
"by ' + ', '.join(map(str, partition_by)) if partition_by is not None and order_by",
"None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] = None ) -> str:",
"\"\"\" Returns the value at the specified offset from beginning the window. Offsets",
"{offset})' if partition_by is not None or order_by is not None: str_out +=",
"<filename>aws_managers/athena/functions/window.py \"\"\" https://prestodb.io/docs/current/functions/window.html \"\"\" from typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\"",
"= f'lag({self.name}, {offset})' if partition_by is not None or order_by is not None:",
"list): partition_by = [partition_by] str_out += 'partition by ' + ', '.join(map(str, partition_by))",
"None: str_out += ')' if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out +=",
"not isinstance(order_by, list): order_by = [order_by] str_out += 'order by ' + ',",
"the window, null is returned. It is an error for the offset to",
"isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition by ' + ', '.join(map(str,",
"null or greater than the number of values in the window, null is",
"is not None: if not isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition",
"The offset can be any scalar expression. If the offset is null or",
"typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def",
"https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag( self, offset: int = 1,",
"at 1. The offset can be any scalar expression. If the offset is",
"None, as_: Optional[str] = None ) -> str: \"\"\" Returns the value at",
"values in the window, null is returned. It is an error for the",
"if partition_by is not None or order_by is not None: str_out += '",
"not None or order_by is not None: str_out += ')' if as_ is",
"None: str_out += ' over (' if partition_by is not None: if not",
"', '.join(map(str, order_by)) if partition_by is not None or order_by is not None:",
"\"\"\" class LagMixin(object): name: str def lag( self, offset: int = 1, partition_by:",
"str_out += ' over (' if partition_by is not None: if not isinstance(partition_by,",
"if partition_by is not None and order_by is not None: str_out += '",
"the value at the specified offset from beginning the window. Offsets start at",
"not isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition by ' + ',",
"Returns the value at the specified offset from beginning the window. Offsets start",
"'order by ' + ', '.join(map(str, order_by)) if partition_by is not None or",
"from beginning the window. Offsets start at 1. The offset can be any",
"to be zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is",
"at the specified offset from beginning the window. Offsets start at 1. The",
"+= ' over (' if partition_by is not None: if not isinstance(partition_by, list):",
"= None ) -> str: \"\"\" Returns the value at the specified offset",
"number of values in the window, null is returned. It is an error",
"greater than the number of values in the window, null is returned. It",
"if order_by is not None: if not isinstance(order_by, list): order_by = [order_by] str_out",
"order_by is not None: str_out += ' ' if order_by is not None:",
"if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out += f' as {as_}' return",
"is not None: str_out += ' ' if order_by is not None: if",
"start at 1. The offset can be any scalar expression. If the offset",
"or greater than the number of values in the window, null is returned.",
"is returned. It is an error for the offset to be zero or",
"if partition_by is not None or order_by is not None: str_out += ')'",
") -> str: \"\"\" Returns the value at the specified offset from beginning",
"str_out += ')' if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out += f'",
"not None: str_out += ')' if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out",
"List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] = None )",
"and order_by is not None: str_out += ' ' if order_by is not",
"None or order_by is not None: str_out += ' over (' if partition_by",
"\"\"\" https://prestodb.io/docs/current/functions/window.html \"\"\" from typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class",
"LagMixin(object): name: str def lag( self, offset: int = 1, partition_by: Optional[Union[str, List[str]]]",
"+= ' ' if order_by is not None: if not isinstance(order_by, list): order_by",
"be zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is not",
"is an error for the offset to be zero or negative. \"\"\" str_out",
"+= 'order by ' + ', '.join(map(str, order_by)) if partition_by is not None",
"beginning the window. Offsets start at 1. The offset can be any scalar",
"partition_by is not None or order_by is not None: str_out += ')' if",
"not None and order_by is not None: str_out += ' ' if order_by",
"' ' if order_by is not None: if not isinstance(order_by, list): order_by =",
"= 1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None, as_:",
"None ) -> str: \"\"\" Returns the value at the specified offset from",
"partition_by is not None and order_by is not None: str_out += ' '",
"not None or order_by is not None: str_out += ' over (' if",
"List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag( self, offset:",
"error for the offset to be zero or negative. \"\"\" str_out = f'lag({self.name},",
"+= 'partition by ' + ', '.join(map(str, partition_by)) if partition_by is not None",
"1. The offset can be any scalar expression. If the offset is null",
"in the window, null is returned. It is an error for the offset",
"partition_by)) if partition_by is not None and order_by is not None: str_out +=",
"can be any scalar expression. If the offset is null or greater than",
"name: str def lag( self, offset: int = 1, partition_by: Optional[Union[str, List[str]]] =",
"offset from beginning the window. Offsets start at 1. The offset can be",
"Offsets start at 1. The offset can be any scalar expression. If the",
"not None: if not isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition by",
"f'lag({self.name}, {offset})' if partition_by is not None or order_by is not None: str_out",
"' + ', '.join(map(str, order_by)) if partition_by is not None or order_by is",
"for the offset to be zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})'",
"if partition_by is not None: if not isinstance(partition_by, list): partition_by = [partition_by] str_out",
"not None: str_out += ' ' if order_by is not None: if not",
"null is returned. It is an error for the offset to be zero",
"' + ', '.join(map(str, partition_by)) if partition_by is not None and order_by is",
"Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] = None",
"order_by)) if partition_by is not None or order_by is not None: str_out +=",
"be any scalar expression. If the offset is null or greater than the",
"as_ is None: as_ = f'{self.name}__lag_{offset}' str_out += f' as {as_}' return str_out",
"str: \"\"\" Returns the value at the specified offset from beginning the window.",
"It is an error for the offset to be zero or negative. \"\"\"",
"is not None or order_by is not None: str_out += ' over ('",
"str_out += 'partition by ' + ', '.join(map(str, partition_by)) if partition_by is not",
"Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag( self, offset: int",
"the specified offset from beginning the window. Offsets start at 1. The offset",
"partition_by is not None or order_by is not None: str_out += ' over",
"window. Offsets start at 1. The offset can be any scalar expression. If",
"value at the specified offset from beginning the window. Offsets start at 1.",
"offset is null or greater than the number of values in the window,",
"def lag( self, offset: int = 1, partition_by: Optional[Union[str, List[str]]] = None, order_by:",
"zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is not None",
"'partition by ' + ', '.join(map(str, partition_by)) if partition_by is not None and",
"lag( self, offset: int = 1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str,",
"[order_by] str_out += 'order by ' + ', '.join(map(str, order_by)) if partition_by is",
"list): order_by = [order_by] str_out += 'order by ' + ', '.join(map(str, order_by))",
"negative. \"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is not None or order_by",
"is not None and order_by is not None: str_out += ' ' if",
"scalar expression. If the offset is null or greater than the number of",
"isinstance(order_by, list): order_by = [order_by] str_out += 'order by ' + ', '.join(map(str,",
"Optional[Union[str, List[str]]] = None, as_: Optional[str] = None ) -> str: \"\"\" Returns",
"str_out += 'order by ' + ', '.join(map(str, order_by)) if partition_by is not",
"\"\"\" str_out = f'lag({self.name}, {offset})' if partition_by is not None or order_by is",
"partition_by is not None: if not isinstance(partition_by, list): partition_by = [partition_by] str_out +=",
"any scalar expression. If the offset is null or greater than the number",
"str def lag( self, offset: int = 1, partition_by: Optional[Union[str, List[str]]] = None,",
"if not isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition by ' +",
"order_by = [order_by] str_out += 'order by ' + ', '.join(map(str, order_by)) if",
"the number of values in the window, null is returned. It is an",
"is not None: if not isinstance(order_by, list): order_by = [order_by] str_out += 'order",
"-> str: \"\"\" Returns the value at the specified offset from beginning the",
"is not None: str_out += ')' if as_ is None: as_ = f'{self.name}__lag_{offset}'",
"returned. It is an error for the offset to be zero or negative.",
"(' if partition_by is not None: if not isinstance(partition_by, list): partition_by = [partition_by]",
"not None: str_out += ' over (' if partition_by is not None: if",
"None: str_out += ' ' if order_by is not None: if not isinstance(order_by,",
"as_: Optional[str] = None ) -> str: \"\"\" Returns the value at the",
"window, null is returned. It is an error for the offset to be",
"is not None: str_out += ' over (' if partition_by is not None:",
"the offset is null or greater than the number of values in the",
"not None: if not isinstance(order_by, list): order_by = [order_by] str_out += 'order by",
"Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str def lag( self,",
"self, offset: int = 1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]]",
"partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str] =",
"List[str]]] = None, as_: Optional[str] = None ) -> str: \"\"\" Returns the",
"If the offset is null or greater than the number of values in",
"1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None, as_: Optional[str]",
"None: if not isinstance(partition_by, list): partition_by = [partition_by] str_out += 'partition by '",
"from typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name: str",
"over (' if partition_by is not None: if not isinstance(partition_by, list): partition_by =",
"None and order_by is not None: str_out += ' ' if order_by is",
"+= ')' if as_ is None: as_ = f'{self.name}__lag_{offset}' str_out += f' as",
"' if order_by is not None: if not isinstance(order_by, list): order_by = [order_by]",
"int = 1, partition_by: Optional[Union[str, List[str]]] = None, order_by: Optional[Union[str, List[str]]] = None,",
"offset can be any scalar expression. If the offset is null or greater",
"an error for the offset to be zero or negative. \"\"\" str_out =",
"the offset to be zero or negative. \"\"\" str_out = f'lag({self.name}, {offset})' if",
"\"\"\" from typing import Optional, List, Union \"\"\" https://prestodb.io/docs/current/functions/window.html#value-functions \"\"\" class LagMixin(object): name:",
"+ ', '.join(map(str, partition_by)) if partition_by is not None and order_by is not",
"than the number of values in the window, null is returned. It is",
"[partition_by] str_out += 'partition by ' + ', '.join(map(str, partition_by)) if partition_by is",
"expression. If the offset is null or greater than the number of values",
"class LagMixin(object): name: str def lag( self, offset: int = 1, partition_by: Optional[Union[str,"
] |
[
"Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT",
"micropython import const # Spectrometer (CM12880MA) TRG = const(14) STA = const(15) CLK",
"[1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel NEOPIX = const(32) # ----------------------------------------------------------------------------",
"import const # Spectrometer (CM12880MA) TRG = const(14) STA = const(15) CLK =",
"SDA = const(23) SCL = const(22) I2C_FRQ = const(400000) # Serial for extensions",
"const(17) RX = const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931]",
"= const(36) # I2C for compass etc. SDA = const(23) SCL = const(22)",
"# 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA) TRG",
"---------------------------------------------------------------------------- # board.py # Pin definitions # # The MIT License (MIT) #",
"= const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG =",
"= [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033,",
"extensions TX = const(17) RX = const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US",
"= const(23) SCL = const(22) I2C_FRQ = const(400000) # Serial for extensions TX",
"Serial for extensions TX = const(17) RX = const(16) # Servos SERVO_PAN =",
"[1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916]",
"# ---------------------------------------------------------------------------- # board.py # Pin definitions # # The MIT License (MIT)",
"VID = const(36) # I2C for compass etc. SDA = const(23) SCL =",
"45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45] #",
"Copyright (c) 2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const",
"CLK = const(21) VID = const(36) # I2C for compass etc. SDA =",
"SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel",
"# I2C for compass etc. SDA = const(23) SCL = const(22) I2C_FRQ =",
"const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel NEOPIX =",
"etc. SDA = const(23) SCL = const(22) I2C_FRQ = const(400000) # Serial for",
"SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT =",
"= const(17) RX = const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010,",
"const(14) STA = const(15) CLK = const(21) VID = const(36) # I2C for",
"I2C for compass etc. SDA = const(23) SCL = const(22) I2C_FRQ = const(400000)",
"# ---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA) TRG = const(14) STA",
"2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const # Spectrometer",
"PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG =",
"# Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45]",
"= const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel NEOPIX",
"= const(21) VID = const(36) # I2C for compass etc. SDA = const(23)",
"(MIT) # Copyright (c) 2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython",
"SCL = const(22) I2C_FRQ = const(400000) # Serial for extensions TX = const(17)",
"board.py # Pin definitions # # The MIT License (MIT) # Copyright (c)",
"for compass etc. SDA = const(23) SCL = const(22) I2C_FRQ = const(400000) #",
"const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45,",
"const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US",
"TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel NEOPIX = const(32)",
"---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA) TRG = const(14) STA =",
"= const(14) STA = const(15) CLK = const(21) VID = const(36) # I2C",
"# # The MIT License (MIT) # Copyright (c) 2020 <NAME> # 2020-11-21,",
"= const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33)",
"<NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA)",
"const(400000) # Serial for extensions TX = const(17) RX = const(16) # Servos",
"License (MIT) # Copyright (c) 2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from",
"v1 # ---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA) TRG = const(14)",
"Pin definitions # # The MIT License (MIT) # Copyright (c) 2020 <NAME>",
"from micropython import const # Spectrometer (CM12880MA) TRG = const(14) STA = const(15)",
"for extensions TX = const(17) RX = const(16) # Servos SERVO_PAN = const(27)",
"= const(22) I2C_FRQ = const(400000) # Serial for extensions TX = const(17) RX",
"Spectrometer (CM12880MA) TRG = const(14) STA = const(15) CLK = const(21) VID =",
"= const(15) CLK = const(21) VID = const(36) # I2C for compass etc.",
"2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const # Spectrometer (CM12880MA) TRG =",
"[-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45, 45]",
"# board.py # Pin definitions # # The MIT License (MIT) # Copyright",
"# The MIT License (MIT) # Copyright (c) 2020 <NAME> # 2020-11-21, v1",
"const # Spectrometer (CM12880MA) TRG = const(14) STA = const(15) CLK = const(21)",
"const(23) SCL = const(22) I2C_FRQ = const(400000) # Serial for extensions TX =",
"# Pin definitions # # The MIT License (MIT) # Copyright (c) 2020",
"RX = const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG",
"MIT License (MIT) # Copyright (c) 2020 <NAME> # 2020-11-21, v1 # ----------------------------------------------------------------------------",
"const(15) CLK = const(21) VID = const(36) # I2C for compass etc. SDA",
"# Copyright (c) 2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import",
"const(22) I2C_FRQ = const(400000) # Serial for extensions TX = const(17) RX =",
"= [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG = [-45,",
"The MIT License (MIT) # Copyright (c) 2020 <NAME> # 2020-11-21, v1 #",
"PAN_RANGE_US = [1010, 1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US =",
"(CM12880MA) TRG = const(14) STA = const(15) CLK = const(21) VID = const(36)",
"STA = const(15) CLK = const(21) VID = const(36) # I2C for compass",
"compass etc. SDA = const(23) SCL = const(22) I2C_FRQ = const(400000) # Serial",
"TX = const(17) RX = const(16) # Servos SERVO_PAN = const(27) PAN_RANGE_US =",
"# Spectrometer (CM12880MA) TRG = const(14) STA = const(15) CLK = const(21) VID",
"(c) 2020 <NAME> # 2020-11-21, v1 # ---------------------------------------------------------------------------- from micropython import const #",
"I2C_FRQ = const(400000) # Serial for extensions TX = const(17) RX = const(16)",
"const(36) # I2C for compass etc. SDA = const(23) SCL = const(22) I2C_FRQ",
"# Serial for extensions TX = const(17) RX = const(16) # Servos SERVO_PAN",
"= const(400000) # Serial for extensions TX = const(17) RX = const(16) #",
"1931] PAN_RANGE_DEG = [-45, 45] SERVO_TLT = const(33) TLT_RANGE_US = [1033, 1916] TLT_RANGE_DEG",
"TRG = const(14) STA = const(15) CLK = const(21) VID = const(36) #",
"definitions # # The MIT License (MIT) # Copyright (c) 2020 <NAME> #",
"= [1033, 1916] TLT_RANGE_DEG = [-45, 45] # NeoPixel NEOPIX = const(32) #",
"const(21) VID = const(36) # I2C for compass etc. SDA = const(23) SCL"
] |
[
"from application import app # Starts the application if __name__ == \"__main__\": app.run()"
] |
[
"pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def",
"pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is None: return None",
"self.started_at is not None def finished(self) -> bool: return self.finished_at is not None",
"finished(self) -> bool: return self.finished_at is not None def successful(self) -> bool: return",
"def return_value(self): if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) ->",
"import pickle from typing import Any from django.db import models class Task(models.Model): pickled_task",
"-> bool: return self.started_at is not None def finished(self) -> bool: return self.finished_at",
"not None def finished(self) -> bool: return self.finished_at is not None def successful(self)",
"def exception(self): if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self):",
"pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is not None def finished(self) ->",
"return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is not None",
"models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception))",
"None def finished(self) -> bool: return self.finished_at is not None def successful(self) ->",
"= models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at",
"= models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is None: return None return",
"django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at",
"= models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is",
"Any from django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256,",
"started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096,",
"null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048,",
"def finished(self) -> bool: return self.finished_at is not None def successful(self) -> bool:",
"is not None def successful(self) -> bool: return self.finished() and self.pickled_return is not",
"Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at =",
"started(self) -> bool: return self.started_at is not None def finished(self) -> bool: return",
"typing import Any from django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool",
"return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return))",
"@property def exception(self): if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def",
"models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return =",
"return self.started_at is not None def finished(self) -> bool: return self.finished_at is not",
"-> bool: return self.finished_at is not None def successful(self) -> bool: return self.finished()",
"None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None: return None return",
"if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return",
"not None def successful(self) -> bool: return self.finished() and self.pickled_return is not None",
"return_value(self): if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool:",
"models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception =",
"<reponame>Volumental/django-leek<gh_stars>1-10 import base64 import pickle from typing import Any from django.db import models",
"None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None: return",
"is not None def finished(self) -> bool: return self.finished_at is not None def",
"bool: return self.finished_at is not None def successful(self) -> bool: return self.finished() and",
"return self.finished_at is not None def successful(self) -> bool: return self.finished() and self.pickled_return",
"pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True)",
"= models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self):",
"exception(self): if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if",
"@property def return_value(self): if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self)",
"class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at",
"is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None:",
"self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is",
"return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is not None def finished(self)",
"models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at =",
"is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is",
"models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True)",
"models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is None:",
"= models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception",
"pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception",
"pickle from typing import Any from django.db import models class Task(models.Model): pickled_task =",
"models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if",
"from django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True)",
"def started(self) -> bool: return self.started_at is not None def finished(self) -> bool:",
"import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at =",
"pickled_task = models.BinaryField(max_length=4096) pool = models.CharField(max_length=256, null=True) queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True)",
"queued_at = models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True)",
"bool: return self.started_at is not None def finished(self) -> bool: return self.finished_at is",
"self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at",
"null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def exception(self): if self.pickled_exception is None: return",
"= models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True)",
"self.finished_at is not None def successful(self) -> bool: return self.finished() and self.pickled_return is",
"from typing import Any from django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096)",
"None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is not",
"import base64 import pickle from typing import Any from django.db import models class",
"None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return self.started_at is not None def",
"return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property def return_value(self): if self.pickled_return is None: return None",
"= models.DateTimeField(auto_now_add=True) started_at = models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return",
"import Any from django.db import models class Task(models.Model): pickled_task = models.BinaryField(max_length=4096) pool =",
"base64 import pickle from typing import Any from django.db import models class Task(models.Model):",
"models.DateTimeField(null=True) finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property",
"finished_at = models.DateTimeField(null=True) pickled_exception = models.BinaryField(max_length=2048, null=True) pickled_return = models.BinaryField(max_length=4096, null=True) @property def",
"if self.pickled_return is None: return None return pickle.loads(base64.b64decode(self.pickled_return)) def started(self) -> bool: return",
"null=True) @property def exception(self): if self.pickled_exception is None: return None return pickle.loads(base64.b64decode(self.pickled_exception)) @property"
] |
[
"from pyevolve import Statistics from pyevolve import DBAdapters import pyevolve # This function",
"Wheel selector method, the number of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel)",
"for value in chromosome: if value==0: score += 1 return score # Enable",
"Sets the range max and min of the 1D List genome.setParams(rangemin=0, rangemax=30) #",
"iterate over the chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList)) for value",
"data every run, you should use this flag # just in the first",
"# Set the Roulette Wheel selector method, the number of generations and #",
"score = 0.0 # iterate over the chromosome # score = len(filter(lambda x:",
"will make the Adapter recreate # the database and erase all data every",
"value in chromosome: if value==0: score += 1 return score # Enable the",
"of 50 elements genome = G1DList.G1DList(10) # Sets the range max and min",
"generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB",
"instance, 1D List of 50 elements genome = G1DList.G1DList(10) # Sets the range",
"Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method,",
"just in the first time, after the pyevolve.db was created, you can #",
"of the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func)",
"Statistics from pyevolve import DBAdapters import pyevolve # This function is the evaluation",
"Do the evolution, with stats dump # frequency of 20 generations ga.evolve(freq_stats=20) #",
"the database and erase all data every run, you should use this flag",
"high score to more zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate",
"Enable the pyevolve logging system pyevolve.logEnable() # Genome instance, 1D List of 50",
"genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel",
"min of the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function)",
"over the chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList)) for value in",
"first time, after the pyevolve.db was created, you can # omit it. sqlite_adapter",
"pyevolve import Statistics from pyevolve import DBAdapters import pyevolve # This function is",
"= GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method, the number of generations",
"import Statistics from pyevolve import DBAdapters import pyevolve # This function is the",
"ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method, the number of",
"pyevolve.db was created, you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter)",
"the number of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) #",
"50 elements genome = G1DList.G1DList(10) # Sets the range max and min of",
"stats dump # frequency of 20 generations ga.evolve(freq_stats=20) # Best individual print ga.bestIndividual()",
"max and min of the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function",
"selector method, the number of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100)",
"# just in the first time, after the pyevolve.db was created, you can",
"ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump # frequency of 20 generations",
"the chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome:",
"chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome: if",
"# score = len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome: if value==0:",
"the pyevolve.db was created, you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True)",
"the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB",
"pyevolve import Selectors from pyevolve import Statistics from pyevolve import DBAdapters import pyevolve",
"This function is the evaluation function, we want # to give high score",
"= G1DList.G1DList(10) # Sets the range max and min of the 1D List",
"Roulette Wheel selector method, the number of generations and # the termination criteria",
"the Roulette Wheel selector method, the number of generations and # the termination",
"in the first time, after the pyevolve.db was created, you can # omit",
"criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB flag will",
"<reponame>janaobsteter/Genotype_CODES from pyevolve import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors",
"of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the",
"resetDB flag will make the Adapter recreate # the database and erase all",
"Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method, the",
"# the database and erase all data every run, you should use this",
"the Adapter recreate # the database and erase all data every run, you",
"evolution, with stats dump # frequency of 20 generations ga.evolve(freq_stats=20) # Best individual",
"run, you should use this flag # just in the first time, after",
"G1DList from pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve import Statistics",
"give high score to more zero'ed chromosomes def eval_func(chromosome): score = 0.0 #",
"DBAdapters import pyevolve # This function is the evaluation function, we want #",
"# Sets the DB Adapter, the resetDB flag will make the Adapter recreate",
"# iterate over the chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList)) for",
"chromosome.genomeList)) for value in chromosome: if value==0: score += 1 return score #",
"score += 1 return score # Enable the pyevolve logging system pyevolve.logEnable() #",
"it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump",
"want # to give high score to more zero'ed chromosomes def eval_func(chromosome): score",
"def eval_func(chromosome): score = 0.0 # iterate over the chromosome # score =",
"pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve import Statistics from pyevolve",
"The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome)",
"# The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga =",
"List of 50 elements genome = G1DList.G1DList(10) # Sets the range max and",
"import pyevolve # This function is the evaluation function, we want # to",
"score = len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome: if value==0: score",
"method, the number of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)",
"to more zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate over the",
"import Selectors from pyevolve import Statistics from pyevolve import DBAdapters import pyevolve #",
"range max and min of the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator",
"x==0, chromosome.genomeList)) for value in chromosome: if value==0: score += 1 return score",
"0.0 # iterate over the chromosome # score = len(filter(lambda x: x==0, chromosome.genomeList))",
"rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga",
"the first time, after the pyevolve.db was created, you can # omit it.",
"1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic",
"1D List of 50 elements genome = G1DList.G1DList(10) # Sets the range max",
"# omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with",
"the evolution, with stats dump # frequency of 20 generations ga.evolve(freq_stats=20) # Best",
"x: x==0, chromosome.genomeList)) for value in chromosome: if value==0: score += 1 return",
"recreate # the database and erase all data every run, you should use",
"elements genome = G1DList.G1DList(10) # Sets the range max and min of the",
"# Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector",
"pyevolve import DBAdapters import pyevolve # This function is the evaluation function, we",
"score to more zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate over",
"time, after the pyevolve.db was created, you can # omit it. sqlite_adapter =",
"make the Adapter recreate # the database and erase all data every run,",
"Selectors from pyevolve import Statistics from pyevolve import DBAdapters import pyevolve # This",
"# to give high score to more zero'ed chromosomes def eval_func(chromosome): score =",
"created, you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do",
"function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette",
"evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) #",
"and min of the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation",
"if value==0: score += 1 return score # Enable the pyevolve logging system",
"evaluation function, we want # to give high score to more zero'ed chromosomes",
"# the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the",
"ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB flag will make the Adapter",
"DB Adapter, the resetDB flag will make the Adapter recreate # the database",
"database and erase all data every run, you should use this flag #",
"pyevolve.logEnable() # Genome instance, 1D List of 50 elements genome = G1DList.G1DList(10) #",
"this flag # just in the first time, after the pyevolve.db was created,",
"the DB Adapter, the resetDB flag will make the Adapter recreate # the",
"flag # just in the first time, after the pyevolve.db was created, you",
"was created, you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) #",
"sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump #",
"function, we want # to give high score to more zero'ed chromosomes def",
"should use this flag # just in the first time, after the pyevolve.db",
"pyevolve logging system pyevolve.logEnable() # Genome instance, 1D List of 50 elements genome",
"1 return score # Enable the pyevolve logging system pyevolve.logEnable() # Genome instance,",
"you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the",
"eval_func(chromosome): score = 0.0 # iterate over the chromosome # score = len(filter(lambda",
"pyevolve import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve",
"Adapter, the resetDB flag will make the Adapter recreate # the database and",
"flag will make the Adapter recreate # the database and erase all data",
"Adapter recreate # the database and erase all data every run, you should",
"in chromosome: if value==0: score += 1 return score # Enable the pyevolve",
"omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats",
"ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB flag will make",
"can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution,",
"number of generations and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets",
"from pyevolve import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors from",
"= 0.0 # iterate over the chromosome # score = len(filter(lambda x: x==0,",
"we want # to give high score to more zero'ed chromosomes def eval_func(chromosome):",
"Set the Roulette Wheel selector method, the number of generations and # the",
"# Sets the range max and min of the 1D List genome.setParams(rangemin=0, rangemax=30)",
"the range max and min of the 1D List genome.setParams(rangemin=0, rangemax=30) # The",
"pyevolve # This function is the evaluation function, we want # to give",
"from pyevolve import DBAdapters import pyevolve # This function is the evaluation function,",
"return score # Enable the pyevolve logging system pyevolve.logEnable() # Genome instance, 1D",
"function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set",
"GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method, the number of generations and",
"use this flag # just in the first time, after the pyevolve.db was",
"List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm",
"the pyevolve logging system pyevolve.logEnable() # Genome instance, 1D List of 50 elements",
"to give high score to more zero'ed chromosomes def eval_func(chromosome): score = 0.0",
"(evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) # Set the",
"score # Enable the pyevolve logging system pyevolve.logEnable() # Genome instance, 1D List",
"and erase all data every run, you should use this flag # just",
"resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump # frequency of 20",
"Sets the DB Adapter, the resetDB flag will make the Adapter recreate #",
"erase all data every run, you should use this flag # just in",
"function is the evaluation function, we want # to give high score to",
"more zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate over the chromosome",
"= DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump # frequency",
"zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate over the chromosome #",
"every run, you should use this flag # just in the first time,",
"from pyevolve import Selectors from pyevolve import Statistics from pyevolve import DBAdapters import",
"# This function is the evaluation function, we want # to give high",
"all data every run, you should use this flag # just in the",
"import DBAdapters import pyevolve # This function is the evaluation function, we want",
"is the evaluation function, we want # to give high score to more",
"ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB flag will make the",
"the 1D List genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func) #",
"value==0: score += 1 return score # Enable the pyevolve logging system pyevolve.logEnable()",
"# Enable the pyevolve logging system pyevolve.logEnable() # Genome instance, 1D List of",
"import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve import",
"import GSimpleGA from pyevolve import Selectors from pyevolve import Statistics from pyevolve import",
"len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome: if value==0: score += 1",
"genome.setParams(rangemin=0, rangemax=30) # The evaluator function (evaluation function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance",
"Genome instance, 1D List of 50 elements genome = G1DList.G1DList(10) # Sets the",
"genome = G1DList.G1DList(10) # Sets the range max and min of the 1D",
"logging system pyevolve.logEnable() # Genome instance, 1D List of 50 elements genome =",
"the resetDB flag will make the Adapter recreate # the database and erase",
"# Do the evolution, with stats dump # frequency of 20 generations ga.evolve(freq_stats=20)",
"you should use this flag # just in the first time, after the",
"+= 1 return score # Enable the pyevolve logging system pyevolve.logEnable() # Genome",
"after the pyevolve.db was created, you can # omit it. sqlite_adapter = DBAdapters.DBSQLite(identify=\"ex1\",",
"= len(filter(lambda x: x==0, chromosome.genomeList)) for value in chromosome: if value==0: score +=",
"and # the termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter,",
"chromosome: if value==0: score += 1 return score # Enable the pyevolve logging",
"GSimpleGA from pyevolve import Selectors from pyevolve import Statistics from pyevolve import DBAdapters",
"DBAdapters.DBSQLite(identify=\"ex1\", resetDB=True) ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump # frequency of",
"chromosomes def eval_func(chromosome): score = 0.0 # iterate over the chromosome # score",
"the evaluation function, we want # to give high score to more zero'ed",
"system pyevolve.logEnable() # Genome instance, 1D List of 50 elements genome = G1DList.G1DList(10)",
"termination criteria ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(100) ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria) # Sets the DB Adapter, the resetDB flag",
"Instance ga = GSimpleGA.GSimpleGA(genome) # Set the Roulette Wheel selector method, the number",
"from pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve import Statistics from",
"with stats dump # frequency of 20 generations ga.evolve(freq_stats=20) # Best individual print",
"# Genome instance, 1D List of 50 elements genome = G1DList.G1DList(10) # Sets",
"G1DList.G1DList(10) # Sets the range max and min of the 1D List genome.setParams(rangemin=0,"
] |
[
"-1 self.rear = -1 self.size = k def enQueue(self, value: int) -> bool:",
"self.rear: self.front = self.rear = -1 else: self.front = (self.front + 1) %",
"the circular queue is full or not. - You must solve the problem",
"self.size = k def enQueue(self, value: int) -> bool: if self.isFull(): return False",
"make use of the spaces in front of the queue. In a normal",
"= -1 self.rear = -1 self.size = k def enQueue(self, value: int) ->",
"such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is True assert",
"FIFO (First In First Out) principle and the last position is connected back",
"true, true, true, false, 3, true, true, true, 4] Explanation - MyCircularQueue myCircularQueue",
"return self.front == -1 def isFull(self) -> bool: return (self.rear + 1) %",
"import List class MyCircularQueue: def __init__(self, k: int): self.arr = [None] * k",
"obj.isFull() is True assert obj.deQueue() is True assert obj.enQueue(4) is True assert obj.Rear()",
"True assert obj.enQueue(3) is True assert obj.enQueue(4) is False assert obj.Rear() == 3",
"structure in which the operations are performed based on FIFO (First In First",
"implementation of the circular queue. The circular queue is a linear data structure",
"queue is empty, return -1. - boolean enQueue(int value) Inserts an element into",
"self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self)",
"of the queue to be k. - int Front() Gets the front item",
"True - myCircularQueue.Rear(); // return 4 Constraints: 1 <= k <= 1000 0",
"true, true, true, 4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1);",
"[], [], [], [4], []] Output: [null, true, true, true, false, 3, true,",
"the last position is connected back to the first position to make a",
"obj.enQueue(4) is False assert obj.Rear() == 3 assert obj.isFull() is True assert obj.deQueue()",
"a circle. It is also called \"Ring Buffer\". One of the benefits of",
"becomes full, we cannot insert the next element even if there is a",
"use of the spaces in front of the queue. In a normal queue,",
"we cannot insert the next element even if there is a space in",
"based on FIFO (First In First Out) principle and the last position is",
"not. - boolean isFull() Checks whether the circular queue is full or not.",
"MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is True assert obj.enQueue(3) is True",
"[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2],",
"__init__(self, k: int): self.arr = [None] * k self.front = -1 self.rear =",
"- myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); //",
"myCircularQueue.Rear(); // return 4 Constraints: 1 <= k <= 1000 0 <= value",
"is empty, return -1. - int Rear() Gets the last item from the",
"return True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return 4 Constraints:",
"size of the queue to be k. - int Front() Gets the front",
"False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue();",
"= new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return True",
"myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return",
"your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\",",
"self.front = -1 self.rear = -1 self.size = k def enQueue(self, value: int)",
"-> int: if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) -> bool: return",
"next element even if there is a space in front of the queue.",
"return True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return 3 -",
"// return 3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return True",
"whether the circular queue is empty or not. - boolean isFull() Checks whether",
"queue to be k. - int Front() Gets the front item from the",
"deQueue() Deletes an element from the circular queue. Return true if the operation",
"of the spaces in front of the queue. In a normal queue, once",
"if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) -> bool: return self.front ==",
"int: if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) -> bool: return self.front",
"of the benefits of the circular queue is that we can make use",
"int Front() Gets the front item from the queue. If the queue is",
"3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.",
"= self.rear = -1 else: self.front = (self.front + 1) % self.size return",
"assert obj.enQueue(1) is True assert obj.enQueue(2) is True assert obj.enQueue(3) is True assert",
"// return True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return False",
"True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull();",
"must solve the problem without using the built-in queue data structure in your",
"the spaces in front of the queue. In a normal queue, once the",
"a normal queue, once the queue becomes full, we cannot insert the next",
"new values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the object with the",
"3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4);",
"bool: if self.isFull(): return False if self.isEmpty(): self.front = 0 self.rear = (self.rear",
"Deletes an element from the circular queue. Return true if the operation is",
"using the built-in queue data structure in your programming language. Example 1: Input:",
"the front item from the queue. If the queue is empty, return -1.",
"queue. If the queue is empty, return -1. - int Rear() Gets the",
"not. - You must solve the problem without using the built-in queue data",
"[null, true, true, true, false, 3, true, true, true, 4] Explanation - MyCircularQueue",
"= MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is True assert obj.enQueue(3) is",
"will be instantiated and called as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is",
"myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return",
"else: self.front = (self.front + 1) % self.size return True def Front(self) ->",
"in your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\",",
"queue becomes full, we cannot insert the next element even if there is",
"an element from the circular queue. Return true if the operation is successful.",
"-> bool: return self.front == -1 def isFull(self) -> bool: return (self.rear +",
"circular queue is a linear data structure in which the operations are performed",
"Rear(self) -> int: if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) -> bool:",
"return True - myCircularQueue.Rear(); // return 4 Constraints: 1 <= k <= 1000",
"self.arr[self.rear] = value return True def deQueue(self) -> bool: if self.isEmpty(): return False",
"value <= 1000 At most 3000 calls will be made to enQueue, deQueue,",
"isFull() Checks whether the circular queue is full or not. - You must",
"return -1. - boolean enQueue(int value) Inserts an element into the circular queue.",
"in front of the queue. But using the circular queue, we can use",
"Rear, isEmpty, and isFull. \"\"\" from typing import List class MyCircularQueue: def __init__(self,",
"------------------ Design your implementation of the circular queue. The circular queue is a",
"True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear();",
"called \"Ring Buffer\". One of the benefits of the circular queue is that",
"True assert obj.enQueue(2) is True assert obj.enQueue(3) is True assert obj.enQueue(4) is False",
"true, 4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return",
"the built-in queue data structure in your programming language. Example 1: Input: [\"MyCircularQueue\",",
"is empty, return -1. - boolean enQueue(int value) Inserts an element into the",
"def enQueue(self, value: int) -> bool: if self.isFull(): return False if self.isEmpty(): self.front",
"the object with the size of the queue to be k. - int",
"circular queue. Return true if the operation is successful. - boolean isEmpty() Checks",
"true, false, 3, true, true, true, 4] Explanation - MyCircularQueue myCircularQueue = new",
"built-in queue data structure in your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\",",
"value: int) -> bool: if self.isFull(): return False if self.isEmpty(): self.front = 0",
"= (self.front + 1) % self.size return True def Front(self) -> int: if",
"== -1 def isFull(self) -> bool: return (self.rear + 1) % self.size ==",
"(self.front + 1) % self.size return True def Front(self) -> int: if self.isEmpty():",
"made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from typing import",
"true if the operation is successful. - boolean isEmpty() Checks whether the circular",
"self.front = (self.front + 1) % self.size return True def Front(self) -> int:",
"operation is successful. - boolean isEmpty() Checks whether the circular queue is empty",
"queue. Return true if the operation is successful. - boolean isEmpty() Checks whether",
"-1. - boolean enQueue(int value) Inserts an element into the circular queue. Return",
"the queue. If the queue is empty, return -1. - boolean enQueue(int value)",
"last item from the queue. If the queue is empty, return -1. -",
"normal queue, once the queue becomes full, we cannot insert the next element",
"class: - MyCircularQueue(k) Initializes the object with the size of the queue to",
"deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from typing import List class MyCircularQueue:",
"1) % self.size self.arr[self.rear] = value return True def deQueue(self) -> bool: if",
"<= 1000 At most 3000 calls will be made to enQueue, deQueue, Front,",
"-1 return self.arr[self.rear] def isEmpty(self) -> bool: return self.front == -1 def isFull(self)",
"queue is empty, return -1. - int Rear() Gets the last item from",
"circular queue is full or not. - You must solve the problem without",
"\"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [],",
"def Front(self) -> int: if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) ->",
"on FIFO (First In First Out) principle and the last position is connected",
"self.rear = -1 self.size = k def enQueue(self, value: int) -> bool: if",
"- int Rear() Gets the last item from the queue. If the queue",
"obj.Rear() == 3 assert obj.isFull() is True assert obj.deQueue() is True assert obj.enQueue(4)",
"benefits of the circular queue is that we can make use of the",
"False if self.front == self.rear: self.front = self.rear = -1 else: self.front =",
"the queue. If the queue is empty, return -1. - int Rear() Gets",
"enQueue(self, value: int) -> bool: if self.isFull(): return False if self.isEmpty(): self.front =",
"successful. - boolean isEmpty() Checks whether the circular queue is empty or not.",
"-1 return self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return -1 return self.arr[self.rear]",
"boolean deQueue() Deletes an element from the circular queue. Return true if the",
"empty, return -1. - boolean enQueue(int value) Inserts an element into the circular",
"queue is that we can make use of the spaces in front of",
"circular queue. The circular queue is a linear data structure in which the",
"% self.size self.arr[self.rear] = value return True def deQueue(self) -> bool: if self.isEmpty():",
"self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) -> bool: return self.front == -1",
"self.size == self.front # Your MyCircularQueue object will be instantiated and called as",
"[3], [4], [], [], [], [4], []] Output: [null, true, true, true, false,",
"Gets the front item from the queue. If the queue is empty, return",
"- You must solve the problem without using the built-in queue data structure",
"(self.rear + 1) % self.size == self.front # Your MyCircularQueue object will be",
"== self.front # Your MyCircularQueue object will be instantiated and called as such:",
"At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty,",
"[], [4], []] Output: [null, true, true, true, false, 3, true, true, true,",
"// return True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return True",
"is True assert obj.enQueue(3) is True assert obj.enQueue(4) is False assert obj.Rear() ==",
"return True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return True -",
"self.size return True def Front(self) -> int: if self.isEmpty(): return -1 return self.arr[self.front]",
"to enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from typing import List",
"full or not. - You must solve the problem without using the built-in",
"or not. - boolean isFull() Checks whether the circular queue is full or",
"if there is a space in front of the queue. But using the",
"the operation is successful. - boolean deQueue() Deletes an element from the circular",
"true if the operation is successful. - boolean deQueue() Deletes an element from",
"and the last position is connected back to the first position to make",
"[1], [2], [3], [4], [], [], [], [4], []] Output: [null, true, true,",
"value return True def deQueue(self) -> bool: if self.isEmpty(): return False if self.front",
"<= value <= 1000 At most 3000 calls will be made to enQueue,",
"In a normal queue, once the queue becomes full, we cannot insert the",
"\"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [], [], [], [4], []]",
"// return True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return 3",
"k def enQueue(self, value: int) -> bool: if self.isFull(): return False if self.isEmpty():",
"empty, return -1. - int Rear() Gets the last item from the queue.",
"- boolean isFull() Checks whether the circular queue is full or not. -",
"empty or not. - boolean isFull() Checks whether the circular queue is full",
"performed based on FIFO (First In First Out) principle and the last position",
"true, true, 4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); //",
"def isFull(self) -> bool: return (self.rear + 1) % self.size == self.front #",
"the circular queue. Return true if the operation is successful. - boolean deQueue()",
"self.front = self.rear = -1 else: self.front = (self.front + 1) % self.size",
"of the queue. In a normal queue, once the queue becomes full, we",
"to the first position to make a circle. It is also called \"Ring",
"queue is full or not. - You must solve the problem without using",
"Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the object with the size of",
"== self.rear: self.front = self.rear = -1 else: self.front = (self.front + 1)",
"as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is True",
"- myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); //",
"Front() Gets the front item from the queue. If the queue is empty,",
"enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from typing import List class",
"Checks whether the circular queue is empty or not. - boolean isFull() Checks",
"called as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is",
"of the queue. But using the circular queue, we can use the space",
"the queue is empty, return -1. - boolean enQueue(int value) Inserts an element",
"circle. It is also called \"Ring Buffer\". One of the benefits of the",
"3 assert obj.isFull() is True assert obj.deQueue() is True assert obj.enQueue(4) is True",
"to be k. - int Front() Gets the front item from the queue.",
"return True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return False -",
"Gets the last item from the queue. If the queue is empty, return",
"circular queue. Return true if the operation is successful. - boolean deQueue() Deletes",
"new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return True -",
"myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return",
"= 0 self.rear = (self.rear + 1) % self.size self.arr[self.rear] = value return",
"+ 1) % self.size == self.front # Your MyCircularQueue object will be instantiated",
"which the operations are performed based on FIFO (First In First Out) principle",
"k. - int Front() Gets the front item from the queue. If the",
"return True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return True -",
"# Your MyCircularQueue object will be instantiated and called as such: obj =",
"True assert obj.deQueue() is True assert obj.enQueue(4) is True assert obj.Rear() == 4",
"\"Ring Buffer\". One of the benefits of the circular queue is that we",
"0 <= value <= 1000 At most 3000 calls will be made to",
"https://leetcode.com/explore/learn/card/queue-stack/228/first-in-first-out-data-structure/1337/ Problem Statement: ------------------ Design your implementation of the circular queue. The circular",
"queue. If the queue is empty, return -1. - boolean enQueue(int value) Inserts",
"is successful. - boolean isEmpty() Checks whether the circular queue is empty or",
"myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return",
"deQueue(self) -> bool: if self.isEmpty(): return False if self.front == self.rear: self.front =",
"+ 1) % self.size self.arr[self.rear] = value return True def deQueue(self) -> bool:",
"most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and",
"int): self.arr = [None] * k self.front = -1 self.rear = -1 self.size",
"principle and the last position is connected back to the first position to",
"MyCircularQueue object will be instantiated and called as such: obj = MyCircularQueue(3) assert",
"a space in front of the queue. But using the circular queue, we",
"calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\"",
"False assert obj.Rear() == 3 assert obj.isFull() is True assert obj.deQueue() is True",
"store new values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the object with",
"[], [], [4], []] Output: [null, true, true, true, false, 3, true, true,",
"return True def Front(self) -> int: if self.isEmpty(): return -1 return self.arr[self.front] def",
"the MyCircularQueue class: - MyCircularQueue(k) Initializes the object with the size of the",
"MyCircularQueue class: - MyCircularQueue(k) Initializes the object with the size of the queue",
"the circular queue is that we can make use of the spaces in",
"4 Constraints: 1 <= k <= 1000 0 <= value <= 1000 At",
"boolean enQueue(int value) Inserts an element into the circular queue. Return true if",
"the circular queue. Return true if the operation is successful. - boolean isEmpty()",
"make a circle. It is also called \"Ring Buffer\". One of the benefits",
"In First Out) principle and the last position is connected back to the",
"if self.isEmpty(): return False if self.front == self.rear: self.front = self.rear = -1",
"if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return",
"self.front # Your MyCircularQueue object will be instantiated and called as such: obj",
"the queue. But using the circular queue, we can use the space to",
"obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2) is True assert obj.enQueue(3)",
"self.arr = [None] * k self.front = -1 self.rear = -1 self.size =",
"in front of the queue. In a normal queue, once the queue becomes",
"space to store new values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the",
"if the operation is successful. - boolean deQueue() Deletes an element from the",
"your implementation of the circular queue. The circular queue is a linear data",
"\"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [], [],",
"queue. The circular queue is a linear data structure in which the operations",
"myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return 4 Constraints: 1 <= k",
"Buffer\". One of the benefits of the circular queue is that we can",
"successful. - boolean deQueue() Deletes an element from the circular queue. Return true",
"position is connected back to the first position to make a circle. It",
"myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return",
"// return True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return True",
"True def deQueue(self) -> bool: if self.isEmpty(): return False if self.front == self.rear:",
"or not. - You must solve the problem without using the built-in queue",
"(self.rear + 1) % self.size self.arr[self.rear] = value return True def deQueue(self) ->",
"return 4 Constraints: 1 <= k <= 1000 0 <= value <= 1000",
"Return true if the operation is successful. - boolean deQueue() Deletes an element",
"queue. Return true if the operation is successful. - boolean deQueue() Deletes an",
"True def Front(self) -> int: if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self)",
"return -1 return self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return -1 return",
"with the size of the queue to be k. - int Front() Gets",
"Statement: ------------------ Design your implementation of the circular queue. The circular queue is",
"First Out) principle and the last position is connected back to the first",
"return -1. - int Rear() Gets the last item from the queue. If",
"the space to store new values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes",
"isEmpty(self) -> bool: return self.front == -1 def isFull(self) -> bool: return (self.rear",
"is True assert obj.enQueue(4) is False assert obj.Rear() == 3 assert obj.isFull() is",
"MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); //",
"that we can make use of the spaces in front of the queue.",
"1000 0 <= value <= 1000 At most 3000 calls will be made",
"front of the queue. In a normal queue, once the queue becomes full,",
"a linear data structure in which the operations are performed based on FIFO",
"True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4);",
"def Rear(self) -> int: if self.isEmpty(): return -1 return self.arr[self.rear] def isEmpty(self) ->",
"\"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4],",
"Your MyCircularQueue object will be instantiated and called as such: obj = MyCircularQueue(3)",
"\"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [], [], [], [4],",
"MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3);",
"to make a circle. It is also called \"Ring Buffer\". One of the",
"It is also called \"Ring Buffer\". One of the benefits of the circular",
"\"\"\" URL: https://leetcode.com/explore/learn/card/queue-stack/228/first-in-first-out-data-structure/1337/ Problem Statement: ------------------ Design your implementation of the circular queue.",
"data structure in which the operations are performed based on FIFO (First In",
"front item from the queue. If the queue is empty, return -1. -",
"is a linear data structure in which the operations are performed based on",
"bool: return (self.rear + 1) % self.size == self.front # Your MyCircularQueue object",
"[[3], [1], [2], [3], [4], [], [], [], [4], []] Output: [null, true,",
"// return False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return True",
"* k self.front = -1 self.rear = -1 self.size = k def enQueue(self,",
"typing import List class MyCircularQueue: def __init__(self, k: int): self.arr = [None] *",
"One of the benefits of the circular queue is that we can make",
"myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return",
"self.arr[self.rear] def isEmpty(self) -> bool: return self.front == -1 def isFull(self) -> bool:",
"from the queue. If the queue is empty, return -1. - boolean enQueue(int",
"of the circular queue is that we can make use of the spaces",
"isEmpty, and isFull. \"\"\" from typing import List class MyCircularQueue: def __init__(self, k:",
"Design your implementation of the circular queue. The circular queue is a linear",
"If the queue is empty, return -1. - boolean enQueue(int value) Inserts an",
"True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return 4 Constraints: 1",
"the first position to make a circle. It is also called \"Ring Buffer\".",
"the queue becomes full, we cannot insert the next element even if there",
"def deQueue(self) -> bool: if self.isEmpty(): return False if self.front == self.rear: self.front",
"boolean isEmpty() Checks whether the circular queue is empty or not. - boolean",
"back to the first position to make a circle. It is also called",
"queue is a linear data structure in which the operations are performed based",
"\"Rear\"] [[3], [1], [2], [3], [4], [], [], [], [4], []] Output: [null,",
"space in front of the queue. But using the circular queue, we can",
"k: int): self.arr = [None] * k self.front = -1 self.rear = -1",
"You must solve the problem without using the built-in queue data structure in",
"queue data structure in your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\",",
"= k def enQueue(self, value: int) -> bool: if self.isFull(): return False if",
"insert the next element even if there is a space in front of",
"first position to make a circle. It is also called \"Ring Buffer\". One",
"the queue is empty, return -1. - int Rear() Gets the last item",
"connected back to the first position to make a circle. It is also",
"front of the queue. But using the circular queue, we can use the",
"self.size self.arr[self.rear] = value return True def deQueue(self) -> bool: if self.isEmpty(): return",
"into the circular queue. Return true if the operation is successful. - boolean",
"the operation is successful. - boolean isEmpty() Checks whether the circular queue is",
"if self.front == self.rear: self.front = self.rear = -1 else: self.front = (self.front",
"Checks whether the circular queue is full or not. - You must solve",
"1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3],",
"an element into the circular queue. Return true if the operation is successful.",
"be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from typing",
"Out) principle and the last position is connected back to the first position",
"even if there is a space in front of the queue. But using",
"- myCircularQueue.enQueue(4); // return False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); //",
"is empty or not. - boolean isFull() Checks whether the circular queue is",
"myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); // return",
"False if self.isEmpty(): self.front = 0 self.rear = (self.rear + 1) % self.size",
"is successful. - boolean deQueue() Deletes an element from the circular queue. Return",
"and called as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert obj.enQueue(2)",
"is True assert obj.deQueue() is True assert obj.enQueue(4) is True assert obj.Rear() ==",
"queue. In a normal queue, once the queue becomes full, we cannot insert",
"- MyCircularQueue(k) Initializes the object with the size of the queue to be",
"enQueue(int value) Inserts an element into the circular queue. Return true if the",
"self.isEmpty(): self.front = 0 self.rear = (self.rear + 1) % self.size self.arr[self.rear] =",
"- myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); // return True - myCircularQueue.enQueue(4); //",
"- MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2);",
"1) % self.size == self.front # Your MyCircularQueue object will be instantiated and",
"URL: https://leetcode.com/explore/learn/card/queue-stack/228/first-in-first-out-data-structure/1337/ Problem Statement: ------------------ Design your implementation of the circular queue. The",
"the last item from the queue. If the queue is empty, return -1.",
"assert obj.isFull() is True assert obj.deQueue() is True assert obj.enQueue(4) is True assert",
"[4], []] Output: [null, true, true, true, false, 3, true, true, true, 4]",
"is connected back to the first position to make a circle. It is",
"if the operation is successful. - boolean isEmpty() Checks whether the circular queue",
"there is a space in front of the queue. But using the circular",
"int Rear() Gets the last item from the queue. If the queue is",
"Output: [null, true, true, true, false, 3, true, true, true, 4] Explanation -",
"is True assert obj.enQueue(2) is True assert obj.enQueue(3) is True assert obj.enQueue(4) is",
"instantiated and called as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True assert",
"is also called \"Ring Buffer\". One of the benefits of the circular queue",
"the circular queue is empty or not. - boolean isFull() Checks whether the",
"Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1],",
"int: if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) -> int: if self.isEmpty():",
"element into the circular queue. Return true if the operation is successful. -",
"// return True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return 4",
"will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. \"\"\" from",
"be instantiated and called as such: obj = MyCircularQueue(3) assert obj.enQueue(1) is True",
"True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear();",
"and isFull. \"\"\" from typing import List class MyCircularQueue: def __init__(self, k: int):",
"// return 4 Constraints: 1 <= k <= 1000 0 <= value <=",
"self.isEmpty(): return False if self.front == self.rear: self.front = self.rear = -1 else:",
"last position is connected back to the first position to make a circle.",
"solve the problem without using the built-in queue data structure in your programming",
"item from the queue. If the queue is empty, return -1. - boolean",
"\"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [], [], [], [4], []] Output:",
"assert obj.enQueue(4) is False assert obj.Rear() == 3 assert obj.isFull() is True assert",
"Front, Rear, isEmpty, and isFull. \"\"\" from typing import List class MyCircularQueue: def",
"value) Inserts an element into the circular queue. Return true if the operation",
"obj.enQueue(2) is True assert obj.enQueue(3) is True assert obj.enQueue(4) is False assert obj.Rear()",
"MyCircularQueue(k) Initializes the object with the size of the queue to be k.",
"isFull. \"\"\" from typing import List class MyCircularQueue: def __init__(self, k: int): self.arr",
"the circular queue. The circular queue is a linear data structure in which",
"element from the circular queue. Return true if the operation is successful. -",
"self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return -1",
"- myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return True - myCircularQueue.enQueue(4); //",
"true, true, false, 3, true, true, true, 4] Explanation - MyCircularQueue myCircularQueue =",
"1) % self.size return True def Front(self) -> int: if self.isEmpty(): return -1",
"boolean isFull() Checks whether the circular queue is full or not. - You",
"from the queue. If the queue is empty, return -1. - int Rear()",
"[4], [], [], [], [4], []] Output: [null, true, true, true, false, 3,",
"== 3 assert obj.isFull() is True assert obj.deQueue() is True assert obj.enQueue(4) is",
"assert obj.Rear() == 3 assert obj.isFull() is True assert obj.deQueue() is True assert",
"Problem Statement: ------------------ Design your implementation of the circular queue. The circular queue",
"circular queue is empty or not. - boolean isFull() Checks whether the circular",
"element even if there is a space in front of the queue. But",
"self.rear = (self.rear + 1) % self.size self.arr[self.rear] = value return True def",
"int) -> bool: if self.isFull(): return False if self.isEmpty(): self.front = 0 self.rear",
"Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True -",
"1 <= k <= 1000 0 <= value <= 1000 At most 3000",
"class MyCircularQueue: def __init__(self, k: int): self.arr = [None] * k self.front =",
"-> bool: return (self.rear + 1) % self.size == self.front # Your MyCircularQueue",
"def isEmpty(self) -> bool: return self.front == -1 def isFull(self) -> bool: return",
"is full or not. - You must solve the problem without using the",
"% self.size == self.front # Your MyCircularQueue object will be instantiated and called",
"cannot insert the next element even if there is a space in front",
"the queue to be k. - int Front() Gets the front item from",
"operations are performed based on FIFO (First In First Out) principle and the",
"Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]",
"the size of the queue to be k. - int Front() Gets the",
"we can use the space to store new values. Implementation the MyCircularQueue class:",
"without using the built-in queue data structure in your programming language. Example 1:",
"self.isFull(): return False if self.isEmpty(): self.front = 0 self.rear = (self.rear + 1)",
"in which the operations are performed based on FIFO (First In First Out)",
"True assert obj.enQueue(4) is False assert obj.Rear() == 3 assert obj.isFull() is True",
"4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True",
"[2], [3], [4], [], [], [], [4], []] Output: [null, true, true, true,",
"myCircularQueue = new MyCircularQueue(3); - myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return",
"<= k <= 1000 0 <= value <= 1000 At most 3000 calls",
"the next element even if there is a space in front of the",
"-1 self.size = k def enQueue(self, value: int) -> bool: if self.isFull(): return",
"the operations are performed based on FIFO (First In First Out) principle and",
"-> int: if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) -> int: if",
"circular queue is that we can make use of the spaces in front",
"Constraints: 1 <= k <= 1000 0 <= value <= 1000 At most",
"is a space in front of the queue. But using the circular queue,",
"= value return True def deQueue(self) -> bool: if self.isEmpty(): return False if",
"linear data structure in which the operations are performed based on FIFO (First",
"bool: if self.isEmpty(): return False if self.front == self.rear: self.front = self.rear =",
"queue is empty or not. - boolean isFull() Checks whether the circular queue",
"-1. - int Rear() Gets the last item from the queue. If the",
"- boolean deQueue() Deletes an element from the circular queue. Return true if",
"use the space to store new values. Implementation the MyCircularQueue class: - MyCircularQueue(k)",
"\"\"\" from typing import List class MyCircularQueue: def __init__(self, k: int): self.arr =",
"- boolean isEmpty() Checks whether the circular queue is empty or not. -",
"- myCircularQueue.enQueue(4); // return True - myCircularQueue.Rear(); // return 4 Constraints: 1 <=",
"values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the object with the size",
"(First In First Out) principle and the last position is connected back to",
"if self.isFull(): return False if self.isEmpty(): self.front = 0 self.rear = (self.rear +",
"\"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3],",
"from typing import List class MyCircularQueue: def __init__(self, k: int): self.arr = [None]",
"= -1 else: self.front = (self.front + 1) % self.size return True def",
"The circular queue is a linear data structure in which the operations are",
"-> bool: if self.isEmpty(): return False if self.front == self.rear: self.front = self.rear",
"def __init__(self, k: int): self.arr = [None] * k self.front = -1 self.rear",
"queue, we can use the space to store new values. Implementation the MyCircularQueue",
"But using the circular queue, we can use the space to store new",
"0 self.rear = (self.rear + 1) % self.size self.arr[self.rear] = value return True",
"is False assert obj.Rear() == 3 assert obj.isFull() is True assert obj.deQueue() is",
"3, true, true, true, 4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3); -",
"Return true if the operation is successful. - boolean isEmpty() Checks whether the",
"circular queue, we can use the space to store new values. Implementation the",
"Initializes the object with the size of the queue to be k. -",
"to store new values. Implementation the MyCircularQueue class: - MyCircularQueue(k) Initializes the object",
"position to make a circle. It is also called \"Ring Buffer\". One of",
"= -1 self.size = k def enQueue(self, value: int) -> bool: if self.isFull():",
"programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\",",
"- boolean enQueue(int value) Inserts an element into the circular queue. Return true",
"k self.front = -1 self.rear = -1 self.size = k def enQueue(self, value:",
"also called \"Ring Buffer\". One of the benefits of the circular queue is",
"the benefits of the circular queue is that we can make use of",
"return True def deQueue(self) -> bool: if self.isEmpty(): return False if self.front ==",
"are performed based on FIFO (First In First Out) principle and the last",
"self.front == self.rear: self.front = self.rear = -1 else: self.front = (self.front +",
"queue. But using the circular queue, we can use the space to store",
"-1 else: self.front = (self.front + 1) % self.size return True def Front(self)",
"\"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"] [[3], [1], [2], [3], [4], [], [], [],",
"if self.isEmpty(): self.front = 0 self.rear = (self.rear + 1) % self.size self.arr[self.rear]",
"Rear() Gets the last item from the queue. If the queue is empty,",
"[]] Output: [null, true, true, true, false, 3, true, true, true, 4] Explanation",
"= (self.rear + 1) % self.size self.arr[self.rear] = value return True def deQueue(self)",
"assert obj.enQueue(3) is True assert obj.enQueue(4) is False assert obj.Rear() == 3 assert",
"we can make use of the spaces in front of the queue. In",
"object with the size of the queue to be k. - int Front()",
"return False if self.isEmpty(): self.front = 0 self.rear = (self.rear + 1) %",
"isEmpty() Checks whether the circular queue is empty or not. - boolean isFull()",
"operation is successful. - boolean deQueue() Deletes an element from the circular queue.",
"-1 def isFull(self) -> bool: return (self.rear + 1) % self.size == self.front",
"full, we cannot insert the next element even if there is a space",
"object will be instantiated and called as such: obj = MyCircularQueue(3) assert obj.enQueue(1)",
"- myCircularQueue.enQueue(1); // return True - myCircularQueue.enQueue(2); // return True - myCircularQueue.enQueue(3); //",
"the queue. In a normal queue, once the queue becomes full, we cannot",
"false, 3, true, true, true, 4] Explanation - MyCircularQueue myCircularQueue = new MyCircularQueue(3);",
"assert obj.enQueue(2) is True assert obj.enQueue(3) is True assert obj.enQueue(4) is False assert",
"spaces in front of the queue. In a normal queue, once the queue",
"isFull(self) -> bool: return (self.rear + 1) % self.size == self.front # Your",
"the problem without using the built-in queue data structure in your programming language.",
"- myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); //",
"Front(self) -> int: if self.isEmpty(): return -1 return self.arr[self.front] def Rear(self) -> int:",
"using the circular queue, we can use the space to store new values.",
"return 3 - myCircularQueue.isFull(); // return True - myCircularQueue.deQueue(); // return True -",
"return self.arr[self.rear] def isEmpty(self) -> bool: return self.front == -1 def isFull(self) ->",
"return self.arr[self.front] def Rear(self) -> int: if self.isEmpty(): return -1 return self.arr[self.rear] def",
"from the circular queue. Return true if the operation is successful. - boolean",
"- int Front() Gets the front item from the queue. If the queue",
"+ 1) % self.size return True def Front(self) -> int: if self.isEmpty(): return",
"// return True - myCircularQueue.Rear(); // return 4 Constraints: 1 <= k <=",
"once the queue becomes full, we cannot insert the next element even if",
"is that we can make use of the spaces in front of the",
"Inserts an element into the circular queue. Return true if the operation is",
"[None] * k self.front = -1 self.rear = -1 self.size = k def",
"List class MyCircularQueue: def __init__(self, k: int): self.arr = [None] * k self.front",
"can make use of the spaces in front of the queue. In a",
"language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\",",
"k <= 1000 0 <= value <= 1000 At most 3000 calls will",
"-> bool: if self.isFull(): return False if self.isEmpty(): self.front = 0 self.rear =",
"can use the space to store new values. Implementation the MyCircularQueue class: -",
"item from the queue. If the queue is empty, return -1. - int",
"obj.enQueue(1) is True assert obj.enQueue(2) is True assert obj.enQueue(3) is True assert obj.enQueue(4)",
"MyCircularQueue: def __init__(self, k: int): self.arr = [None] * k self.front = -1",
"whether the circular queue is full or not. - You must solve the",
"be k. - int Front() Gets the front item from the queue. If",
"self.front = 0 self.rear = (self.rear + 1) % self.size self.arr[self.rear] = value",
"the circular queue, we can use the space to store new values. Implementation",
"If the queue is empty, return -1. - int Rear() Gets the last",
"queue, once the queue becomes full, we cannot insert the next element even",
"= [None] * k self.front = -1 self.rear = -1 self.size = k",
"1000 At most 3000 calls will be made to enQueue, deQueue, Front, Rear,",
"self.front == -1 def isFull(self) -> bool: return (self.rear + 1) % self.size",
"bool: return self.front == -1 def isFull(self) -> bool: return (self.rear + 1)",
"self.rear = -1 else: self.front = (self.front + 1) % self.size return True",
"<= 1000 0 <= value <= 1000 At most 3000 calls will be",
"return -1 return self.arr[self.rear] def isEmpty(self) -> bool: return self.front == -1 def",
"- myCircularQueue.Rear(); // return 4 Constraints: 1 <= k <= 1000 0 <=",
"return (self.rear + 1) % self.size == self.front # Your MyCircularQueue object will",
"structure in your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\",",
"problem without using the built-in queue data structure in your programming language. Example",
"data structure in your programming language. Example 1: Input: [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\",",
"return False if self.front == self.rear: self.front = self.rear = -1 else: self.front",
"of the circular queue. The circular queue is a linear data structure in",
"return False - myCircularQueue.Rear(); // return 3 - myCircularQueue.isFull(); // return True -",
"% self.size return True def Front(self) -> int: if self.isEmpty(): return -1 return",
"obj.enQueue(3) is True assert obj.enQueue(4) is False assert obj.Rear() == 3 assert obj.isFull()"
] |
[
"get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrder\"))",
"import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\",",
"<reponame>ButchershopCreative/django-oscar-mws<gh_stars>10-100 from django.contrib import admin from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\"))",
"django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\"))",
"admin from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\"))",
"admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrder\")) admin.site.register(get_model(\"oscar_mws\",",
"\"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrder\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrderLine\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentShipment\"))",
"django.contrib import admin from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\"))",
"from django.contrib import admin from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\",",
"from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\",",
"admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrder\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrderLine\")) admin.site.register(get_model(\"oscar_mws\",",
"import admin from django.db.models import get_model admin.site.register(get_model(\"oscar_mws\", \"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\",",
"\"FeedSubmission\")) admin.site.register(get_model(\"oscar_mws\", \"FeedReport\")) admin.site.register(get_model(\"oscar_mws\", \"FeedResult\")) admin.site.register(get_model(\"oscar_mws\", \"AmazonProfile\")) admin.site.register(get_model(\"oscar_mws\", \"ShipmentPackage\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrder\")) admin.site.register(get_model(\"oscar_mws\", \"FulfillmentOrderLine\"))"
] |
[
"palavra in palavras: # Replace emoji if len(palavra) <= 3: # replace good",
"'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre',",
"return [palavra for palavra in palavras if palavra not in self.stoplist] def remove_punctuation(self,",
"return re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras): return [palavra for palavra",
"Textuais sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda',",
"string import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords')",
"palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet):",
"'²', '³'] # UniLex: Método Léxico para Análise de Sentimentos Textuais sobre Conteúdo",
"'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas',",
"Sentimentos Textuais sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora',",
"remove_stopwords(self, palavras): return [palavra for palavra in palavras if palavra not in self.stoplist]",
"'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita',",
"3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad",
"'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses',",
"words if len(palavra) <= 2: palavra = '' for s in self.special_char: palavra",
"'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo',",
"for s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas)",
"'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso',",
"'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha',",
"'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum',",
"palavra = self.stemmer.stem(palavra) # Remove small words if len(palavra) <= 2: palavra =",
"# Stemming # palavra = self.stemmer.stem(palavra) # Remove small words if len(palavra) <=",
"in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet =",
"'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse',",
"or more repetitions of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return",
"'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco',",
"'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos',",
"'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk + stopwords",
"\\S+ matches all non-whitespace characters (the end of the url) return re.sub(\"http\\S+\", \"\",",
"punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class",
"# pattern to look for three or more repetitions of any character, including",
"'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve',",
"'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as',",
"# UniLex: Método Léxico para Análise de Sentimentos Textuais sobre Conteúdo de Tweets",
"palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def",
"'~', '.', ',', ';', 'º', 'ª', '°', '¹', '²', '³'] # UniLex: Método",
"= re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra) # Remove small",
"Remove spaces before and after string return re.sub(\" +\", \" \", tweet) def",
"'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem',",
"'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso',",
"#nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char",
"stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet =",
"'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de',",
"including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet",
"def process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet",
"'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era',",
"'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem',",
"'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos',",
"'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia',",
"'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham',",
"'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer',",
"'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la',",
"return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self,",
"'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam',",
"'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam',",
"# replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra",
"'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito',",
"'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita',",
"'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para',",
"pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces before and",
"\", tweet) def remove_stopwords(self, palavras): return [palavra for palavra in palavras if palavra",
"'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa',",
"= self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet =",
"pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip()",
"= ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower()",
"'vos', 'vos'] # Stopwords do nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex",
"'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords",
"'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha',",
"'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo',",
"'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos',",
"remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet)",
"emoji if len(palavra) <= 3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom',",
"'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo',",
"'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me',",
"'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada',",
"'(', ')', '_', '-', '+', '=', '{', '[', '}', ']', '~', '.', ',',",
"import re import nltk from string import punctuation from nltk.tokenize import TweetTokenizer from",
"+ stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet",
"'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses',",
"= self.stemmer.stem(palavra) # Remove small words if len(palavra) <= 2: palavra = ''",
"tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\",",
"'[', '}', ']', '~', '.', ',', ';', 'º', 'ª', '°', '¹', '²', '³']",
"palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras:",
"#nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char =",
"'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas',",
"tweet): tweet = tweet.strip() # Remove spaces before and after string return re.sub(\"",
"'°', '¹', '²', '³'] # UniLex: Método Léxico para Análise de Sentimentos Textuais",
"matches all non-whitespace characters (the end of the url) return re.sub(\"http\\S+\", \"\", tweet)",
"'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos',",
"palavra = '' for s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet",
"emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra) #",
"'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois',",
"'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos',",
"of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def",
"'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima',",
"good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra =",
"# Remove spaces before and after string return re.sub(\" +\", \" \", tweet)",
"'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa',",
"self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras)",
"'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem',",
"'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este',",
"'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas',",
"'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so',",
"nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer",
"';', 'º', 'ª', '°', '¹', '²', '³'] # UniLex: Método Léxico para Análise",
"'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido',",
"'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua',",
"and \\S+ matches all non-whitespace characters (the end of the url) return re.sub(\"http\\S+\",",
"\"\", tweet) def replace_three_or_more(self, tweet): # pattern to look for three or more",
"tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas",
"'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao',",
"= palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet",
"'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver',",
"three or more repetitions of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL)",
"re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove",
"de Sentimentos Textuais sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex = ['a',",
"'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual',",
"'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate',",
"'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele',",
"remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces before and after string return",
"for three or more repetitions of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\",",
"stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet =",
"tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): # http matches literal",
"return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern to look for three",
"palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras: # Replace emoji",
"do nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self,",
"Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas',",
"'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto',",
"'.', ',', ';', 'º', 'ª', '°', '¹', '²', '³'] # UniLex: Método Léxico",
"[palavra for palavra in palavras if palavra not in self.stoplist] def remove_punctuation(self, palavras):",
"'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo',",
"tweet): # http matches literal characters and \\S+ matches all non-whitespace characters (the",
"def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\",",
"sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet",
"tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras",
"import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer =",
"import nltk from string import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import",
"look for three or more repetitions of any character, including newlines pattern =",
"nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet):",
"'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou',",
"return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self,",
"UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet",
"= self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet =",
"'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos',",
"'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera',",
"nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer =",
"'=', '{', '[', '}', ']', '~', '.', ',', ';', 'º', 'ª', '°', '¹',",
"def remove_links(self, tweet): # http matches literal characters and \\S+ matches all non-whitespace",
"non-whitespace characters (the end of the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self,",
"'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu',",
"'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela',",
"tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet):",
"stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo',",
"in self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra in palavras if palavra",
"['$', '%', '&', '*', '(', ')', '_', '-', '+', '=', '{', '[', '}',",
"'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos',",
"'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno',",
"'ª', '°', '¹', '²', '³'] # UniLex: Método Léxico para Análise de Sentimentos",
"from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object):",
"= self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra",
"def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces before and after string",
"nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*', '(', ')',",
"'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta',",
"'bom', palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming",
"if len(palavra) <= 2: palavra = '' for s in self.special_char: palavra =",
"stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet)",
"do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet)",
"'vir', 'vos', 'vos'] # Stopwords do nltk + stopwords do UniLex stoplist =",
"'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro',",
"'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre',",
"characters and \\S+ matches all non-whitespace characters (the end of the url) return",
"sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem',",
"after string return re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras): return [palavra",
"PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&',",
"TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*', '(', ')', '_', '-', '+',",
"newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet =",
"if palavra not in self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra in",
"'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo',",
"'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros',",
"# http matches literal characters and \\S+ matches all non-whitespace characters (the end",
"replace_three_or_more(self, tweet): # pattern to look for three or more repetitions of any",
"stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False)",
"'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas',",
"\"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return",
"'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao',",
"tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern",
"emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]',",
"= self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): #",
"palavras: # Replace emoji if len(palavra) <= 3: # replace good emoticons palavra",
"tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet",
"Léxico para Análise de Sentimentos Textuais sobre Conteúdo de Tweets em Português Brasileiro*",
"Stemming # palavra = self.stemmer.stem(palavra) # Remove small words if len(palavra) <= 2:",
"to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): # http matches literal characters and",
"url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def",
"= self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras: # Replace emoji if",
"'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se',",
"'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia',",
"'³'] # UniLex: Método Léxico para Análise de Sentimentos Textuais sobre Conteúdo de",
"nltk from string import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords",
"'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em',",
"'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles',",
"'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca',",
"'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas',",
"'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do',",
"not in self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra in palavras if",
"= TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*', '(', ')', '_', '-',",
"re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) #",
"tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*', '(', ')', '_',",
"'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na',",
"'vos'] # Stopwords do nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex +",
"'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas',",
"s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet",
"'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia',",
"= sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet)",
"'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam',",
"'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no',",
"'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda',",
"'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo',",
"before and after string return re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras):",
"\"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): #",
"'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns',",
"tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern to look for",
"'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas',",
"'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu',",
"'}', ']', '~', '.', ',', ';', 'º', 'ª', '°', '¹', '²', '³'] #",
"'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te',",
"'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais',",
"the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet)",
"= tweet.strip() # Remove spaces before and after string return re.sub(\" +\", \"",
"'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do",
"'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre',",
"'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros',",
"'%', '&', '*', '(', ')', '_', '-', '+', '=', '{', '[', '}', ']',",
"Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas',",
"'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua',",
"self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): # http",
"'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria',",
"tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras",
"'{', '[', '}', ']', '~', '.', ',', ';', 'º', 'ª', '°', '¹', '²',",
"'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste',",
"'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das',",
"re import nltk from string import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus",
"'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito',",
"TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer()",
"'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos',",
"= ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos',",
"= '' for s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet =",
"tweet): # pattern to look for three or more repetitions of any character,",
"self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = []",
"'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa',",
"'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo',",
"palavra) # Stemming # palavra = self.stemmer.stem(palavra) # Remove small words if len(palavra)",
"'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas',",
"= self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas =",
"tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def",
"'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem',",
"+ stopwords.words('portuguese'))) def process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet =",
"remove_links(self, tweet): # http matches literal characters and \\S+ matches all non-whitespace characters",
"'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles',",
"'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram',",
"remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet)",
"'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si',",
"'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu',",
"'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto',",
"'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando',",
"'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois',",
"'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo',",
"'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez',",
"'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo',",
"'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos',",
"import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True,",
"de Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma',",
"len(palavra) <= 3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) #",
"'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com',",
"Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum',",
"'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever',",
"tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet",
"re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet):",
"matches literal characters and \\S+ matches all non-whitespace characters (the end of the",
"'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles',",
"replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra =",
"'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra',",
"' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower() def",
"'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa',",
"def replace_three_or_more(self, tweet): # pattern to look for three or more repetitions of",
"'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera',",
"tweet) def remove_stopwords(self, palavras): return [palavra for palavra in palavras if palavra not",
"'' for s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = '",
"'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas',",
"'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes',",
"'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem',",
"'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas',",
"'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma',",
"'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk + stopwords do UniLex",
"'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti',",
"<= 2: palavra = '' for s in self.special_char: palavra = palavra.replace(s, '')",
"'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi',",
"literal characters and \\S+ matches all non-whitespace characters (the end of the url)",
"'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas',",
"self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet)",
"bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra)",
"tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet)",
"re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra) # Remove small words",
"'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam',",
"'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe',",
"'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem',",
"'') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self,",
"repetitions of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet)",
"to look for three or more repetitions of any character, including newlines pattern",
"'&', '*', '(', ')', '_', '-', '+', '=', '{', '[', '}', ']', '~',",
"'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes',",
"'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela',",
"re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet):",
"'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo',",
"tweet) def replace_three_or_more(self, tweet): # pattern to look for three or more repetitions",
"'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso',",
"from string import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp')",
"palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for",
"self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet)",
"'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes',",
"def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): # http matches literal characters",
"self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras: # Replace",
"self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra in",
"'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao',",
"'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos',",
"'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio',",
"'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas',",
"return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces before",
"process(self, tweet): tweet = self.to_lower(tweet) tweet = self.remove_links(tweet) tweet = self.remove_mentions(tweet) tweet =",
"'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia',",
"= self.remove_punctuation(palavras) palavras = self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras: #",
"palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra) # Remove",
"len(palavra) <= 2: palavra = '' for s in self.special_char: palavra = palavra.replace(s,",
"'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele',",
"palavras_processadas = [] for palavra in palavras: # Replace emoji if len(palavra) <=",
"'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos',",
"= re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() #",
"from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer",
"'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam',",
"'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz',",
"all non-whitespace characters (the end of the url) return re.sub(\"http\\S+\", \"\", tweet) def",
"'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os',",
"re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras): return [palavra for palavra in",
"'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk + stopwords do",
"'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu',",
"self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet)",
"palavras if palavra not in self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra",
"spaces before and after string return re.sub(\" +\", \" \", tweet) def remove_stopwords(self,",
"characters (the end of the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet):",
"'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo',",
"re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces",
"tweet.strip() # Remove spaces before and after string return re.sub(\" +\", \" \",",
"'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes',",
"'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca',",
"in palavras: # Replace emoji if len(palavra) <= 3: # replace good emoticons",
"UniLex: Método Léxico para Análise de Sentimentos Textuais sobre Conteúdo de Tweets em",
"'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele',",
"'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk",
"palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra) # Stemming #",
"'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas',",
"Remove small words if len(palavra) <= 2: palavra = '' for s in",
"'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto',",
"'.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self,",
"of the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\",",
"'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante',",
"'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem',",
"'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes',",
"'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao',",
"# Remove small words if len(palavra) <= 2: palavra = '' for s",
"# Stopwords do nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese')))",
"def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\",",
"'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas',",
"'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse',",
"'das', 'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas',",
"import punctuation from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords #nltk.download('rslp') #nltk.download('stopwords') #nltk.download('punkt')",
"['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante',",
"'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque',",
"def remove_punctuation(self, palavras): return [palavra for palavra in palavras if palavra not in",
"'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta',",
"'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse',",
"# replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons",
"'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como',",
"'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos']",
"'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha',",
"\"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return",
"'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo',",
"']', '~', '.', ',', ';', 'º', 'ª', '°', '¹', '²', '³'] # UniLex:",
"'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode',",
"tweet) def remove_duplicated_spaces(self, tweet): tweet = tweet.strip() # Remove spaces before and after",
"'_', '-', '+', '=', '{', '[', '}', ']', '~', '.', ',', ';', 'º',",
"'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela', 'delas', 'dele', 'deles',",
"'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o',",
"= [] for palavra in palavras: # Replace emoji if len(palavra) <= 3:",
"'+', '=', '{', '[', '}', ']', '~', '.', ',', ';', 'º', 'ª', '°',",
"'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves',",
"tweet): return tweet.lower() def remove_links(self, tweet): # http matches literal characters and \\S+",
"',', ';', 'º', 'ª', '°', '¹', '²', '³'] # UniLex: Método Léxico para",
"'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus',",
"'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos',",
"end of the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return re.sub(\"@\\S+\",",
"+\", \" \", tweet) def remove_stopwords(self, palavras): return [palavra for palavra in palavras",
"'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela',",
"'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas',",
"'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas', 'todavia', 'todo',",
"'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao',",
"'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido', 'tinha', 'tinham', 'toda', 'todas',",
"'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito',",
"'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um',",
"'de', 'dela', 'delas', 'dele', 'deles', 'depois', 'dessa', 'dessas', 'desse', 'desses', 'desta', 'destas', 'deste',",
"= self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras) palavras =",
"'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra',",
"Replace emoji if len(palavra) <= 3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]',",
"tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\",",
"def remove_stopwords(self, palavras): return [palavra for palavra in palavras if palavra not in",
"replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra",
"'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos',",
"character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self, tweet):",
"'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos',",
"'deveria', 'deveriam', 'devia', 'deviam', 'disse', 'disso', 'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e',",
"re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern to look for three or",
"Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns', 'ampla',",
"'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo',",
"'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios',",
"'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem',",
"'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem',",
"palavras): return [palavra for palavra in palavras if palavra not in self.stoplist] def",
"'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava',",
"for palavra in palavras: # Replace emoji if len(palavra) <= 3: # replace",
"'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro',",
"'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo',",
"'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas',",
"'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam',",
"palavra in palavras if palavra not in self.stoplist] def remove_punctuation(self, palavras): return [palavra",
"'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos',",
"#nltk.download('punkt') class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$',",
"palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim',",
"'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa',",
"self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra in palavras if palavra not",
"in palavras if palavra not in self.stoplist] def remove_punctuation(self, palavras): return [palavra for",
"'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir',",
"http matches literal characters and \\S+ matches all non-whitespace characters (the end of",
"'toda', 'todas', 'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos',",
"pattern to look for three or more repetitions of any character, including newlines",
"'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele', 'daqueles', 'das', 'de', 'dela',",
"'ele', 'eles', 'em', 'enquanto', 'entre', 'era', 'essa', 'essas', 'esse', 'esses', 'esta', 'estamos', 'estao',",
"'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso',",
"'ultimos', 'um', 'uma', 'umas', 'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] #",
"def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern to",
"special_char = ['$', '%', '&', '*', '(', ')', '_', '-', '+', '=', '{',",
"for palavra in palavras if palavra not in self.stoplist] def remove_punctuation(self, palavras): return",
"tweet = self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras",
"self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras = self.remove_punctuation(palavras)",
"')', '_', '-', '+', '=', '{', '[', '}', ']', '~', '.', ',', ';',",
"class PreProcessor(object): stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%',",
"'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk + stopwords do UniLex stoplist",
"'º', 'ª', '°', '¹', '²', '³'] # UniLex: Método Léxico para Análise de",
"'disto', 'dito', 'diz', 'dizem', 'do', 'dos', 'e', 'ela', 'elas', 'ele', 'eles', 'em', 'enquanto',",
"'minhas', 'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta',",
"'*', '(', ')', '_', '-', '+', '=', '{', '[', '}', ']', '~', '.',",
"em Português Brasileiro* stoplist_uniLex = ['a', 'agora', 'ainda', 'alguem', 'algum', 'alguma', 'algumas', 'alguns',",
"para Análise de Sentimentos Textuais sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex",
"palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return",
"'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per',",
"remove_punctuation(self, palavras): return [palavra for palavra in palavras if palavra not in list(punctuation)]",
"stemmer = nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*',",
"'o', 'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena',",
"= ['$', '%', '&', '*', '(', ')', '_', '-', '+', '=', '{', '[',",
"= nltk.stem.RSLPStemmer() tokenizer = TweetTokenizer(reduce_len=True, preserve_case=False) special_char = ['$', '%', '&', '*', '(',",
"'uns', 'vendo', 'ver', 'vez', 'vindo', 'vir', 'vos', 'vos'] # Stopwords do nltk +",
"palavra not in self.stoplist] def remove_punctuation(self, palavras): return [palavra for palavra in palavras",
"'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob',",
"'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha',",
"'os', 'ou', 'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas',",
"'¹', '²', '³'] # UniLex: Método Léxico para Análise de Sentimentos Textuais sobre",
"'poucos', 'primeiro', 'primeiros', 'propria', 'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que',",
"'essas', 'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou',",
"self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra) tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet)",
"if len(palavra) <= 3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra)",
"'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter',",
"'muita', 'muitas', 'muito', 'muitos', 'na', 'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas',",
"self.remove_stopwords(palavras) palavras_processadas = [] for palavra in palavras: # Replace emoji if len(palavra)",
"'outra', 'outras', 'outro', 'outros', 'para', 'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos',",
"'-', '+', '=', '{', '[', '}', ']', '~', '.', ',', ';', 'º', 'ª',",
"'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da',",
"'grandes', 'ha', 'isso', 'isto', 'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas',",
"'desses', 'desta', 'destas', 'deste', 'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria',",
"[] for palavra in palavras: # Replace emoji if len(palavra) <= 3: #",
"'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas',",
"tweet = ' '.join(palavras_processadas) tweet = self.remove_duplicated_spaces(tweet) return tweet def to_lower(self, tweet): return",
"'esse', 'esses', 'esta', 'estamos', 'estao', 'estas', 'estava', 'estavam', 'estavamos', 'este', 'estes', 'estou', 'eu',",
"Análise de Sentimentos Textuais sobre Conteúdo de Tweets em Português Brasileiro* stoplist_uniLex =",
"'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez', 'tambem', 'tampouco',",
"'todavia', 'todo', 'todos', 'tu', 'tua', 'tuas', 'tudo', 'ultima', 'ultimas', 'ultimo', 'ultimos', 'um', 'uma',",
"= re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace bad emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[(\\[<{cC]|[D>)\\]}][\\-=^*\\']?[:;=8]', 'ruim', palavra)",
"return tweet def to_lower(self, tweet): return tweet.lower() def remove_links(self, tweet): # http matches",
"# Replace emoji if len(palavra) <= 3: # replace good emoticons palavra =",
"'proprias', 'proprio', 'proprios', 'quais', 'qual', 'quando', 'quanto', 'quantos', 'que', 'quem', 'sao', 'se', 'seja',",
"'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num', 'numa', 'nunca', 'o', 'os', 'ou', 'outra', 'outras',",
"'sendo', 'sera', 'serao', 'seu', 'seus', 'si', 'sido', 'so', 'sob', 'sobre', 'sua', 'suas', 'talvez',",
"re.sub(\"@\\S+\", \"\", tweet) def remove_hashtags(self, tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet):",
"'deste', 'destes', 'deve', 'devem', 'devendo', 'dever', 'devera', 'deverao', 'deveria', 'deveriam', 'devia', 'deviam', 'disse',",
"'estavamos', 'este', 'estes', 'estou', 'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for',",
"and after string return re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras): return",
"'pela', 'pelas', 'pelo', 'pelos', 'pequena', 'pequenas', 'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder',",
"'ao', 'aos', 'apos', 'aquela', 'aquelas', 'aquele', 'aqueles', 'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa',",
"remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self, tweet): # pattern to look",
"Stopwords do nltk + stopwords do UniLex stoplist = sorted(set(stoplist_uniLex + stopwords.words('portuguese'))) def",
"'ruim', palavra) # Stemming # palavra = self.stemmer.stem(palavra) # Remove small words if",
"string return re.sub(\" +\", \" \", tweet) def remove_stopwords(self, palavras): return [palavra for",
"'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por', 'porem',",
"<= 3: # replace good emoticons palavra = re.sub('[:;=8][\\-=^*\\']?[)\\]Dpb}]|[cCqd{(\\[][\\-=^*\\']?[:;=8]', 'bom', palavra) # replace",
"'eu', 'fazendo', 'fazer', 'feita', 'feitas', 'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande',",
"'ja', 'la', 'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus',",
"'pequeno', 'pequenos', 'per', 'perante', 'pode', 'podendo', 'poder', 'poderia', 'poderiam', 'podia', 'podiam', 'pois', 'por',",
"'pois', 'por', 'porem', 'porque', 'posso', 'pouca', 'poucas', 'pouco', 'poucos', 'primeiro', 'primeiros', 'propria', 'proprias',",
"'que', 'quem', 'sao', 'se', 'seja', 'sejam', 'sem', 'sempre', 'sendo', 'sera', 'serao', 'seu', 'seus',",
"more repetitions of any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\",",
"Método Léxico para Análise de Sentimentos Textuais sobre Conteúdo de Tweets em Português",
"= self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras = self.tokenizer.tokenize(tweet) palavras =",
"\" \", tweet) def remove_stopwords(self, palavras): return [palavra for palavra in palavras if",
"small words if len(palavra) <= 2: palavra = '' for s in self.special_char:",
"return tweet.lower() def remove_links(self, tweet): # http matches literal characters and \\S+ matches",
"2: palavra = '' for s in self.special_char: palavra = palavra.replace(s, '') palavras_processadas.append(palavra)",
"preserve_case=False) special_char = ['$', '%', '&', '*', '(', ')', '_', '-', '+', '=',",
"tweet.lower() def remove_links(self, tweet): # http matches literal characters and \\S+ matches all",
"'algumas', 'alguns', 'ampla', 'amplas', 'amplo', 'amplos', 'ante', 'antes', 'ao', 'aos', 'apos', 'aquela', 'aquelas',",
"'nao', 'nas', 'nem', 'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas',",
"= self.remove_mentions(tweet) tweet = self.remove_hashtags(tweet) tweet = self.remove_numbers(tweet) tweet = self.replace_three_or_more(tweet) palavras =",
"any character, including newlines pattern = re.compile(r\"(.)\\1{2,}\", re.DOTALL) return pattern.sub(r\"\\1\\1\", tweet) def remove_duplicated_spaces(self,",
"(the end of the url) return re.sub(\"http\\S+\", \"\", tweet) def remove_mentions(self, tweet): return",
"self.stemmer.stem(palavra) # Remove small words if len(palavra) <= 2: palavra = '' for",
"'feito', 'feitos', 'foi', 'for', 'foram', 'fosse', 'fossem', 'grande', 'grandes', 'ha', 'isso', 'isto', 'ja',",
"'suas', 'talvez', 'tambem', 'tampouco', 'te', 'tem', 'tendo', 'tenha', 'ter', 'teu', 'teus', 'ti', 'tido',",
"tweet = tweet.strip() # Remove spaces before and after string return re.sub(\" +\",",
"tweet): return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def",
"'lhe', 'lhes', 'lo', 'mas', 'me', 'mesma', 'mesmas', 'mesmo', 'mesmos', 'meu', 'meus', 'minha', 'minhas',",
"'nenhum', 'nessa', 'nessas', 'nesta', 'nestas', 'ninguem', 'no', 'nos', 'nossa', 'nossas', 'nosso', 'nossos', 'num',",
"# palavra = self.stemmer.stem(palavra) # Remove small words if len(palavra) <= 2: palavra",
"'aquilo', 'as', 'ate', 'atraves', 'cada', 'coisa', 'coisas', 'com', 'como', 'contra', 'contudo', 'da', 'daquele',",
"return re.sub(\"#\", \"\", tweet) def remove_numbers(self, tweet): return re.sub(\"\\d+\", \"\", tweet) def replace_three_or_more(self,"
] |
[
"SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not",
"assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not",
"assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not",
"exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\" assert",
"os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME",
"import SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is",
"None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not None, \"MYSQL_DATABASE_NAME is not",
"is not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\" assert",
"MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not None,",
"db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not",
"is not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is not given.\" assert",
"USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is",
"is not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not None, \"MYSQL_DATABASE_NAME",
"static import SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path}",
"MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL:",
"not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME",
"MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert",
"given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is",
"def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is",
"from static import SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH),",
"import os from static import SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate():",
"assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None,",
"not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\"",
"MYSQL_HOST is not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not None,",
"USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH)",
"None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not",
"is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not",
"\"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not None, \"MYSQL_DATABASE_NAME is not given.\"",
"\"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\"",
"not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is",
"given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is",
"None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is not",
"MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not None,",
"if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD",
"\"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME is not None, \"MYSQL_USERNAME is",
"MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if",
"not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST",
"os from static import SQLITE_DIR_PATH, USE_MYSQL, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DATABASE_NAME def db_path_validate(): assert",
"not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is",
"is not None, \"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST",
"\"MYSQL_PASSWORD is not given.\" assert MYSQL_HOST is not None, \"MYSQL_HOST is not given.\"",
"assert MYSQL_HOST is not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not",
"not None, \"MYSQL_HOST is not given.\" assert MYSQL_DATABASE_NAME is not None, \"MYSQL_DATABASE_NAME is",
"is not None, \"MYSQL_USERNAME is not given.\" assert MYSQL_PASSWORD is not None, \"MYSQL_PASSWORD",
"MYSQL_DATABASE_NAME def db_path_validate(): assert os.path.exists(SQLITE_DIR_PATH), \"{path} is not exists.\".format(path=SQLITE_DIR_PATH) if USE_MYSQL: assert MYSQL_USERNAME"
] |
[
"the catalog from AVSpeech # loc | the location for file to store",
"# name | name for the wav mix file # cat | the",
"AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as avh import pandas as pd",
"to store # name | name for the wav mix file # cat",
"'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for proc in processes: proc.join() #m_audio('audio_train','audio_train',cat_train,80000,80500)",
"if not, see the requirement.txt # download and preprocess the data from AVspeech",
"download and concatenate for i in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i,",
"loc | the location for file to store # name | name for",
"link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time)",
"download and preprocess the data from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler",
"sys sys.path.append(\"../lib\") import AVHandler as avh import pandas as pd import multiprocessing from",
"following by the catalog from AVSpeech # loc | the location for file",
"in catalog. # if not, see the requirement.txt # download and preprocess the",
"dataset import sys sys.path.append(\"../lib\") import AVHandler as avh import pandas as pd import",
"Process def m_link(youtube_id): # return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return",
"index of the audio to download and concatenate for i in range(start_idx,end_idx): #f_name",
"f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time",
"pandas as pd import multiprocessing from multiprocessing import Process def m_link(youtube_id): # return",
"from multiprocessing import Process def m_link(youtube_id): # return the youtube actual link link",
"with audio link and time # start_idx | the starting index of the",
"catalog from AVSpeech # loc | the location for file to store #",
"'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K",
"cat | the catalog with audio link and time # start_idx | the",
"= 10 sample_per_process = 2000 for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train',",
"end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link',",
"f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time",
"import AVHandler as avh import pandas as pd import multiprocessing from multiprocessing import",
"i in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link",
"make sure avspeech_train.csv and avspeech_test.csv are in catalog. # if not, see the",
"'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for proc in processes:",
"for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc)",
"end_idx | the ending index of the audio to download and concatenate for",
"link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following",
"the data from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as avh import",
"3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test",
"start_idx | the starting index of the audio to download and concatenate #",
"concatenated audio following by the catalog from AVSpeech # loc | the location",
"make concatenated audio following by the catalog from AVSpeech # loc | the",
"preprocess the data from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as avh",
"index of the audio to download and concatenate # end_idx | the ending",
"auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link)",
"audio link and time # start_idx | the starting index of the audio",
"| the catalog with audio link and time # start_idx | the starting",
"# cat | the catalog with audio link and time # start_idx |",
"store # name | name for the wav mix file # cat |",
"'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for proc in processes: proc.join()",
"m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train =",
"# Multiprocess processes = [] n_process = 10 sample_per_process = 2000 for i",
"avspeech_train.csv and avspeech_test.csv are in catalog. # if not, see the requirement.txt #",
"import sys sys.path.append(\"../lib\") import AVHandler as avh import pandas as pd import multiprocessing",
"return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the catalog from",
"the audio to download and concatenate # end_idx | the ending index of",
"m_link(youtube_id): # return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def",
"2000 for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process})",
"concatenate for i in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' #",
"avspeech_test.csv are in catalog. # if not, see the requirement.txt # download and",
"link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the catalog from AVSpeech",
"mix file # cat | the catalog with audio link and time #",
"for i in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio",
"to download and concatenate for i in range(start_idx,end_idx): #f_name = name+str(i) f_name =",
"and concatenate # end_idx | the ending index of the audio to download",
"290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process = 10 sample_per_process = 2000",
"and avspeech_test.csv are in catalog. # if not, see the requirement.txt # download",
"avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv')",
"the audio to download and concatenate for i in range(start_idx,end_idx): #f_name = name+str(i)",
"start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv')",
"#f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time",
"and time # start_idx | the starting index of the audio to download",
"return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): #",
"youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated",
"= 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the",
"m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the catalog from AVSpeech # loc",
"the catalog with audio link and time # start_idx | the starting index",
"\"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time +",
"requirement.txt # download and preprocess the data from AVspeech dataset import sys sys.path.append(\"../lib\")",
"| the ending index of the audio to download and concatenate for i",
"Before running, make sure avspeech_train.csv and avspeech_test.csv are in catalog. # if not,",
"# download and preprocess the data from AVspeech dataset import sys sys.path.append(\"../lib\") import",
"#cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess",
"in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start",
"to download and concatenate # end_idx | the ending index of the audio",
"pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess processes =",
"10 sample_per_process = 2000 for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name':",
"pd import multiprocessing from multiprocessing import Process def m_link(youtube_id): # return the youtube",
"file # cat | the catalog with audio link and time # start_idx",
"processes = [] n_process = 10 sample_per_process = 2000 for i in range(n_process):",
"n_process = 10 sample_per_process = 2000 for i in range(n_process): proc = Process(target=m_audio,",
"catalog. # if not, see the requirement.txt # download and preprocess the data",
"in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link =",
"= pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess processes",
"audios data from 290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process = 10",
"proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \",",
"import Process def m_link(youtube_id): # return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id",
"of the audio to download and concatenate # end_idx | the ending index",
"actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio",
"download and concatenate # end_idx | the ending index of the audio to",
"by the catalog from AVSpeech # loc | the location for file to",
"= 2000 for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process,",
"| the starting index of the audio to download and concatenate # end_idx",
"# return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx):",
"catalog with audio link and time # start_idx | the starting index of",
"# create 80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess processes = []",
"multiprocessing from multiprocessing import Process def m_link(youtube_id): # return the youtube actual link",
"import pandas as pd import multiprocessing from multiprocessing import Process def m_link(youtube_id): #",
"data from 290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process = 10 sample_per_process",
"audio to download and concatenate for i in range(start_idx,end_idx): #f_name = name+str(i) f_name",
"| the location for file to store # name | name for the",
"cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') #",
"running, make sure avspeech_train.csv and avspeech_test.csv are in catalog. # if not, see",
"wav mix file # cat | the catalog with audio link and time",
"file to store # name | name for the wav mix file #",
"cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns =",
"concatenate # end_idx | the ending index of the audio to download and",
"'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K avh.mkdir('audio_train') #",
"AVHandler as avh import pandas as pd import multiprocessing from multiprocessing import Process",
"80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process =",
"for file to store # name | name for the wav mix file",
"and preprocess the data from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as",
"import multiprocessing from multiprocessing import Process def m_link(youtube_id): # return the youtube actual",
"= m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train",
"['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from",
"name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time']",
"= [] n_process = 10 sample_per_process = 2000 for i in range(n_process): proc",
"sys.path.append(\"../lib\") import AVHandler as avh import pandas as pd import multiprocessing from multiprocessing",
"avh import pandas as pd import multiprocessing from multiprocessing import Process def m_link(youtube_id):",
"sample_per_process = 2000 for i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train,",
"= f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time =",
"range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link'])",
"from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as avh import pandas as",
"avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test =",
"of the audio to download and concatenate for i in range(start_idx,end_idx): #f_name =",
"name | name for the wav mix file # cat | the catalog",
"audio to download and concatenate # end_idx | the ending index of the",
"pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000",
"def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the catalog from AVSpeech #",
"the ending index of the audio to download and concatenate for i in",
"= name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}' # auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time =",
"= cat.loc[i,'start_time'] end_time = start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns",
"kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for proc",
"the wav mix file # cat | the catalog with audio link and",
"# end_idx | the ending index of the audio to download and concatenate",
"link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by",
"from AVSpeech # loc | the location for file to store # name",
"ending index of the audio to download and concatenate for i in range(start_idx,end_idx):",
"cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios",
"# start_idx | the starting index of the audio to download and concatenate",
"and concatenate for i in range(start_idx,end_idx): #f_name = name+str(i) f_name = f'{name}_{cat.loc[i, \"link\"]}_{i}'",
"multiprocessing import Process def m_link(youtube_id): # return the youtube actual link link =",
"[] n_process = 10 sample_per_process = 2000 for i in range(n_process): proc =",
"Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for",
"the requirement.txt # download and preprocess the data from AVspeech dataset import sys",
"def m_link(youtube_id): # return the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link",
"= start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time',",
"'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data from 290K avh.mkdir('audio_train')",
"are in catalog. # if not, see the requirement.txt # download and preprocess",
"# make concatenated audio following by the catalog from AVSpeech # loc |",
"audio following by the catalog from AVSpeech # loc | the location for",
"from 290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process = 10 sample_per_process =",
"= ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create 80000-90000 audios data",
"# loc | the location for file to store # name | name",
"not, see the requirement.txt # download and preprocess the data from AVspeech dataset",
"range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process:",
"'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make concatenated audio following by the catalog",
"'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i) for proc in",
"i in range(n_process): proc = Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start()",
"= Process(target=m_audio, kwargs={'loc':'audio_train', 'name': 'audio_train','cat':cat_train, 'start_idx':i*sample_per_process, 'end_idx':(i+1)*sample_per_process}) processes.append(proc) proc.start() print(\"Start process: \", i)",
"for the wav mix file # cat | the catalog with audio link",
"create 80000-90000 audios data from 290K avh.mkdir('audio_train') # Multiprocess processes = [] n_process",
"sure avspeech_train.csv and avspeech_test.csv are in catalog. # if not, see the requirement.txt",
"Multiprocess processes = [] n_process = 10 sample_per_process = 2000 for i in",
"link and time # start_idx | the starting index of the audio to",
"the location for file to store # name | name for the wav",
"starting index of the audio to download and concatenate # end_idx | the",
"start_time + 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time',",
"time # start_idx | the starting index of the audio to download and",
"as avh import pandas as pd import multiprocessing from multiprocessing import Process def",
"the youtube actual link link = 'https://www.youtube.com/watch?v='+youtube_id return link def m_audio(loc,name,cat,start_idx,end_idx): # make",
"# auio_train_id_indexofaudio link = m_link(cat.loc[i,'link']) start_time = cat.loc[i,'start_time'] end_time = start_time + 3.0",
"the starting index of the audio to download and concatenate # end_idx |",
"as pd import multiprocessing from multiprocessing import Process def m_link(youtube_id): # return the",
"name for the wav mix file # cat | the catalog with audio",
"avh.mkdir('audio_train') # Multiprocess processes = [] n_process = 10 sample_per_process = 2000 for",
"AVSpeech # loc | the location for file to store # name |",
"+ 3.0 avh.download(loc,f_name,link) avh.cut(loc,f_name,start_time,end_time) cat_train = pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y']",
"| name for the wav mix file # cat | the catalog with",
"data from AVspeech dataset import sys sys.path.append(\"../lib\") import AVHandler as avh import pandas",
"# Before running, make sure avspeech_train.csv and avspeech_test.csv are in catalog. # if",
"location for file to store # name | name for the wav mix",
"# if not, see the requirement.txt # download and preprocess the data from",
"= pd.read_csv('catalog/avspeech_train.csv') cat_train.columns = ['link', 'start_time', 'end_time', 'x','y'] #cat_test = pd.read_csv('catalog/avspeech_test.csv') # create",
"see the requirement.txt # download and preprocess the data from AVspeech dataset import"
] |
[
".serializers import CommentSerializer from comments.models import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet):",
"import CommentSerializer from comments.models import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset",
"from comments.models import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all()",
"from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes",
"Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer",
"comments.models import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class",
"CommentSerializer from comments.models import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset =",
"rest_framework import viewsets from .serializers import CommentSerializer from comments.models import Comment from .permissions",
"import Comment from .permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class =",
"import viewsets from .serializers import CommentSerializer from comments.models import Comment from .permissions import",
"from rest_framework import viewsets from .serializers import CommentSerializer from comments.models import Comment from",
"from .serializers import CommentSerializer from comments.models import Comment from .permissions import IsGetOrIsAdmin class",
"<reponame>rkarthikdev/blog_api_django from rest_framework import viewsets from .serializers import CommentSerializer from comments.models import Comment",
"import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (IsGetOrIsAdmin,)",
".permissions import IsGetOrIsAdmin class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes =",
"viewsets from .serializers import CommentSerializer from comments.models import Comment from .permissions import IsGetOrIsAdmin"
] |
[
"pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games']) labels = df.Games.str.slice(0,4)",
"import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals')",
"np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games'])",
"as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('medals_data.csv')",
"plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games']) labels = df.Games.str.slice(0,4) plt.xticks(np.arange(n),labels,rotation='horizontal') plt.show()",
"as plt import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal')",
"matplotlib.pyplot as plt import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics",
"= pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games']) labels =",
"df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games']) labels = df.Games.str.slice(0,4) plt.xticks(np.arange(n),labels,rotation='horizontal')",
"numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n",
"pandas as pd import matplotlib.pyplot as plt import numpy as np df =",
"plt import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years')",
"as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n =",
"import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India",
"df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True) plt.title('India Olympics Medal') plt.xlabel('Years') plt.ylabel('Medals') n = len(df['Games']) labels",
"import pandas as pd import matplotlib.pyplot as plt import numpy as np df",
"pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('medals_data.csv') df[['Gold','Silver','Bronze']].plot(kind='bar',stacked=True)"
] |
[
"@property def lang(self): \"\"\"Get the language for this transcription\"\"\" return self._lg @property def",
"lang # the name of the script of the transcription defined according to",
"possibly modified it. A transcription without a username has not # been marked",
"15924 standard. self._scp = script_name # the name of the user indicates the",
"the name of the script of the transcription defined according to # the",
"ISO 15924 standard. self._scp = script_name # the name of the user indicates",
"has not # been marked as reviewed. self._usr = username # the transcription",
"name of the user who have this language skill\"\"\" return self._usr @property def",
"# the ISO 15924 standard. self._scp = script_name # the name of the",
"def lang(self): \"\"\"Get the language for this transcription\"\"\" return self._lg @property def script_name(self):",
"the transcription defined according to # the ISO 15924 standard. self._scp = script_name",
"transcription itself self._trs = transcription @property def sentence_id(self): \"\"\"Get the id of the",
"the id of the sentence self._sid = sentence_id # the language of the",
"for this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the name of the",
"# the id of the sentence self._sid = sentence_id # the language of",
"A transcription without a username has not # been marked as reviewed. self._usr",
"the name of the user indicates the user who last reviewed and #",
"user who have this language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the",
"lang, script_name, username, transcription ): # the id of the sentence self._sid =",
"sentence_id(self): \"\"\"Get the id of the sentence of this transcription\"\"\" return int(self._sid) @property",
"sentence_id # the language of the sentence self._lg = lang # the name",
"username # the transcription itself self._trs = transcription @property def sentence_id(self): \"\"\"Get the",
"script_name(self): \"\"\"Get the name of the script in which this transcription is made\"\"\"",
"# the name of the script of the transcription defined according to #",
"transcription @property def sentence_id(self): \"\"\"Get the id of the sentence of this transcription\"\"\"",
"have this language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the text of",
"reviewed and # possibly modified it. A transcription without a username has not",
"the ISO 15924 standard. self._scp = script_name # the name of the user",
"\"\"\"A sentence transcription in an auxiliary or alternative script\"\"\" def __init__( self, sentence_id,",
"script_name # the name of the user indicates the user who last reviewed",
"the user who have this language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get",
"# possibly modified it. A transcription without a username has not # been",
"made\"\"\" return self._scp @property def username(self): \"\"\"Get the name of the user who",
"sentence transcription in an auxiliary or alternative script\"\"\" def __init__( self, sentence_id, lang,",
"username(self): \"\"\"Get the name of the user who have this language skill\"\"\" return",
"script\"\"\" def __init__( self, sentence_id, lang, script_name, username, transcription ): # the id",
"user who last reviewed and # possibly modified it. A transcription without a",
"the user indicates the user who last reviewed and # possibly modified it.",
"# the name of the user indicates the user who last reviewed and",
"marked as reviewed. self._usr = username # the transcription itself self._trs = transcription",
"of the script in which this transcription is made\"\"\" return self._scp @property def",
"transcription in an auxiliary or alternative script\"\"\" def __init__( self, sentence_id, lang, script_name,",
"sentence self._lg = lang # the name of the script of the transcription",
"= sentence_id # the language of the sentence self._lg = lang # the",
"an auxiliary or alternative script\"\"\" def __init__( self, sentence_id, lang, script_name, username, transcription",
"the language of the sentence self._lg = lang # the name of the",
"this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the name of the script",
"defined according to # the ISO 15924 standard. self._scp = script_name # the",
"auxiliary or alternative script\"\"\" def __init__( self, sentence_id, lang, script_name, username, transcription ):",
"the sentence of this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the language",
"= transcription @property def sentence_id(self): \"\"\"Get the id of the sentence of this",
"__init__( self, sentence_id, lang, script_name, username, transcription ): # the id of the",
"the script in which this transcription is made\"\"\" return self._scp @property def username(self):",
"lang(self): \"\"\"Get the language for this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get",
"def script_name(self): \"\"\"Get the name of the script in which this transcription is",
"def __init__( self, sentence_id, lang, script_name, username, transcription ): # the id of",
"def sentence_id(self): \"\"\"Get the id of the sentence of this transcription\"\"\" return int(self._sid)",
"transcription is made\"\"\" return self._scp @property def username(self): \"\"\"Get the name of the",
"= script_name # the name of the user indicates the user who last",
"= lang # the name of the script of the transcription defined according",
"self._scp @property def username(self): \"\"\"Get the name of the user who have this",
"and # possibly modified it. A transcription without a username has not #",
"transcription defined according to # the ISO 15924 standard. self._scp = script_name #",
"id of the sentence self._sid = sentence_id # the language of the sentence",
"sentence_id, lang, script_name, username, transcription ): # the id of the sentence self._sid",
"username, transcription ): # the id of the sentence self._sid = sentence_id #",
"skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the text of this transcription\"\"\" return",
"= username # the transcription itself self._trs = transcription @property def sentence_id(self): \"\"\"Get",
"script_name, username, transcription ): # the id of the sentence self._sid = sentence_id",
"the sentence self._sid = sentence_id # the language of the sentence self._lg =",
"reviewed. self._usr = username # the transcription itself self._trs = transcription @property def",
"script in which this transcription is made\"\"\" return self._scp @property def username(self): \"\"\"Get",
"self._scp = script_name # the name of the user indicates the user who",
"of the sentence of this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the",
"this transcription is made\"\"\" return self._scp @property def username(self): \"\"\"Get the name of",
"\"\"\"Get the language for this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the",
"the user who last reviewed and # possibly modified it. A transcription without",
"a username has not # been marked as reviewed. self._usr = username #",
"alternative script\"\"\" def __init__( self, sentence_id, lang, script_name, username, transcription ): # the",
"<filename>tatoebatools/transcriptions.py class Transcription: \"\"\"A sentence transcription in an auxiliary or alternative script\"\"\" def",
"indicates the user who last reviewed and # possibly modified it. A transcription",
"return self._scp @property def username(self): \"\"\"Get the name of the user who have",
"language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the text of this transcription\"\"\"",
"self._sid = sentence_id # the language of the sentence self._lg = lang #",
"to # the ISO 15924 standard. self._scp = script_name # the name of",
"transcription ): # the id of the sentence self._sid = sentence_id # the",
"language for this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the name of",
"or alternative script\"\"\" def __init__( self, sentence_id, lang, script_name, username, transcription ): #",
"@property def script_name(self): \"\"\"Get the name of the script in which this transcription",
"is made\"\"\" return self._scp @property def username(self): \"\"\"Get the name of the user",
"script of the transcription defined according to # the ISO 15924 standard. self._scp",
"# been marked as reviewed. self._usr = username # the transcription itself self._trs",
"self, sentence_id, lang, script_name, username, transcription ): # the id of the sentence",
"name of the user indicates the user who last reviewed and # possibly",
"sentence of this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the language for",
"the sentence self._lg = lang # the name of the script of the",
"last reviewed and # possibly modified it. A transcription without a username has",
"the transcription itself self._trs = transcription @property def sentence_id(self): \"\"\"Get the id of",
"transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the language for this transcription\"\"\" return",
"of the transcription defined according to # the ISO 15924 standard. self._scp =",
"the language for this transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the name",
"\"\"\"Get the name of the script in which this transcription is made\"\"\" return",
"int(self._sid) @property def lang(self): \"\"\"Get the language for this transcription\"\"\" return self._lg @property",
"the id of the sentence of this transcription\"\"\" return int(self._sid) @property def lang(self):",
"transcription\"\"\" return self._lg @property def script_name(self): \"\"\"Get the name of the script in",
"of the user who have this language skill\"\"\" return self._usr @property def transcription(self):",
"Transcription: \"\"\"A sentence transcription in an auxiliary or alternative script\"\"\" def __init__( self,",
"of the script of the transcription defined according to # the ISO 15924",
"return self._usr @property def transcription(self): \"\"\"Get the text of this transcription\"\"\" return self._trs",
"the name of the script in which this transcription is made\"\"\" return self._scp",
"sentence self._sid = sentence_id # the language of the sentence self._lg = lang",
"# the transcription itself self._trs = transcription @property def sentence_id(self): \"\"\"Get the id",
"@property def sentence_id(self): \"\"\"Get the id of the sentence of this transcription\"\"\" return",
"this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the language for this transcription\"\"\"",
"been marked as reviewed. self._usr = username # the transcription itself self._trs =",
"username has not # been marked as reviewed. self._usr = username # the",
"language of the sentence self._lg = lang # the name of the script",
"name of the script in which this transcription is made\"\"\" return self._scp @property",
"id of the sentence of this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get",
"in which this transcription is made\"\"\" return self._scp @property def username(self): \"\"\"Get the",
"\"\"\"Get the name of the user who have this language skill\"\"\" return self._usr",
"not # been marked as reviewed. self._usr = username # the transcription itself",
"itself self._trs = transcription @property def sentence_id(self): \"\"\"Get the id of the sentence",
"of this transcription\"\"\" return int(self._sid) @property def lang(self): \"\"\"Get the language for this",
"modified it. A transcription without a username has not # been marked as",
"# the language of the sentence self._lg = lang # the name of",
"which this transcription is made\"\"\" return self._scp @property def username(self): \"\"\"Get the name",
"def username(self): \"\"\"Get the name of the user who have this language skill\"\"\"",
"self._lg = lang # the name of the script of the transcription defined",
"who last reviewed and # possibly modified it. A transcription without a username",
"return int(self._sid) @property def lang(self): \"\"\"Get the language for this transcription\"\"\" return self._lg",
"of the sentence self._sid = sentence_id # the language of the sentence self._lg",
"name of the script of the transcription defined according to # the ISO",
"return self._lg @property def script_name(self): \"\"\"Get the name of the script in which",
"it. A transcription without a username has not # been marked as reviewed.",
"self._usr = username # the transcription itself self._trs = transcription @property def sentence_id(self):",
"self._trs = transcription @property def sentence_id(self): \"\"\"Get the id of the sentence of",
"of the user indicates the user who last reviewed and # possibly modified",
"\"\"\"Get the id of the sentence of this transcription\"\"\" return int(self._sid) @property def",
"self._lg @property def script_name(self): \"\"\"Get the name of the script in which this",
"transcription without a username has not # been marked as reviewed. self._usr =",
"): # the id of the sentence self._sid = sentence_id # the language",
"the script of the transcription defined according to # the ISO 15924 standard.",
"this language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the text of this",
"standard. self._scp = script_name # the name of the user indicates the user",
"of the sentence self._lg = lang # the name of the script of",
"as reviewed. self._usr = username # the transcription itself self._trs = transcription @property",
"@property def username(self): \"\"\"Get the name of the user who have this language",
"user indicates the user who last reviewed and # possibly modified it. A",
"class Transcription: \"\"\"A sentence transcription in an auxiliary or alternative script\"\"\" def __init__(",
"according to # the ISO 15924 standard. self._scp = script_name # the name",
"without a username has not # been marked as reviewed. self._usr = username",
"the name of the user who have this language skill\"\"\" return self._usr @property",
"in an auxiliary or alternative script\"\"\" def __init__( self, sentence_id, lang, script_name, username,",
"who have this language skill\"\"\" return self._usr @property def transcription(self): \"\"\"Get the text"
] |
[
"100 ans = 0 for i in doubles: if i < limit: ans",
"len(scores) for i in range(length): for j in range(i, length): if scores[i] +",
"doubles: if i + j < limit: ans += 1 length = len(scores)",
"break for k in doubles: if scores[i] + scores[j] + k >= limit:",
"break for i in scores: for j in doubles: if i + j",
"in range(1, 21)] singles.append(25) triples = [3 * x for x in range(1,",
"= 0 for i in doubles: if i < limit: ans += 1",
"i in doubles: if i < limit: ans += 1 else: break for",
"for x in range(1, 21)] doubles.append(50) singles = [x for x in range(1,",
"k in doubles: if scores[i] + scores[j] + k >= limit: break ans",
"scores = singles + doubles + triples scores.sort() limit = 100 ans =",
"21)] singles.append(25) triples = [3 * x for x in range(1, 21)] scores",
"in range(i, length): if scores[i] + scores[j] >= limit: break for k in",
"scores[i] + scores[j] >= limit: break for k in doubles: if scores[i] +",
"for x in range(1, 21)] scores = singles + doubles + triples scores.sort()",
"ans += 1 length = len(scores) for i in range(length): for j in",
"i + j < limit: ans += 1 length = len(scores) for i",
"1 else: break for i in scores: for j in doubles: if i",
">= limit: break for k in doubles: if scores[i] + scores[j] + k",
"== \"__main__\": doubles = [2 * x for x in range(1, 21)] doubles.append(50)",
"length = len(scores) for i in range(length): for j in range(i, length): if",
"= [x for x in range(1, 21)] singles.append(25) triples = [3 * x",
"i in range(length): for j in range(i, length): if scores[i] + scores[j] >=",
"doubles: if scores[i] + scores[j] + k >= limit: break ans += 1",
"+= 1 length = len(scores) for i in range(length): for j in range(i,",
"in doubles: if i + j < limit: ans += 1 length =",
"* x for x in range(1, 21)] scores = singles + doubles +",
"range(i, length): if scores[i] + scores[j] >= limit: break for k in doubles:",
"in scores: for j in doubles: if i + j < limit: ans",
"scores[i] + scores[j] + k >= limit: break ans += 1 print ans",
"for i in scores: for j in doubles: if i + j <",
"in doubles: if i < limit: ans += 1 else: break for i",
"length): if scores[i] + scores[j] >= limit: break for k in doubles: if",
"* x for x in range(1, 21)] doubles.append(50) singles = [x for x",
"limit: break for k in doubles: if scores[i] + scores[j] + k >=",
"j in range(i, length): if scores[i] + scores[j] >= limit: break for k",
"doubles: if i < limit: ans += 1 else: break for i in",
"= len(scores) for i in range(length): for j in range(i, length): if scores[i]",
"in range(1, 21)] scores = singles + doubles + triples scores.sort() limit =",
"+ doubles + triples scores.sort() limit = 100 ans = 0 for i",
"doubles.append(50) singles = [x for x in range(1, 21)] singles.append(25) triples = [3",
"ans += 1 else: break for i in scores: for j in doubles:",
"[3 * x for x in range(1, 21)] scores = singles + doubles",
"= singles + doubles + triples scores.sort() limit = 100 ans = 0",
"j in doubles: if i + j < limit: ans += 1 length",
"in doubles: if scores[i] + scores[j] + k >= limit: break ans +=",
"for i in range(length): for j in range(i, length): if scores[i] + scores[j]",
"range(1, 21)] scores = singles + doubles + triples scores.sort() limit = 100",
"21)] doubles.append(50) singles = [x for x in range(1, 21)] singles.append(25) triples =",
"if scores[i] + scores[j] >= limit: break for k in doubles: if scores[i]",
"ans = 0 for i in doubles: if i < limit: ans +=",
"limit = 100 ans = 0 for i in doubles: if i <",
"= [2 * x for x in range(1, 21)] doubles.append(50) singles = [x",
"in range(1, 21)] doubles.append(50) singles = [x for x in range(1, 21)] singles.append(25)",
"i < limit: ans += 1 else: break for i in scores: for",
"x in range(1, 21)] scores = singles + doubles + triples scores.sort() limit",
"else: break for i in scores: for j in doubles: if i +",
"doubles = [2 * x for x in range(1, 21)] doubles.append(50) singles =",
"for k in doubles: if scores[i] + scores[j] + k >= limit: break",
"__name__ == \"__main__\": doubles = [2 * x for x in range(1, 21)]",
"x for x in range(1, 21)] scores = singles + doubles + triples",
"scores: for j in doubles: if i + j < limit: ans +=",
"if __name__ == \"__main__\": doubles = [2 * x for x in range(1,",
"\"__main__\": doubles = [2 * x for x in range(1, 21)] doubles.append(50) singles",
"triples = [3 * x for x in range(1, 21)] scores = singles",
"< limit: ans += 1 else: break for i in scores: for j",
"for j in range(i, length): if scores[i] + scores[j] >= limit: break for",
"scores.sort() limit = 100 ans = 0 for i in doubles: if i",
"x for x in range(1, 21)] doubles.append(50) singles = [x for x in",
"= [3 * x for x in range(1, 21)] scores = singles +",
"0 for i in doubles: if i < limit: ans += 1 else:",
"triples scores.sort() limit = 100 ans = 0 for i in doubles: if",
"[2 * x for x in range(1, 21)] doubles.append(50) singles = [x for",
"if i < limit: ans += 1 else: break for i in scores:",
"singles + doubles + triples scores.sort() limit = 100 ans = 0 for",
"if i + j < limit: ans += 1 length = len(scores) for",
"for i in doubles: if i < limit: ans += 1 else: break",
"singles.append(25) triples = [3 * x for x in range(1, 21)] scores =",
"for j in doubles: if i + j < limit: ans += 1",
"if scores[i] + scores[j] + k >= limit: break ans += 1 print",
"<reponame>EdisonAlgorithms/ProjectEuler if __name__ == \"__main__\": doubles = [2 * x for x in",
"doubles + triples scores.sort() limit = 100 ans = 0 for i in",
"scores[j] >= limit: break for k in doubles: if scores[i] + scores[j] +",
"+ j < limit: ans += 1 length = len(scores) for i in",
"range(1, 21)] doubles.append(50) singles = [x for x in range(1, 21)] singles.append(25) triples",
"1 length = len(scores) for i in range(length): for j in range(i, length):",
"range(1, 21)] singles.append(25) triples = [3 * x for x in range(1, 21)]",
"i in scores: for j in doubles: if i + j < limit:",
"j < limit: ans += 1 length = len(scores) for i in range(length):",
"< limit: ans += 1 length = len(scores) for i in range(length): for",
"21)] scores = singles + doubles + triples scores.sort() limit = 100 ans",
"range(length): for j in range(i, length): if scores[i] + scores[j] >= limit: break",
"singles = [x for x in range(1, 21)] singles.append(25) triples = [3 *",
"limit: ans += 1 length = len(scores) for i in range(length): for j",
"for x in range(1, 21)] singles.append(25) triples = [3 * x for x",
"limit: ans += 1 else: break for i in scores: for j in",
"= 100 ans = 0 for i in doubles: if i < limit:",
"x in range(1, 21)] doubles.append(50) singles = [x for x in range(1, 21)]",
"x in range(1, 21)] singles.append(25) triples = [3 * x for x in",
"+ scores[j] >= limit: break for k in doubles: if scores[i] + scores[j]",
"[x for x in range(1, 21)] singles.append(25) triples = [3 * x for",
"+ triples scores.sort() limit = 100 ans = 0 for i in doubles:",
"in range(length): for j in range(i, length): if scores[i] + scores[j] >= limit:",
"+= 1 else: break for i in scores: for j in doubles: if"
] |
[
"d = abs(y2-y1) x3 , y3 = x2+d , y2 x4 , y4",
"y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2: d",
", y2+d x4 , y4 = x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3,",
"{x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3, y3 = x2",
"y4=y4)) else: dist = x1-x2 x3, y3 = x2 + dist, y2 x4,",
"else: dist = x1-x2 x3, y3 = x2 + dist, y2 x4, y4",
"{y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2: d = abs(x2-x1) x3 ,",
"{y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2: d = abs(x2-x1)",
"if true_dist == apparent_dist: if min(y1,y2) == y1: dist = x2-x1 x3, y3",
"y4 = x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4))",
"x1-x2 x3, y3 = x2 + dist, y2 x4, y4 = x1 -",
"print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3, y3",
"dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2",
"x4=x4, y4=y4)) else: dist = x1-x2 x3, y3 = x2 + dist, y2",
"x4, y4 = x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4,",
"x2-x1 x3, y3 = x1 + dist, y1 x4, y4 = x2 -",
"elif y1 == y2: d = abs(x2-x1) x3 , y3 = x2 ,",
"if x1 == x2 : d = abs(y2-y1) x3 , y3 = x2+d",
"y3 = x1 + dist, y1 x4, y4 = x2 - dist, y2",
"y2 = list(map(int,input().split())) if x1 == x2 : d = abs(y2-y1) x3 ,",
"y1: dist = x2-x1 x3, y3 = x1 + dist, y1 x4, y4",
", y4 = x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4))",
"{y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3, y3 =",
"= abs(y2-y1) x3 , y3 = x2+d , y2 x4 , y4 =",
"d = abs(x2-x1) x3 , y3 = x2 , y2+d x4 , y4",
"== y1: dist = x2-x1 x3, y3 = x1 + dist, y1 x4,",
"x4, y4 = x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4,",
": d = abs(y2-y1) x3 , y3 = x2+d , y2 x4 ,",
"y4 = x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4))",
"y2 x4, y4 = x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3,",
"== apparent_dist: if min(y1,y2) == y1: dist = x2-x1 x3, y3 = x1",
"dist = x1-x2 x3, y3 = x2 + dist, y2 x4, y4 =",
"= x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d",
"y2+d x4 , y4 = x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3,",
"{y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2",
"if min(y1,y2) == y1: dist = x2-x1 x3, y3 = x1 + dist,",
"= x2 + dist, y2 x4, y4 = x1 - dist, y1 print(\"{x3}",
"= abs(x2-x1) x3 , y3 = x2 , y2+d x4 , y4 =",
"{x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2: d = abs(x2-x1) x3",
"y1 x4, y4 = x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3,",
"+ (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist: if min(y1,y2) == y1:",
"x2, y2 = list(map(int,input().split())) if x1 == x2 : d = abs(y2-y1) x3",
"x2 : d = abs(y2-y1) x3 , y3 = x2+d , y2 x4",
"(y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist: if min(y1,y2) == y1: dist",
"= 2*(d**2) if true_dist == apparent_dist: if min(y1,y2) == y1: dist = x2-x1",
"x3 , y3 = x2+d , y2 x4 , y4 = x1+d ,",
", y3 = x2 , y2+d x4 , y4 = x1 , y1+d",
"x1 + dist, y1 x4, y4 = x2 - dist, y2 print(\"{x3} {y3}",
", y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2:",
"+ dist, y1 x4, y4 = x2 - dist, y2 print(\"{x3} {y3} {x4}",
"x4 , y4 = x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4,",
"(x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist: if min(y1,y2) ==",
"= x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else:",
"x1 == x2 : d = abs(y2-y1) x3 , y3 = x2+d ,",
"apparent_dist: if min(y1,y2) == y1: dist = x2-x1 x3, y3 = x1 +",
"x2+d , y2 x4 , y4 = x1+d , y1 print(\"{x3} {y3} {x4}",
"y4 = x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif",
"x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 ==",
"x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist",
"2*(d**2) if true_dist == apparent_dist: if min(y1,y2) == y1: dist = x2-x1 x3,",
"abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist:",
"y1, x2, y2 = list(map(int,input().split())) if x1 == x2 : d = abs(y2-y1)",
"= abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist ==",
"y4 = x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else:",
"y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3, y3 = x2 + dist,",
", y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1)",
"y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3,",
"x4=x4, y4=y4)) elif y1 == y2: d = abs(x2-x1) x3 , y3 =",
"x1, y1, x2, y2 = list(map(int,input().split())) if x1 == x2 : d =",
"y3 = x2 + dist, y2 x4, y4 = x1 - dist, y1",
"= x2-x1 x3, y3 = x1 + dist, y1 x4, y4 = x2",
"y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2)",
"x3, y3 = x2 + dist, y2 x4, y4 = x1 - dist,",
"y3=y3, x4=x4, y4=y4)) elif y1 == y2: d = abs(x2-x1) x3 , y3",
"dist, y2 x4, y4 = x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3,",
"= list(map(int,input().split())) if x1 == x2 : d = abs(y2-y1) x3 , y3",
"print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist =",
"abs(x2-x1) x3 , y3 = x2 , y2+d x4 , y4 = x1",
"= x2+d , y2 x4 , y4 = x1+d , y1 print(\"{x3} {y3}",
"x4 , y4 = x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4,",
"y3 = x2+d , y2 x4 , y4 = x1+d , y1 print(\"{x3}",
"= x1 + dist, y1 x4, y4 = x2 - dist, y2 print(\"{x3}",
", y3 = x2+d , y2 x4 , y4 = x1+d , y1",
"y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist",
"y2: d = abs(x2-x1) x3 , y3 = x2 , y2+d x4 ,",
"y1 == y2: d = abs(x2-x1) x3 , y3 = x2 , y2+d",
"apparent_dist = 2*(d**2) if true_dist == apparent_dist: if min(y1,y2) == y1: dist =",
"== y2: d = abs(x2-x1) x3 , y3 = x2 , y2+d x4",
"{y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2",
"x3, y3 = x1 + dist, y1 x4, y4 = x2 - dist,",
"abs(y2-y1) x3 , y3 = x2+d , y2 x4 , y4 = x1+d",
"y3 = x2 , y2+d x4 , y4 = x1 , y1+d print(\"{x3}",
"x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: print(-1)",
"x1 , y1+d print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d =",
"print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1 == y2: d =",
"y2 x4 , y4 = x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3,",
"true_dist == apparent_dist: if min(y1,y2) == y1: dist = x2-x1 x3, y3 =",
"= x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) elif y1",
"= x1-x2 x3, y3 = x2 + dist, y2 x4, y4 = x1",
"x2 + dist, y2 x4, y4 = x1 - dist, y1 print(\"{x3} {y3}",
"dist, y1 x4, y4 = x2 - dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3,",
"true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist: if",
"+ dist, y2 x4, y4 = x1 - dist, y1 print(\"{x3} {y3} {x4}",
"y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist",
"list(map(int,input().split())) if x1 == x2 : d = abs(y2-y1) x3 , y3 =",
", y2 x4 , y4 = x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3,",
"= x2 , y2+d x4 , y4 = x1 , y1+d print(\"{x3} {y3}",
"x2 , y2+d x4 , y4 = x1 , y1+d print(\"{x3} {y3} {x4}",
"dist = x2-x1 x3, y3 = x1 + dist, y1 x4, y4 =",
"{x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2 +",
"x4=x4, y4=y4)) else: d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist =",
"{y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist = x1-x2 x3, y3 = x2 +",
"d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist",
"y4=y4)) elif y1 == y2: d = abs(x2-x1) x3 , y3 = x2",
"- dist, y2 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else: dist =",
"== x2 : d = abs(y2-y1) x3 , y3 = x2+d , y2",
", y4 = x1+d , y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4))",
"= x1 - dist, y1 print(\"{x3} {y3} {x4} {y4}\".format(x3=x3, y3=y3, x4=x4, y4=y4)) else:",
"= (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if true_dist == apparent_dist: if min(y1,y2)",
"min(y1,y2) == y1: dist = x2-x1 x3, y3 = x1 + dist, y1",
"else: d = abs(x2-x1) true_dist = (x2-x1)**2 + (y2-y1)**2 apparent_dist = 2*(d**2) if",
"x3 , y3 = x2 , y2+d x4 , y4 = x1 ,"
] |
[
"403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites:",
"output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\")",
"= { } headers = { } sites_200 = [] sites_403 = []",
"elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code",
"webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = { } sites_200 = []",
"sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt',",
": {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def write_report():",
"= str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code,",
"response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}:",
"output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites: lines = sites.readlines() for line",
"write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200:",
"= [] def printPage(response): with open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t',",
"for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in",
"} headers = { } sites_200 = [] sites_403 = [] def printPage(response):",
"badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in badchars: responseContent",
"200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm",
"= requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report() if __name__ == '__main__': main()",
"for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites: lines",
"print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT",
"output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\")",
"print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\")",
"THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for",
"elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt', \"w\")",
"urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = { } sites_200",
"{response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with",
"output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in badchars:",
"sites_403 = [] def printPage(response): with open('test.html', \"w\") as output: badchars = ['\\\\n',",
"in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites: lines = sites.readlines()",
"lines: page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report()",
"{ } sites_200 = [] sites_403 = [] def printPage(response): with open('test.html', \"w\")",
"in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\")",
"elif response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code == 404:",
"= { } sites_200 = [] sites_403 = [] def printPage(response): with open('test.html',",
"def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url)",
"headers = { } sites_200 = [] sites_403 = [] def printPage(response): with",
"sites: lines = sites.readlines() for line in lines: page_url = line.strip() response =",
"Failed : {response_code}\") def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\")",
"cookies = { } headers = { } sites_200 = [] sites_403 =",
"def printPage(response): with open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent",
"= ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in badchars: responseContent =",
"THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as",
"= responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} :",
"as sites: lines = sites.readlines() for line in lines: page_url = line.strip() response",
"sites.readlines() for line in lines: page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies,",
"page_url): if response_code == 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code",
"Success : {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url)",
"== 404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt', \"w\") as output:",
"[] sites_403 = [] def printPage(response): with open('test.html', \"w\") as output: badchars =",
"sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def",
"with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: #",
"\"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm",
"test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif",
"import requests import urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers =",
"responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url}",
"badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200:",
"'b\\''] responseContent = str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent)",
"response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt', \"w\") as",
"open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm)",
"= sites.readlines() for line in lines: page_url = line.strip() response = requests.get(page_url, headers=headers,",
"responseContent = str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def",
"elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites: lines =",
"response_code == 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code == 403:",
"import requests import requests import urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { }",
"403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed :",
"import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = { } sites_200 =",
"sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code ==",
"printPage(response): with open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent =",
"as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in",
"== 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed",
"# webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main():",
"line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report() if __name__ ==",
"with open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip()",
"{ } headers = { } sites_200 = [] sites_403 = [] def",
"output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT",
"webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with",
"\"r\") as sites: lines = sites.readlines() for line in lines: page_url = line.strip()",
"str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url):",
"in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code ==",
"in lines: page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url)",
"if response_code == 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code ==",
"sites_200 = [] sites_403 = [] def printPage(response): with open('test.html', \"w\") as output:",
"== 200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}:",
"response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report() if __name__ == '__main__':",
"[] def printPage(response): with open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\'']",
"page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report() if",
"requests import requests import urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers",
": {response_code}\") def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for",
"= [] sites_403 = [] def printPage(response): with open('test.html', \"w\") as output: badchars",
"{response_code}\") def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm",
"200: print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success",
"open('test.txt', \"r\") as sites: lines = sites.readlines() for line in lines: page_url =",
"urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = { } sites_200 = [] sites_403",
"= line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code, page_url) write_report() if __name__",
"\"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\")",
"['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm,",
"404: print(f\"{page_url}: Failed : {response_code}\") def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES",
"open('test.html', \"w\") as output: badchars = ['\\\\n', '\\\\t', 'b\\''] responseContent = str(response.content).strip() for",
"import urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = { }",
"} sites_200 = [] sites_403 = [] def printPage(response): with open('test.html', \"w\") as",
": {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif",
"as output: output.write(\"PAGES THAT 200:\\n\") for elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES",
"output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt',",
"main(): with open('test.txt', \"r\") as sites: lines = sites.readlines() for line in lines:",
"for line in lines: page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False)",
"responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} : Success",
"Success : {response_code}\") sites_403.append(page_url) elif response_code == 404: print(f\"{page_url}: Failed : {response_code}\") def",
"sites_403: output.write(f\"{elm}\\n\") def main(): with open('test.txt', \"r\") as sites: lines = sites.readlines() for",
"\"\") output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} : Success :",
"{response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success : {response_code}\") sites_403.append(page_url) elif response_code",
"lines = sites.readlines() for line in lines: page_url = line.strip() response = requests.get(page_url,",
"for elm in badchars: responseContent = responseContent.replace(elm, \"\") output.write(responseContent) def test_html_code(response_code, page_url): if",
"def main(): with open('test.txt', \"r\") as sites: lines = sites.readlines() for line in",
"line in lines: page_url = line.strip() response = requests.get(page_url, headers=headers, cookies=cookies, verify=False) test_html_code(response.status_code,",
"requests import urllib3 import webbrowser urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) cookies = { } headers = {",
"output.write(responseContent) def test_html_code(response_code, page_url): if response_code == 200: print(f\"{page_url} : Success : {response_code}\")",
"print(f\"{page_url} : Success : {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success :",
"with open('test.txt', \"r\") as sites: lines = sites.readlines() for line in lines: page_url",
"def write_report(): with open('success.txt', \"w\") as output: output.write(\"PAGES THAT 200:\\n\") for elm in",
"'\\\\t', 'b\\''] responseContent = str(response.content).strip() for elm in badchars: responseContent = responseContent.replace(elm, \"\")",
"elm in sites_200: # webbrowser.open(elm) output.write(f\"{elm}\\n\") output.write(\"\\n\\nPAGES THAT 403:\\n\") for elm in sites_403:",
": Success : {response_code}\") sites_200.append(page_url) elif response_code == 403: print(f\"{page_url}: Success : {response_code}\")"
] |
[
"1 if checkList[index + width - 1] == LIVE: count += 1 if",
"height): os.system('clear') for index in range(width * height): if index < width: pass",
"live neighbours dies, as if caused by underpopulation. # Any live cell with",
"old_list = first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width",
"== LIVE: count += 1 if checkList[index - 1] == LIVE: count +=",
"index in range(width * height): # 枠は何もしない if index < width: pass elif",
"index % width == 0: first_list[index] = DEAD elif index % width ==",
"if checkList[index - 1] == LIVE: count += 1 if checkList[index + 1]",
"width * (height - 1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD])",
"life_cell_count == 2 or life_cell_count == 3: newList[index] = LIVE else: newList[index] =",
"range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD",
"caused by underpopulation. # Any live cell with two or three live neighbours",
"with exactly three live neighbours becomes a live cell, as if by reproduction.",
"on to the next generation. # Any live cell with more than three",
"+ 2 height = MAX_HEIGHT + 2 first_list = [DEAD] * (width *",
"time import copy import os LIVE = '*' DEAD = ' ' MAX_WIDTH",
"life_cell_count == 3: newList[index] = LIVE def print_life(life_list, width, height): os.system('clear') for index",
"+ 1] == LIVE: count += 1 if checkList[index + width - 1]",
"1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list",
"= 40 MAX_HEIGHT = 20 # Any live cell with fewer than two",
"width): count = 0 if checkList[index - width - 1] == LIVE: count",
"LIVE: count += 1 return count def check_life(oldList, newList, index, width): life_cell_count =",
"width] == LIVE: count += 1 if checkList[index + width + 1] ==",
"next generation. # Any live cell with more than three live neighbours dies,",
"Any live cell with more than three live neighbours dies, as if by",
"= LIVE else: newList[index] = DEAD elif oldList[index] == DEAD: if life_cell_count ==",
"# Any live cell with two or three live neighbours lives on to",
"utf-8 import random import sys, time import copy import os LIVE = '*'",
"width - 1] == LIVE: count += 1 if checkList[index + width] ==",
"a live cell, as if by reproduction. def count_live_neighbours(checkList, index, width): count =",
"<= 1: newList[index] = DEAD elif life_cell_count == 2 or life_cell_count == 3:",
"# Any live cell with more than three live neighbours dies, as if",
"live neighbours dies, as if by overpopulation. # Any dead cell with exactly",
"checkList[index - width + 1] == LIVE: count += 1 if checkList[index -",
"width) if oldList[index] == LIVE: if life_cell_count <= 1: newList[index] = DEAD elif",
"as if caused by underpopulation. # Any live cell with two or three",
"index, width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if life_cell_count",
"dies, as if by overpopulation. # Any dead cell with exactly three live",
"dead cell with exactly three live neighbours becomes a live cell, as if",
"0 if checkList[index - width - 1] == LIVE: count += 1 if",
"+ width + 1] == LIVE: count += 1 return count def check_life(oldList,",
"* (height - 1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list,",
"= count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if life_cell_count <= 1: newList[index]",
"exactly three live neighbours becomes a live cell, as if by reproduction. def",
"checkList[index + width] == LIVE: count += 1 if checkList[index + width +",
"Any live cell with two or three live neighbours lives on to the",
"= DEAD elif index % width == width - 1: first_list[index] = DEAD",
"else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list while True:",
"if life_cell_count <= 1: newList[index] = DEAD elif life_cell_count == 2 or life_cell_count",
"# Any live cell with fewer than two live neighbours dies, as if",
"% width == width - 1: pass elif index >= width * (height",
"height) for index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index <",
"cell with fewer than two live neighbours dies, as if caused by underpopulation.",
"== 0: first_list[index] = DEAD elif index % width == width - 1:",
"live cell with more than three live neighbours dies, as if by overpopulation.",
"3: newList[index] = LIVE def print_life(life_list, width, height): os.system('clear') for index in range(width",
"for index in range(width * height): # 枠は何もしない if index < width: pass",
"[DEAD] * (width * height) for index in range(width * height): # 枠はDEADで固定,",
"== LIVE: count += 1 if checkList[index + width] == LIVE: count +=",
"count += 1 if checkList[index - width + 1] == LIVE: count +=",
"DEAD elif index % width == 0: first_list[index] = DEAD elif index %",
"== LIVE: count += 1 if checkList[index - width] == LIVE: count +=",
"width - 1: pass elif index >= width * (height - 1): pass",
"- 1: pass elif index >= width * (height - 1): pass else:",
"1: pass elif index >= width * (height - 1): pass else: sys.stdout.write(str(life_list[index]))",
"three live neighbours dies, as if by overpopulation. # Any dead cell with",
"= DEAD elif life_cell_count == 2 or life_cell_count == 3: newList[index] = LIVE",
"neighbours dies, as if caused by underpopulation. # Any live cell with two",
"1] == LIVE: count += 1 if checkList[index + width - 1] ==",
"in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] =",
"' MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any live cell with fewer",
"= DEAD elif index >= width * (height - 1): first_list[index] = DEAD",
"count def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index]",
"width + 1] == LIVE: count += 1 if checkList[index - 1] ==",
"= first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width *",
"LIVE: count += 1 if checkList[index + width - 1] == LIVE: count",
"elif index % width == 0: pass elif index % width == width",
"Any dead cell with exactly three live neighbours becomes a live cell, as",
"index >= width * (height - 1): first_list[index] = DEAD else: first_list[index] =",
"if index % width == width - 2: print(\"\") width = MAX_WIDTH +",
"checkList[index - width] == LIVE: count += 1 if checkList[index - width +",
"count += 1 if checkList[index - 1] == LIVE: count += 1 if",
"(width * height) for index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if",
"* (height - 1): pass else: sys.stdout.write(str(life_list[index])) if index % width == width",
"sys, time import copy import os LIVE = '*' DEAD = ' '",
"two or three live neighbours lives on to the next generation. # Any",
"DEAD]) print_life(first_list, width, height) old_list = first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list)",
"sys.stdout.write(str(life_list[index])) if index % width == width - 2: print(\"\") width = MAX_WIDTH",
"== LIVE: if life_cell_count <= 1: newList[index] = DEAD elif life_cell_count == 2",
"LIVE else: newList[index] = DEAD elif oldList[index] == DEAD: if life_cell_count == 3:",
"width * (height - 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width)",
"= copy.deepcopy(old_list) for index in range(width * height): # 枠は何もしない if index <",
"index % width == width - 1: pass elif index >= width *",
"+= 1 if checkList[index + width - 1] == LIVE: count += 1",
"count += 1 if checkList[index - width] == LIVE: count += 1 if",
"elif index % width == width - 1: first_list[index] = DEAD elif index",
"= [DEAD] * (width * height) for index in range(width * height): #",
"os.system('clear') for index in range(width * height): if index < width: pass elif",
"if checkList[index - width - 1] == LIVE: count += 1 if checkList[index",
"width - 1] == LIVE: count += 1 if checkList[index - width] ==",
"index % width == width - 1: first_list[index] = DEAD elif index >=",
"reproduction. def count_live_neighbours(checkList, index, width): count = 0 if checkList[index - width -",
"range(width * height): if index < width: pass elif index % width ==",
"MAX_WIDTH + 2 height = MAX_HEIGHT + 2 first_list = [DEAD] * (width",
"index % width == 0: pass elif index % width == width -",
"- 1] == LIVE: count += 1 if checkList[index + 1] == LIVE:",
"elif index % width == width - 1: pass elif index >= width",
"== 3: newList[index] = LIVE def print_life(life_list, width, height): os.system('clear') for index in",
"1 if checkList[index - width + 1] == LIVE: count += 1 if",
"pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list, width, height) old_list =",
"generation. # Any live cell with more than three live neighbours dies, as",
"live neighbours becomes a live cell, as if by reproduction. def count_live_neighbours(checkList, index,",
"height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD elif index",
"in range(width * height): if index < width: pass elif index % width",
"- width - 1] == LIVE: count += 1 if checkList[index - width]",
"first_list = [DEAD] * (width * height) for index in range(width * height):",
"index in range(width * height): if index < width: pass elif index %",
"== LIVE: count += 1 if checkList[index + width - 1] == LIVE:",
"oldList[index] == DEAD: if life_cell_count == 3: newList[index] = LIVE def print_life(life_list, width,",
"20 # Any live cell with fewer than two live neighbours dies, as",
"1: newList[index] = DEAD elif life_cell_count == 2 or life_cell_count == 3: newList[index]",
"underpopulation. # Any live cell with two or three live neighbours lives on",
"with more than three live neighbours dies, as if by overpopulation. # Any",
"' ' MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any live cell with",
"2: print(\"\") width = MAX_WIDTH + 2 height = MAX_HEIGHT + 2 first_list",
"def count_live_neighbours(checkList, index, width): count = 0 if checkList[index - width - 1]",
"if checkList[index + width - 1] == LIVE: count += 1 if checkList[index",
"+ 1] == LIVE: count += 1 if checkList[index - 1] == LIVE:",
"width == width - 2: print(\"\") width = MAX_WIDTH + 2 height =",
"for index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width:",
"== LIVE: count += 1 return count def check_life(oldList, newList, index, width): life_cell_count",
"< width: first_list[index] = DEAD elif index % width == 0: first_list[index] =",
"index < width: pass elif index % width == 0: pass elif index",
"width == 0: pass elif index % width == width - 1: pass",
"# 枠は何もしない if index < width: pass elif index % width == 0:",
"width - 1: first_list[index] = DEAD elif index >= width * (height -",
"1: first_list[index] = DEAD elif index >= width * (height - 1): first_list[index]",
"the next generation. # Any live cell with more than three live neighbours",
"< width: pass elif index % width == 0: pass elif index %",
"DEAD elif oldList[index] == DEAD: if life_cell_count == 3: newList[index] = LIVE def",
"coding: utf-8 import random import sys, time import copy import os LIVE =",
"= MAX_WIDTH + 2 height = MAX_HEIGHT + 2 first_list = [DEAD] *",
"cell with more than three live neighbours dies, as if by overpopulation. #",
"def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] ==",
"print_life(life_list, width, height): os.system('clear') for index in range(width * height): if index <",
"= 20 # Any live cell with fewer than two live neighbours dies,",
"height): if index < width: pass elif index % width == 0: pass",
"== LIVE: count += 1 if checkList[index - width + 1] == LIVE:",
"count += 1 if checkList[index + width - 1] == LIVE: count +=",
"count += 1 return count def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList,",
"= random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list while True: time.sleep(0.5) new_list",
"= DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list",
"True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width * height): # 枠は何もしない",
"枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD elif index % width ==",
"枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD elif index % width",
"0: pass elif index % width == width - 1: pass elif index",
"if life_cell_count == 3: newList[index] = LIVE def print_life(life_list, width, height): os.system('clear') for",
"neighbours dies, as if by overpopulation. # Any dead cell with exactly three",
"first_list[index] = DEAD elif index >= width * (height - 1): first_list[index] =",
"* height): if index < width: pass elif index % width == 0:",
"(height - 1): pass else: sys.stdout.write(str(life_list[index])) if index % width == width -",
"== width - 1: pass elif index >= width * (height - 1):",
"- 1): pass else: sys.stdout.write(str(life_list[index])) if index % width == width - 2:",
"DEAD elif index >= width * (height - 1): first_list[index] = DEAD else:",
"* height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD elif",
"return count def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width) if",
"width == width - 1: first_list[index] = DEAD elif index >= width *",
"range(width * height): # 枠は何もしない if index < width: pass elif index %",
"+= 1 if checkList[index - width + 1] == LIVE: count += 1",
"1 return count def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width)",
"1] == LIVE: count += 1 if checkList[index - 1] == LIVE: count",
"for index in range(width * height): if index < width: pass elif index",
"DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list while",
"- 1] == LIVE: count += 1 if checkList[index + width] == LIVE:",
"== width - 2: print(\"\") width = MAX_WIDTH + 2 height = MAX_HEIGHT",
"cell, as if by reproduction. def count_live_neighbours(checkList, index, width): count = 0 if",
"LIVE = '*' DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT = 20",
"DEAD elif life_cell_count == 2 or life_cell_count == 3: newList[index] = LIVE else:",
"Any live cell with fewer than two live neighbours dies, as if caused",
"import os LIVE = '*' DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT",
"while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width * height): #",
"1 if checkList[index + width] == LIVE: count += 1 if checkList[index +",
"else: sys.stdout.write(str(life_list[index])) if index % width == width - 2: print(\"\") width =",
"= DEAD elif index % width == 0: first_list[index] = DEAD elif index",
"1: pass elif index >= width * (height - 1): pass # 枠の内部は世代を進める",
"LIVE: count += 1 if checkList[index - width] == LIVE: count += 1",
"LIVE: count += 1 if checkList[index + width + 1] == LIVE: count",
"elif index >= width * (height - 1): pass else: sys.stdout.write(str(life_list[index])) if index",
"% width == 0: pass elif index % width == width - 1:",
"by underpopulation. # Any live cell with two or three live neighbours lives",
"first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width * height):",
"+= 1 return count def check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index,",
"= MAX_HEIGHT + 2 first_list = [DEAD] * (width * height) for index",
"elif index >= width * (height - 1): first_list[index] = DEAD else: first_list[index]",
"% width == 0: first_list[index] = DEAD elif index % width == width",
"first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list =",
"count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if life_cell_count <= 1: newList[index] =",
"os LIVE = '*' DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT =",
"newList[index] = DEAD elif oldList[index] == DEAD: if life_cell_count == 3: newList[index] =",
"index, width) if oldList[index] == LIVE: if life_cell_count <= 1: newList[index] = DEAD",
"* height) for index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index",
"+ width - 1] == LIVE: count += 1 if checkList[index + width]",
"by reproduction. def count_live_neighbours(checkList, index, width): count = 0 if checkList[index - width",
"def print_life(life_list, width, height): os.system('clear') for index in range(width * height): if index",
"import sys, time import copy import os LIVE = '*' DEAD = '",
"* height): # 枠は何もしない if index < width: pass elif index % width",
"pass elif index >= width * (height - 1): pass # 枠の内部は世代を進める else:",
"else: newList[index] = DEAD elif oldList[index] == DEAD: if life_cell_count == 3: newList[index]",
"count += 1 if checkList[index + width] == LIVE: count += 1 if",
"elif life_cell_count == 2 or life_cell_count == 3: newList[index] = LIVE else: newList[index]",
"2 first_list = [DEAD] * (width * height) for index in range(width *",
"in range(width * height): # 枠は何もしない if index < width: pass elif index",
"newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if",
"index >= width * (height - 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list,",
"* (width * height) for index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく",
"time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in range(width * height): # 枠は何もしない if",
"width] == LIVE: count += 1 if checkList[index - width + 1] ==",
"== DEAD: if life_cell_count == 3: newList[index] = LIVE def print_life(life_list, width, height):",
"0: first_list[index] = DEAD elif index % width == width - 1: first_list[index]",
"elif oldList[index] == DEAD: if life_cell_count == 3: newList[index] = LIVE def print_life(life_list,",
"count += 1 if checkList[index + width + 1] == LIVE: count +=",
"three live neighbours lives on to the next generation. # Any live cell",
"<filename>lifegame.py # coding: utf-8 import random import sys, time import copy import os",
"as if by reproduction. def count_live_neighbours(checkList, index, width): count = 0 if checkList[index",
"1] == LIVE: count += 1 if checkList[index + width] == LIVE: count",
">= width * (height - 1): pass else: sys.stdout.write(str(life_list[index])) if index % width",
"== LIVE: count += 1 if checkList[index + width + 1] == LIVE:",
"if oldList[index] == LIVE: if life_cell_count <= 1: newList[index] = DEAD elif life_cell_count",
"1): pass else: sys.stdout.write(str(life_list[index])) if index % width == width - 2: print(\"\")",
"+= 1 if checkList[index + width] == LIVE: count += 1 if checkList[index",
"if checkList[index + width + 1] == LIVE: count += 1 return count",
"live cell, as if by reproduction. def count_live_neighbours(checkList, index, width): count = 0",
"dies, as if caused by underpopulation. # Any live cell with two or",
"LIVE: if life_cell_count <= 1: newList[index] = DEAD elif life_cell_count == 2 or",
"elif index >= width * (height - 1): pass # 枠の内部は世代を進める else: check_life(old_list,",
"height = MAX_HEIGHT + 2 first_list = [DEAD] * (width * height) for",
"than two live neighbours dies, as if caused by underpopulation. # Any live",
"by overpopulation. # Any dead cell with exactly three live neighbours becomes a",
"LIVE: count += 1 if checkList[index + width] == LIVE: count += 1",
"== LIVE: count += 1 if checkList[index + 1] == LIVE: count +=",
"index < width: first_list[index] = DEAD elif index % width == 0: first_list[index]",
"random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list while True: time.sleep(0.5) new_list =",
"LIVE: count += 1 if checkList[index - width + 1] == LIVE: count",
"1 if checkList[index + width + 1] == LIVE: count += 1 return",
"== 3: newList[index] = LIVE else: newList[index] = DEAD elif oldList[index] == DEAD:",
"print_life(first_list, width, height) old_list = first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for",
"- 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list, width, height)",
"check_life(oldList, newList, index, width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] == LIVE:",
"life_cell_count <= 1: newList[index] = DEAD elif life_cell_count == 2 or life_cell_count ==",
"* (height - 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list,",
"1] == LIVE: count += 1 if checkList[index + 1] == LIVE: count",
"+ 2 first_list = [DEAD] * (width * height) for index in range(width",
"DEAD: if life_cell_count == 3: newList[index] = LIVE def print_life(life_list, width, height): os.system('clear')",
"+= 1 if checkList[index + width + 1] == LIVE: count += 1",
"= LIVE def print_life(life_list, width, height): os.system('clear') for index in range(width * height):",
"width == 0: first_list[index] = DEAD elif index % width == width -",
"becomes a live cell, as if by reproduction. def count_live_neighbours(checkList, index, width): count",
"- 1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height)",
"== 0: pass elif index % width == width - 1: pass elif",
"height) old_list = first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index in",
"newList[index] = DEAD elif life_cell_count == 2 or life_cell_count == 3: newList[index] =",
"# 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index] = DEAD elif index %",
"# Any dead cell with exactly three live neighbours becomes a live cell,",
"cell with exactly three live neighbours becomes a live cell, as if by",
"if checkList[index + 1] == LIVE: count += 1 if checkList[index + width",
"width + 1] == LIVE: count += 1 return count def check_life(oldList, newList,",
"LIVE def print_life(life_list, width, height): os.system('clear') for index in range(width * height): if",
"= ' ' MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any live cell",
"== width - 1: first_list[index] = DEAD elif index >= width * (height",
"(height - 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list, width,",
"# coding: utf-8 import random import sys, time import copy import os LIVE",
"pass elif index >= width * (height - 1): pass else: sys.stdout.write(str(life_list[index])) if",
"DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any live",
"two live neighbours dies, as if caused by underpopulation. # Any live cell",
"if by overpopulation. # Any dead cell with exactly three live neighbours becomes",
"width * (height - 1): pass else: sys.stdout.write(str(life_list[index])) if index % width ==",
"pass else: sys.stdout.write(str(life_list[index])) if index % width == width - 2: print(\"\") width",
"% width == width - 1: first_list[index] = DEAD elif index >= width",
"(height - 1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width,",
"overpopulation. # Any dead cell with exactly three live neighbours becomes a live",
"newList[index] = LIVE else: newList[index] = DEAD elif oldList[index] == DEAD: if life_cell_count",
"oldList[index] == LIVE: if life_cell_count <= 1: newList[index] = DEAD elif life_cell_count ==",
"width, height): os.system('clear') for index in range(width * height): if index < width:",
"three live neighbours becomes a live cell, as if by reproduction. def count_live_neighbours(checkList,",
"count_live_neighbours(checkList, index, width): count = 0 if checkList[index - width - 1] ==",
"width, height) old_list = first_list while True: time.sleep(0.5) new_list = copy.deepcopy(old_list) for index",
"with two or three live neighbours lives on to the next generation. #",
"pass elif index % width == width - 1: pass elif index >=",
"fewer than two live neighbours dies, as if caused by underpopulation. # Any",
"2 height = MAX_HEIGHT + 2 first_list = [DEAD] * (width * height)",
"neighbours lives on to the next generation. # Any live cell with more",
"than three live neighbours dies, as if by overpopulation. # Any dead cell",
"+= 1 if checkList[index + 1] == LIVE: count += 1 if checkList[index",
"live cell with two or three live neighbours lives on to the next",
"1 if checkList[index + 1] == LIVE: count += 1 if checkList[index +",
"LIVE: count += 1 if checkList[index + 1] == LIVE: count += 1",
"== 2 or life_cell_count == 3: newList[index] = LIVE else: newList[index] = DEAD",
"new_list = copy.deepcopy(old_list) for index in range(width * height): # 枠は何もしない if index",
"index, width): count = 0 if checkList[index - width - 1] == LIVE:",
"index % width == width - 2: print(\"\") width = MAX_WIDTH + 2",
"first_list[index] = DEAD elif index % width == width - 1: first_list[index] =",
"+= 1 if checkList[index - width] == LIVE: count += 1 if checkList[index",
"1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list, width, height) old_list",
"or three live neighbours lives on to the next generation. # Any live",
"height): # 枠は何もしない if index < width: pass elif index % width ==",
"width: first_list[index] = DEAD elif index % width == 0: first_list[index] = DEAD",
"- width + 1] == LIVE: count += 1 if checkList[index - 1]",
"first_list[index] = random.choice([LIVE, DEAD]) print_life(first_list, width, height) old_list = first_list while True: time.sleep(0.5)",
"life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if life_cell_count <= 1:",
"index in range(width * height): # 枠はDEADで固定, 枠内部はランダムに設定しておく if index < width: first_list[index]",
"import random import sys, time import copy import os LIVE = '*' DEAD",
"+ 1] == LIVE: count += 1 return count def check_life(oldList, newList, index,",
"count += 1 if checkList[index + 1] == LIVE: count += 1 if",
"width = MAX_WIDTH + 2 height = MAX_HEIGHT + 2 first_list = [DEAD]",
"if checkList[index + width] == LIVE: count += 1 if checkList[index + width",
"width - 2: print(\"\") width = MAX_WIDTH + 2 height = MAX_HEIGHT +",
"40 MAX_HEIGHT = 20 # Any live cell with fewer than two live",
"3: newList[index] = LIVE else: newList[index] = DEAD elif oldList[index] == DEAD: if",
"with fewer than two live neighbours dies, as if caused by underpopulation. #",
"life_cell_count == 3: newList[index] = LIVE else: newList[index] = DEAD elif oldList[index] ==",
"if index < width: pass elif index % width == 0: pass elif",
"2 or life_cell_count == 3: newList[index] = LIVE else: newList[index] = DEAD elif",
"or life_cell_count == 3: newList[index] = LIVE else: newList[index] = DEAD elif oldList[index]",
"if checkList[index - width + 1] == LIVE: count += 1 if checkList[index",
"checkList[index + width - 1] == LIVE: count += 1 if checkList[index +",
"- width] == LIVE: count += 1 if checkList[index - width + 1]",
"DEAD elif index % width == width - 1: first_list[index] = DEAD elif",
"count = 0 if checkList[index - width - 1] == LIVE: count +=",
">= width * (height - 1): first_list[index] = DEAD else: first_list[index] = random.choice([LIVE,",
">= width * (height - 1): pass # 枠の内部は世代を進める else: check_life(old_list, new_list, index,",
"if checkList[index - width] == LIVE: count += 1 if checkList[index - width",
"width: pass elif index % width == 0: pass elif index % width",
"# 枠の内部は世代を進める else: check_life(old_list, new_list, index, width) print_life(new_list, width, height) old_list = new_list",
"index >= width * (height - 1): pass else: sys.stdout.write(str(life_list[index])) if index %",
"= '*' DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT = 20 #",
"- 1: first_list[index] = DEAD elif index >= width * (height - 1):",
"if index < width: first_list[index] = DEAD elif index % width == 0:",
"= DEAD elif oldList[index] == DEAD: if life_cell_count == 3: newList[index] = LIVE",
"elif index % width == 0: first_list[index] = DEAD elif index % width",
"MAX_HEIGHT + 2 first_list = [DEAD] * (width * height) for index in",
"MAX_HEIGHT = 20 # Any live cell with fewer than two live neighbours",
"枠は何もしない if index < width: pass elif index % width == 0: pass",
"1 if checkList[index - 1] == LIVE: count += 1 if checkList[index +",
"checkList[index - 1] == LIVE: count += 1 if checkList[index + 1] ==",
"print(\"\") width = MAX_WIDTH + 2 height = MAX_HEIGHT + 2 first_list =",
"1] == LIVE: count += 1 if checkList[index - width] == LIVE: count",
"MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any live cell with fewer than",
"first_list[index] = DEAD elif index % width == 0: first_list[index] = DEAD elif",
"copy.deepcopy(old_list) for index in range(width * height): # 枠は何もしない if index < width:",
"if caused by underpopulation. # Any live cell with two or three live",
"copy import os LIVE = '*' DEAD = ' ' MAX_WIDTH = 40",
"width == width - 1: pass elif index >= width * (height -",
"1] == LIVE: count += 1 return count def check_life(oldList, newList, index, width):",
"newList[index] = LIVE def print_life(life_list, width, height): os.system('clear') for index in range(width *",
"+= 1 if checkList[index - 1] == LIVE: count += 1 if checkList[index",
"- 1: pass elif index >= width * (height - 1): pass #",
"- 2: print(\"\") width = MAX_WIDTH + 2 height = MAX_HEIGHT + 2",
"LIVE: count += 1 if checkList[index - 1] == LIVE: count += 1",
"checkList[index + 1] == LIVE: count += 1 if checkList[index + width -",
"checkList[index - width - 1] == LIVE: count += 1 if checkList[index -",
"checkList[index + width + 1] == LIVE: count += 1 return count def",
"as if by overpopulation. # Any dead cell with exactly three live neighbours",
"neighbours becomes a live cell, as if by reproduction. def count_live_neighbours(checkList, index, width):",
"more than three live neighbours dies, as if by overpopulation. # Any dead",
"live neighbours lives on to the next generation. # Any live cell with",
"= 0 if checkList[index - width - 1] == LIVE: count += 1",
"cell with two or three live neighbours lives on to the next generation.",
"pass elif index % width == 0: pass elif index % width ==",
"+ width] == LIVE: count += 1 if checkList[index + width + 1]",
"random import sys, time import copy import os LIVE = '*' DEAD =",
"live cell with fewer than two live neighbours dies, as if caused by",
"width): life_cell_count = count_live_neighbours(oldList, index, width) if oldList[index] == LIVE: if life_cell_count <=",
"% width == width - 2: print(\"\") width = MAX_WIDTH + 2 height",
"import copy import os LIVE = '*' DEAD = ' ' MAX_WIDTH =",
"- 1] == LIVE: count += 1 if checkList[index - width] == LIVE:",
"lives on to the next generation. # Any live cell with more than",
"1 if checkList[index - width] == LIVE: count += 1 if checkList[index -",
"to the next generation. # Any live cell with more than three live",
"if by reproduction. def count_live_neighbours(checkList, index, width): count = 0 if checkList[index -",
"'*' DEAD = ' ' MAX_WIDTH = 40 MAX_HEIGHT = 20 # Any"
] |
[
"rest of the code will be only runned when execured from the terminal",
"the tello camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\")",
"rate.sleep() # -- the rest of the code will be only runned when",
"0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0, 0, 0, 1], P=[",
"to calibrate the tello camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo,",
"height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000,",
"datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() # -- the rest of",
"0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published",
"node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo(",
"0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000,",
"while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r')",
"0, 0, 0, 1, 0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000,",
"1, 0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597,",
"354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0, 0, 0, 1],",
"be only runned when execured from the terminal if __name__ == '__main__': publisher()",
"\"\"\" This method contains the information to calibrate the tello camera \"\"\" print(\"Starting",
"print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() # -- the rest of the",
"0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1,",
"information to calibrate the tello camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\",",
"#!/usr/bin/python3 import rospy from sensor_msgs.msg import CameraInfo from datetime import datetime def publisher():",
"calibrate the tello camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10)",
"CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335,",
"fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424,",
"= CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000,",
"R=[1, 0, 0, 0, 1, 0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272,",
"rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454,",
"0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000,",
"453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0,",
"rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\",",
"now = datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() # -- the",
") while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration info\",",
"method contains the information to calibrate the tello camera \"\"\" print(\"Starting calibrator node\")",
"the information to calibrate the tello camera \"\"\" print(\"Starting calibrator node\") publisher =",
"queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951,",
"CameraInfo from datetime import datetime def publisher(): \"\"\" This method contains the information",
"print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg",
"= rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720,",
"= datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() # -- the rest",
"-0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1,",
"K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0,",
"D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000,",
"0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0, 0,",
"<reponame>PedroS235/TelloSwarm<gh_stars>0 #!/usr/bin/python3 import rospy from sensor_msgs.msg import CameraInfo from datetime import datetime def",
"code will be only runned when execured from the terminal if __name__ ==",
"publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() # --",
"= rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000],",
"0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0, 0, 0, 1], P=[ 891.148254,",
"0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time()",
"0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while",
"tello camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate",
"P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000],",
"rospy from sensor_msgs.msg import CameraInfo from datetime import datetime def publisher(): \"\"\" This",
"from datetime import datetime def publisher(): \"\"\" This method contains the information to",
"def publisher(): \"\"\" This method contains the information to calibrate the tello camera",
"-- the rest of the code will be only runned when execured from",
"distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881,",
"datetime def publisher(): \"\"\" This method contains the information to calibrate the tello",
"datetime import datetime def publisher(): \"\"\" This method contains the information to calibrate",
"calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg =",
"the code will be only runned when execured from the terminal if __name__",
"of the code will be only runned when execured from the terminal if",
"import rospy from sensor_msgs.msg import CameraInfo from datetime import datetime def publisher(): \"\"\"",
"0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}:",
"-0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000,",
"published camera calibration info\", end='\\r') rate.sleep() # -- the rest of the code",
"0, 0, 1, 0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000,",
"sensor_msgs.msg import CameraInfo from datetime import datetime def publisher(): \"\"\" This method contains",
"1.000000], R=[1, 0, 0, 0, 1, 0, 0, 0, 1], P=[ 891.148254, 0.000000,",
"1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000,",
"the rest of the code will be only runned when execured from the",
"\"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15)",
"891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], )",
"camera \"\"\" print(\"Starting calibrator node\") publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate =",
"calibration info\", end='\\r') rate.sleep() # -- the rest of the code will be",
"449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not",
"355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now =",
"0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000,",
"contains the information to calibrate the tello camera \"\"\" print(\"Starting calibrator node\") publisher",
"import CameraInfo from datetime import datetime def publisher(): \"\"\" This method contains the",
"0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000],",
"info\", end='\\r') rate.sleep() # -- the rest of the code will be only",
"camera calibration info\", end='\\r') rate.sleep() # -- the rest of the code will",
"0.000000, 0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown():",
"publisher(): \"\"\" This method contains the information to calibrate the tello camera \"\"\"",
"# -- the rest of the code will be only runned when execured",
"will be only runned when execured from the terminal if __name__ == '__main__':",
"901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now",
"from sensor_msgs.msg import CameraInfo from datetime import datetime def publisher(): \"\"\" This method",
"1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera",
"0, 1, 0, 0, 0, 1], P=[ 891.148254, 0.000000, 449.250272, 0.000000, 0.000000, 901.238647,",
"897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0,",
"0.000000, 901.238647, 355.367597, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg)",
"rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep() #",
"0.000000], ) while not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration",
"not rospy.is_shutdown(): publisher.publish(fixed_msg) now = datetime.now().time() print(f\"{now}: published camera calibration info\", end='\\r') rate.sleep()",
"902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0, 0, 0, 1, 0, 0, 0,",
"publisher = rospy.Publisher(\"camera/camera_info\", CameraInfo, queue_size=10) rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960,",
"CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111,",
"rospy.init_node(\"calibrator\") rate = rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913,",
"0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567, 354.958881, 0.000000, 0.000000, 1.000000], R=[1, 0,",
"rospy.Rate(15) fixed_msg = CameraInfo( height=960, width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[",
"end='\\r') rate.sleep() # -- the rest of the code will be only runned",
"This method contains the information to calibrate the tello camera \"\"\" print(\"Starting calibrator",
"width=720, distortion_model=\"plumb_bob\", D=[-0.013335, -0.018951, 0.000913, -0.005454, 0.000000], K=[ 897.137424, 0.000000, 453.939111, 0.000000, 902.273567,",
"import datetime def publisher(): \"\"\" This method contains the information to calibrate the"
] |
[
"#Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered",
"Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName = []",
"RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible",
"matches list hostnames,an more for xx in range(len(matches)): #print(AllDataPluginNames[xx]) print(xx,AllDataHostNames[matches[xx]],AllDataProtocols[matches[xx]],AllDataPorts[matches[xx]]) #print() print(\"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\") #AllData.append(({AllDataPluginNames[j]:[AllDataHostNames[j],AllDataProtocols[j],AllDataPorts[j]]}))",
"#Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable",
"Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName =",
"csv import sys from collections import defaultdict #Defining list of variables hold the",
"= [] RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate",
"= list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData = list() for j",
"= [] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso =",
"= list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit",
"RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin ID']",
"#See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE =",
"[] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity",
"RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last",
"rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows =",
"[] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list()",
"Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol",
"= [] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress =",
"= list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address Varible",
"#Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName",
"ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port']",
"list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer",
"#RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName)",
"= list() #All Data In One Place PluginsIndexList = [] PluginsIndexList = list()",
"SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows =",
"[] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list()",
"RowOfDataProtocol = list() #Port Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible",
"RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort = [] RowOfDataPort =",
"RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS",
"RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin",
"RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All",
"RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible",
"= list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData =",
"list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed Varibale",
"value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data",
"the data based on matches list hostnames,an more for xx in range(len(matches)): #print(AllDataPluginNames[xx])",
"RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol =",
"= [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks =",
"IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort()",
"= [] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName =",
"= csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList",
"RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication",
"= list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See Also Varibale",
"[] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution",
"RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase",
"RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable =",
"RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit",
"for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList))",
"collections import defaultdict #Defining list of variables hold the actual data. #IP Addresses",
"RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data In One Place PluginsIndexList =",
"PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile)",
"AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData",
"= list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed",
"in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based",
"[index for index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\")",
"#Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data In One",
"as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows",
"open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] ==",
"matches = [index for index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\")",
"#MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName",
"RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks",
"AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData = list() for",
"PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter <",
"RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName",
"IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results",
"Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription",
"= list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale",
"list() #Port Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable =",
"defaultdict #Defining list of variables hold the actual data. #IP Addresses Varible RowOfDataIPAddress",
"RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading:",
"= [] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved =",
"list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort =",
"Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable",
"list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1",
"= [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE = list()",
"actual data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID",
"#Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort = []",
"from collections import defaultdict #Defining list of variables hold the actual data. #IP",
"1 AllData = [] AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches",
"Place PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader =",
"list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName",
"[] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository",
"[] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list()",
"with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer =",
"= IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows",
"RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName)",
"#First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved",
"#Repository Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress =",
"Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = []",
"RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName",
"RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See Also",
"Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = []",
"#Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso =",
"Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved = []",
"RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription =",
"= list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text",
"= list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader:",
"list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as",
"Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText = []",
"[] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description",
"#Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis =",
"= list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort",
"ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter",
"= [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list()",
"RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale",
"= list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 =",
"data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host']",
"Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName = []",
"#IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID",
"Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis",
"== AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on matches list hostnames,an",
"PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending",
"#DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName",
"= list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address Variable",
"[] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows",
"len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if",
"= IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the",
"[] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list()",
"Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = []",
"print(j,AllDataPluginNames2[j]) matches = [index for index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]]",
"list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort)",
"= list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity",
"results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs =",
"= [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list()",
"= list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data",
"RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin",
"[] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity",
"= [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list()",
"index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the",
"[] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list()",
"j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value in enumerate(AllDataPluginNames) if",
"= [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily = list()",
"One Place PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader",
"[] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName = list()",
"#CVE Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate",
"MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer)",
"RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First",
"= [] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID =",
"= list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv')",
"Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase",
"as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin",
"print(matches) print(\"*************************************************************************************\") #display the data based on matches list hostnames,an more for xx",
"#Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily =",
"Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso = []",
"SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching",
"Address Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = []",
"= [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription = list()",
"FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter",
"list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData = list()",
"IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort()",
"list of variables hold the actual data. #IP Addresses Varible RowOfDataIPAddress = []",
"while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows",
"Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate =",
"[] RowOfDataExploitEase = list() #All Data In One Place PluginsIndexList = [] PluginsIndexList",
"RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = []",
"IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in the lists",
"list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository =",
"RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale",
"RowOfDataExploitEase = list() #All Data In One Place PluginsIndexList = [] PluginsIndexList =",
"= csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the",
"= [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort = [] RowOfDataPort = list()",
"list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name Varibale",
"Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName = []",
"IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader =",
"#Port Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = []",
"= [] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered =",
"IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows =",
"variables hold the actual data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress =",
"sys from collections import defaultdict #Defining list of variables hold the actual data.",
"print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader",
"of variables hold the actual data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress",
"#Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName =",
"RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID",
"RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list()",
"Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID =",
"Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data In One Place PluginsIndexList",
"Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID = []",
"= list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name",
"= [] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for",
"#Defining list of variables hold the actual data. #IP Addresses Varible RowOfDataIPAddress =",
"= IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows)",
"= list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value",
"[] RowOfDataProtocol = list() #Port Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit?",
"list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName))",
"= list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository",
"RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName))",
"= [] AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index",
"#Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = []",
"Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity",
"RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale",
"in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows",
"= [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list()",
"AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on matches list hostnames,an more",
"list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale",
"ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows)",
"IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows)",
"= list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks",
"Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase =",
"IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in",
"list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress",
"HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in",
"RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName",
"import csv import sys from collections import defaultdict #Defining list of variables hold",
"= list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter +=",
"list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso",
"< len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader:",
"IndexCounter += 1 AllData = [] AllData = list() for j in range(len(AllDataPluginNames2)):",
"if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin",
"RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity =",
"Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution",
"the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames",
"= list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols =",
"Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port Varibale RowOfDataPort = [] RowOfDataPort",
"AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts",
"= list() #Port Varibale RowOfDataPort = [] RowOfDataPort = list() #Exploit? Varible RowOfDataIsExploitable",
"RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository =",
"list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE",
"RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName",
"#Family Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = []",
"Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily",
"value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on matches list",
"list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis",
"RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE =",
"list() #All Data In One Place PluginsIndexList = [] PluginsIndexList = list() with",
"== IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows",
"ID']: #fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name']",
"[] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list()",
"Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText =",
"[] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC",
"= list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData =",
"RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family",
"with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter]",
"PluginsIndexList = list() with open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in",
"list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol",
"the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs",
"enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on",
"[] RowOfDataDNSName = list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list()",
"print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on matches list hostnames,an more for",
"RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address",
"list(RowOfDataPort) IndexCounter += 1 AllData = [] AllData = list() for j in",
"as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID']",
"on matches list hostnames,an more for xx in range(len(matches)): #print(AllDataPluginNames[xx]) print(xx,AllDataHostNames[matches[xx]],AllDataProtocols[matches[xx]],AllDataPorts[matches[xx]]) #print() print(\"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\")",
"Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved =",
"#Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription = []",
"in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList)",
"ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName =",
"RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE",
"AllData = [] AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches =",
"RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText",
"Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE",
"list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease",
"list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered Variable",
"list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication Date Variable",
"= list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list() #CVE Variable",
"= list() #CVE Variable RowOfDataCVE = [] RowOfDataCVE = list() #Vulnerablity Publication Date",
"[] RowOfDataIPAddress = list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list()",
"Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered =",
"FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort()",
"= [] RowOfDataExploitEase = list() #All Data In One Place PluginsIndexList = []",
"list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data In",
"= list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription",
"AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter",
"= IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0",
"AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols",
"= [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase =",
"0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for",
"[] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol = [] RowOfDataProtocol = list() #Port",
"Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks =",
"= [index for index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches)",
"RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with",
"IndexAllDataRows['Plugin ID']: #fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows =",
"for index, value in enumerate(AllDataPluginNames) if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display",
"RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis",
"= list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts =",
"list() #Plugin ID Varible RowOfDataPluginID = [] RowOfDataPluginID = list() #Plugin Name Varible",
"= list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale",
"list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol)",
"= [] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName =",
"import sys from collections import defaultdict #Defining list of variables hold the actual",
"#RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames =",
"Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = []",
"#display the data based on matches list hostnames,an more for xx in range(len(matches)):",
"[] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP",
"Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate = list() #Exploit Ease Variable RowOfDataExploitEase = []",
"PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows = IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol']",
"= 0 while IndexCounter < len(RemovingDublicatesFromIndexList): with open('nessus.csv') as SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading)",
"[] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list()",
"#Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks",
"Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName = []",
"RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 =",
"[] AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for",
"Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName =",
"list() #NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text Variable",
"= IndexAllDataRows['Host'] ProtocolRows = IndexAllDataRows['Protocol'] PortRows = IndexAllDataRows['Port'] #Appending the results in the",
"#Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort()",
"= [] RowOfDataPluginID = list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName =",
"AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames = list(RowOfDataHostName) AllDataHostNames2",
"Varible RowOfDataIsExploitable = [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository",
"csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data",
"list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily = list() #Severity Varible RowOfDataSeverity =",
"#IP Address Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible RowOfDataProtocol =",
"= list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress = list() #DNS Name",
"print(\"*************************************************************************************\") #display the data based on matches list hostnames,an more for xx in",
"import defaultdict #Defining list of variables hold the actual data. #IP Addresses Varible",
"= [] RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName =",
"if value == AllDataPluginNames2[j]] print(\"*************************************************************************************\") print(matches) print(\"*************************************************************************************\") #display the data based on matches",
"RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered = list() #Last Observed Varibale RowOfDataLastObserved = [] RowOfDataLastObserved",
"RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2 = list(set(RowOfDataPluginName)) AllDataHostNames",
"= [] RowOfDataIsExploitable = list() #Repository Varible RowOfDataRepository = [] RowOfDataRepository = list()",
"= [] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText =",
"In One Place PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv') as MainCSVFile:",
"hold the actual data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list()",
"[] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso = list()",
"the actual data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin",
"list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name Variable",
"open('nessus.csv') as MainCSVFile: FirstRoundReader = csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin",
"= list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol Varible",
"Data In One Place PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv') as",
"AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index,",
"<filename>all.py import csv import sys from collections import defaultdict #Defining list of variables",
"range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value in enumerate(AllDataPluginNames) if value ==",
"data based on matches list hostnames,an more for xx in range(len(matches)): #print(AllDataPluginNames[xx]) print(xx,AllDataHostNames[matches[xx]],AllDataProtocols[matches[xx]],AllDataPorts[matches[xx]])",
"Varible RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress = []",
"Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered = []",
"#Description Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = []",
"in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID)",
"RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily = [] RowOfDataFamily =",
"+= 1 AllData = [] AllData = list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j])",
"Ease Variable RowOfDataExploitEase = [] RowOfDataExploitEase = list() #All Data In One Place",
"= list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS Name",
"RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis =",
"the data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows =",
"list() #Synopsis Varibale RowOfDataSynopsis = [] RowOfDataSynopsis = list() #Description Varibale RowOfDataDescription =",
"[] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list() #See",
"[] RowOfDataLastObserved = list() #Exploit Frameworks Varibale RowOfDataExploitFrameworks = [] RowOfDataExploitFrameworks = list()",
"RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered Variable RowOfDataFirstDiscovered = [] RowOfDataFirstDiscovered",
"RowOfDataSolution = [] RowOfDataSolution = list() #See Also Varibale RowOfDataSeeAlso = [] RowOfDataSeeAlso",
"AllDataHostNames2 = list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData",
"#NetBIOS Name Variable RowOfDataNetBIOSName = [] RowOfDataNetBIOSName = list() #Plugin Text Variable RowOfDataPluginText",
"PortRows = IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows)",
"RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames = list(RowOfDataPluginName) AllDataPluginNames2",
"RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution =",
"lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows) #RowOfDataPluginName.sort() #RowOfDataHostName.sort() AllDataPluginIDs = list(RowOfDataPluginID) AllDataPluginNames =",
"for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as",
"#fetching the data as rows PluginIDRows = IndexAllDataRows['Plugin ID'] PluginNameRows = IndexAllDataRows['Name'] HostNameRows",
"PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while IndexCounter < len(RemovingDublicatesFromIndexList):",
"= list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution",
"for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value in enumerate(AllDataPluginNames)",
"in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value in enumerate(AllDataPluginNames) if value",
"= IndexAllDataRows['Port'] #Appending the results in the lists RowOfDataPluginID.append(PluginIDRows) RowOfDataPluginName.append(PluginNameRows) RowOfDataHostName.append(HostNameRows) RowOfDataProtocol.append(ProtocolRows) RowOfDataPort.append(PortRows)",
"SecondMainFileLoading: SecondRoundReader = csv.DictReader(SecondMainFileLoading) for IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']:",
"RowOfDataFamily = list() #Severity Varible RowOfDataSeverity = [] RowOfDataSeverity = list() #IP Address",
"= list() #Plugin Text Variable RowOfDataPluginText = [] RowOfDataPluginText = list() #First Discovered",
"#All Data In One Place PluginsIndexList = [] PluginsIndexList = list() with open('nessus.csv')",
"list(set(RowOfDataHostName)) AllDataProtocols = list(RowOfDataProtocol) AllDataPorts = list(RowOfDataPort) IndexCounter += 1 AllData = []",
"list() #Plugin Name Varible RowOfDataPluginName = [] RowOfDataPluginName = list() #Family Varibale RowOfDataFamily",
"IndexAllDataRows in SecondRoundReader: if RemovingDublicatesFromIndexList[IndexCounter] == IndexAllDataRows['Plugin ID']: #fetching the data as rows",
"list() #Description Varibale RowOfDataDescription = [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution =",
"RowOfDataSeverity = list() #IP Address Varible RowOfDataHostName = [] RowOfDataHostName = list() #Protocol",
"RowOfDataRepository = [] RowOfDataRepository = list() #MAC Address Variable RowOfDataMACAddress = [] RowOfDataMACAddress",
"IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter = 0 while",
"= [] RowOfDataDescription = list() #Solution Varibale RowOfDataSolution = [] RowOfDataSolution = list()",
"csv.DictReader(MainCSVFile) for IndexPluginRows in FirstRoundReader: PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList =",
"PluginListIndexer = IndexPluginRows['Plugin ID'] PluginsIndexList.append(PluginListIndexer) PluginsIndexList.sort() RemovingDublicatesFromIndexList = list(set(PluginsIndexList)) RemovingDublicatesFromIndexList.sort() print(RemovingDublicatesFromIndexList) IndexCounter =",
"based on matches list hostnames,an more for xx in range(len(matches)): #print(AllDataPluginNames[xx]) print(xx,AllDataHostNames[matches[xx]],AllDataProtocols[matches[xx]],AllDataPorts[matches[xx]]) #print()",
"RowOfDataMACAddress = list() #DNS Name Varibale RowOfDataDNSName = [] RowOfDataDNSName = list() #NetBIOS",
"list() for j in range(len(AllDataPluginNames2)): print(j,AllDataPluginNames2[j]) matches = [index for index, value in",
"[] RowOfDataCVE = list() #Vulnerablity Publication Date Variable RowOfDataVulnerablityPublicationDate = [] RowOfDataVulnerablityPublicationDate =",
"data. #IP Addresses Varible RowOfDataIPAddress = [] RowOfDataIPAddress = list() #Plugin ID Varible"
] |
[
"in locals(): import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from .",
"import AnimSequence from . import Channel from . import Clip from . import",
"AnimSequence from . import Channel from . import Clip from . import ClipDictionary",
"importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from . import AnimSequence",
"from . import Animation from . import AnimSequence from . import Channel from",
"import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation",
"from . import AnimSequence from . import Channel from . import Clip from",
". import Clip from . import ClipDictionary from . import utils import bpy",
"from . import Channel from . import Clip from . import ClipDictionary from",
"from . import Clip from . import ClipDictionary from . import utils import",
"importlib.reload(utils) else: from . import Animation from . import AnimSequence from . import",
"Channel from . import Clip from . import ClipDictionary from . import utils",
"Animation from . import AnimSequence from . import Channel from . import Clip",
"locals(): import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import",
"importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from . import AnimSequence from .",
"import Animation from . import AnimSequence from . import Channel from . import",
". import Animation from . import AnimSequence from . import Channel from .",
"importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from .",
". import Channel from . import Clip from . import ClipDictionary from .",
"else: from . import Animation from . import AnimSequence from . import Channel",
"import Channel from . import Clip from . import ClipDictionary from . import",
"<filename>formats/ycd/__init__.py if \"bpy\" in locals(): import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils)",
"importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from . import",
". import AnimSequence from . import Channel from . import Clip from .",
"importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from",
"importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from . import Animation from . import AnimSequence from",
"if \"bpy\" in locals(): import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else:",
"\"bpy\" in locals(): import importlib importlib.reload(Animation) importlib.reload(AnimSequence) importlib.reload(Channel) importlib.reload(Clip) importlib.reload(ClipDictionary) importlib.reload(utils) else: from"
] |
[] |
[
"== meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content)",
"# assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length",
"list], str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}},",
"dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting)",
"from .helpers import read_content_metadata # from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict,",
"pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length",
"( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"),",
"admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2",
"<reponame>noirbizarre/pelican-myst from __future__ import annotations from typing import Union import pytest from .helpers",
"pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([],",
"from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = (",
"import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"),",
"admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8",
"({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content,",
"\"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert",
"...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\":",
"\"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)},",
"meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions(): # content,",
"def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html =",
"html.find(\"div.admonition\") # assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert",
"as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"),",
"= html.find(\"div.admonition\") # assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8 #",
"\"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta =",
"str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"),",
"# html = pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8",
"({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"),",
"content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions(): #",
"({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def",
"({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\",",
"\"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS)",
"pytest from .helpers import read_content_metadata # from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS:",
"read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) # admonitions = html.find(\"div.admonition\") #",
"assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2 # assert html.find(\"div.admonition.warning\").length ==",
"from __future__ import annotations from typing import Union import pytest from .helpers import",
"typing import Union import pytest from .helpers import read_content_metadata # from pyquery import",
"test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def",
"def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] #",
"([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\":",
"assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length ==",
"meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) # admonitions =",
"TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key]",
"assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length ==",
"print(content) # html = pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length ==",
"html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2 # assert html.find(\"div.admonition.warning\").length == 1",
"html = pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8 #",
"dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta",
"== 8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4 #",
"# assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length",
"tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\":",
"content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) # admonitions",
"test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content)",
"MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\",",
"assert content == meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"])",
"admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4",
"= pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8 # assert",
"\"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key):",
"# content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) #",
"# admonitions = html.find(\"div.admonition\") # assert admonitions.length == 8 # assert admonitions.find(\"p.admonition-title\").length ==",
"# assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2 # assert html.find(\"div.admonition.warning\").length",
"content == meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) #",
"Union import pytest from .helpers import read_content_metadata # from pyquery import PyQuery as",
"key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions():",
"= ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)},",
"([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\",",
"from typing import Union import pytest from .helpers import read_content_metadata # from pyquery",
"meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) #",
"# from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] =",
".helpers import read_content_metadata # from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list],",
"8 # assert admonitions.find(\"p.admonition-title\").length == 8 # assert html.find(\"div.admonition.note\").length == 4 # assert",
"PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"), ({},",
"8 # assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2 # assert",
"import pytest from .helpers import read_content_metadata # from pyquery import PyQuery as pq",
"\"disabled\"), ([\"tasklist\"], \"default\"), ({\"tasklist\": {}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), )",
"TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"], \"default\"),",
"MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) # admonitions = html.find(\"div.admonition\") # assert",
"__future__ import annotations from typing import Union import pytest from .helpers import read_content_metadata",
"annotations from typing import Union import pytest from .helpers import read_content_metadata # from",
"# def test_myst_admonitions(): # content, meta = read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html",
"import Union import pytest from .helpers import read_content_metadata # from pyquery import PyQuery",
"@pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content ==",
"{}}, \"default\"), ({\"tasklist\": dict(enabled=True)}, \"enabled\"), ({\"tasklist\": dict(label=True)}, \"label\"), ) @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting,",
"= read_content_metadata(\"myst/admonitions.md\", MYST_PLUGINS=[\"admonitions\"]) # print(content) # html = pq(content) # admonitions = html.find(\"div.admonition\")",
"read_content_metadata # from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...]",
"# print(content) # html = pq(content) # admonitions = html.find(\"div.admonition\") # assert admonitions.length",
") @pytest.mark.parametrize(\"setting,key\", TASKLIST_EXPECTATIONS) def test_myst_tasklist(setting, key): content, meta = read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content",
"= read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta",
"read_content_metadata(\"myst/tasklist.md\", MYST_PLUGINS=setting) assert content == meta[\"expected\"][key] # def test_myst_admonitions(): # content, meta =",
"import annotations from typing import Union import pytest from .helpers import read_content_metadata #",
"import read_content_metadata # from pyquery import PyQuery as pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str],",
"== 8 # assert html.find(\"div.admonition.note\").length == 4 # assert html.find(\"div.admonition.important\").length == 2 #",
"pq TASKLIST_EXPECTATIONS: tuple[tuple[Union[dict, list], str], ...] = ( ([], \"disabled\"), ({}, \"disabled\"), ([\"tasklist\"],"
] |
[
"fetch and pass into localstore all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont,",
"mode for ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder",
"for i in item if i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch",
"''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') # store = ''",
"screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name:",
"ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout:",
"is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into localstore all today",
"build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def",
"screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') # store =",
"rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows for i in",
"poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1]",
"section graph dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if",
"costs for pro, cat and datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost')",
"for item in r_ for i in item]):.2f}' return ar1 def storage(self): #app",
"- current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass into",
"kivymd.app import MDApp from Mdialog import GraphDialog \"\"\" set test window and input",
"class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows for i",
"localstore all costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\"",
"#todo: TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat'])",
"dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if item in",
"from kivy.properties import StringProperty from kivymd.app import MDApp from Mdialog import GraphDialog \"\"\"",
"tym roku') \"\"\" fetch and pass into local store all cost from last",
"i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into localstore all",
"list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0,",
"ScrollView: MDList: id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active:",
"from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\"",
"= f'{sum([i for item in r_ for i in item]):.2f}' return ar1 def",
"\"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self):",
"Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv",
"BoxLayout: id: view ScrollView: MDList: id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\")",
"#Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock",
"'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel'",
"import MDApp from Mdialog import GraphDialog \"\"\" set test window and input android",
"def update_store_cat_pro(self, *args): for i in args: rows = self.db.fetch_col(i) items = [i",
"\"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass into localstore all costs",
"self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE'",
"in r_ for i in item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app()",
"GraphDialog \"\"\" set test window and input android keyboard\"\"\" # from kivy.core.window import",
"kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>:",
"= \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def",
"in args: rows = self.db.fetch_col(i) items = [i for item in rows for",
"list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self):",
"\"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into localstore all costs from",
"'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category',",
"[r[i][1] for i in range(len(r))] #if r[i][0] != 0] cost = [r[i][0] for",
"'w tym tygodniu') \"\"\" fetch and pass into localstore all costs from -",
"\"\"\" fetch and pass into localstore all costs from - current month \"\"\"",
"store = '' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage()",
"Budget(MDApp): costs_sum = StringProperty('0') # store = '' def __init__(self, **kwargs): super().__init__(**kwargs) #",
"zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all",
"return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close()",
"self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args): for",
"fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for",
"def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i",
"range(len(r))] #if r[i][0] != 0] cost = [r[i][0] for i in range(len(r))] #if",
"r[i][0] != 0] cost = [r[i][0] for i in range(len(r))] #if r[i][0] !=",
"is not None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] =",
"Storage() in storage.py for ios device self.storage = Storage(self.user_data_dir) # self.storage = Storage('')",
"import MDBottomNavigation from kivy.clock import Clock from functools import partial import SecondScreen import",
"item) time = [r[i][1] for i in range(len(r))] #if r[i][0] != 0] cost",
"fetch and pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch",
"from class_mydb import Mydb from storage import Storage from kivy.properties import StringProperty from",
"= list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def",
"if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item)",
"pass into localstore all costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym",
"year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass into local store",
"\"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore from curent week \"\"\"",
"class_mydb import Mydb from storage import Storage from kivy.properties import StringProperty from kivymd.app",
"if i is not None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else:",
"storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir)",
"1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view()",
"\"\"\" def update_store_cat_pro(self, *args): for i in args: rows = self.db.fetch_col(i) items =",
"and pass into localstore all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc",
"in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time =",
"# init DICTstorage from class Storage() in storage.py for ios device self.storage =",
"FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width:",
"if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self):",
"\"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)]",
"StringProperty from kivymd.app import MDApp from Mdialog import GraphDialog \"\"\" set test window",
"item if i is not None]):.2f}' self.costs_sum = f'{(sum([i for item in rows",
"r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in range(len(r))] #if r[i][0]",
"curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass into localstore",
"year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\"",
"def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:',",
"self.db.fetch_col(i) items = [i for item in rows for i in item if",
"icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon:",
"\"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList: id: list MDScreen: Manager:",
"cat and datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i",
"= [r[i][1] for i in range(len(r))] #if r[i][0] != 0] cost = [r[i][0]",
"in range(len(r))] #if r[i][0] != 0] \"pass param as a graph attr\" GraphDialog(cost,",
"= self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in range(len(r))] #if r[i][0] !=",
"self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close()",
"print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE' \"\"\" section graph dialog",
"functools import partial import SecondScreen import FirstScreen import ThirdScreen from class_mydb import Mydb",
"spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id:",
"StringProperty('0') # store = '' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from",
"self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro,",
"last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into localstore all",
"\"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for item in r_",
"text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text:",
"and datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for",
"fetch_general_costs(self): \"\"\" fetch and pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj')",
"= text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else:",
"def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch",
"view ScrollView: MDList: id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\")",
"'w tym roku') \"\"\" fetch and pass into local store all cost from",
"= StringProperty('0') # store = '' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage",
"text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class",
"self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week,",
"localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass",
"from kivymd.app import MDApp from Mdialog import GraphDialog \"\"\" set test window and",
"from Mdialog import GraphDialog \"\"\" set test window and input android keyboard\"\"\" #",
"item if i is not None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items))",
"- current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass into",
"keyboard mode for ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from",
"on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db",
"self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all()",
"- last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into localstore",
"self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass into local store all cost",
"text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view()",
"'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass",
"pass into localstore all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym",
"def fetch_costs(self): \"\"\" all costs for pro, cat and datas source in mydb",
"import Clock from functools import partial import SecondScreen import FirstScreen import ThirdScreen from",
"\"\"\" fetch and pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym",
"return ar1 def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir",
"\"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList: id: list",
"? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for",
"all costs for pro, cat and datas source in mydb class\"\"\" rows =",
"localstore all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch",
"#selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1 name: 'screen1' text:",
"list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self):",
"partial import SecondScreen import FirstScreen import ThirdScreen from class_mydb import Mydb from storage",
"MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1",
"pass into localstore all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej')",
"\"\"\" set test window and input android keyboard\"\"\" # from kivy.core.window import Window",
"name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation):",
"#:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\"",
"graph dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if item",
"TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def",
"for item in rows for i in item if i is not None])):.2f}'",
"'miesiąc wcześniej') \"\"\" fetch and pass into localstore all costs from - current",
"Storage(self.user_data_dir) # self.storage = Storage('') local env self.store = self.storage.store self.db = Mydb(self.user_data_dir)",
"methods \"\"\" def update_store_cat_pro(self, *args): for i in args: rows = self.db.fetch_col(i) items",
"in range(len(r))] #if r[i][0] != 0] cost = [r[i][0] for i in range(len(r))]",
"today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore from curent",
"id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0,",
"and pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and",
"def fetch_general_costs(self): \"\"\" fetch and pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date,",
"args: rows = self.db.fetch_col(i) items = [i for item in rows for i",
"SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text:",
"cost = [r[i][0] for i in range(len(r))] #if r[i][0] != 0] \"pass param",
"return self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text): item",
"\"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_",
"from class Storage() in storage.py for ios device self.storage = Storage(self.user_data_dir) # self.storage",
"fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for item in r_ for",
"item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time",
"i in item if i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and",
"= self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i",
"screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon:",
"and pass into local store all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w",
"pass into local store all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim",
"item in rows for i in item if i is not None]):.2f}' self.costs_sum",
"not None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items))",
"kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from functools",
"FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen:",
"self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass into localstore all costs from",
"from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\"",
"f'{sum([i for item in r_ for i in item]):.2f}' return ar1 def storage(self):",
"self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def",
"device self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local env self.store = self.storage.store",
"#app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:',",
"self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in range(len(r))] #if r[i][0] != 0]",
"def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo:",
"into localstore all costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku')",
"localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore",
"- 1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r =",
"env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return",
"costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and",
"def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self,",
"keyboard\"\"\" # from kivy.core.window import Window # Window.size = (375, 667) # Window.softinput_mode",
"= \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def",
"from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass",
"env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env def",
"'' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage() in storage.py",
"self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self):",
"get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1 name: 'screen1'",
"self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs()",
"# Window.size = (375, 667) # Window.softinput_mode = \"resize\" kv = ''' #:import",
"rows = self.db.fetch_col(i) items = [i for item in rows for i in",
"self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local env self.store = self.storage.store self.db",
"icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum",
"if i is not None]):.2f}' self.costs_sum = f'{(sum([i for item in rows for",
"pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch",
"id: graph BoxLayout: id: view ScrollView: MDList: id: list MDScreen: Manager: id: manager",
"open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r =",
"db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs",
"in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows",
"in rows for i in item if i is not None])):.2f}' def fetch_general_costs(self):",
"storage import Storage from kivy.properties import StringProperty from kivymd.app import MDApp from Mdialog",
"= app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') #",
"from kivy.core.window import Window # Window.size = (375, 667) # Window.softinput_mode = \"resize\"",
"costs_sum = StringProperty('0') # store = '' def __init__(self, **kwargs): super().__init__(**kwargs) # init",
"f'{sum([i for item in rows for i in item if i is not",
"else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in range(len(r))] #if",
"self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs()",
"'STORE') # return self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self,",
"item in rows for i in item if i is not None])):.2f}' def",
"import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation",
"local store all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def",
"in rows for i in item if i is not None] if i",
"print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE' \"\"\"",
"kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from functools import partial import SecondScreen",
"= '' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage() in",
"all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch",
"local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\"",
"id: view ScrollView: MDList: id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background:",
"and pass into localstore all costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w",
"db methods \"\"\" def update_store_cat_pro(self, *args): for i in args: rows = self.db.fetch_col(i)",
"Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') # store = '' def __init__(self,",
"= list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def",
"pro, cat and datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] =",
"i is not None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro']",
"month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into localstore all costs",
"time = [r[i][1] for i in range(len(r))] #if r[i][0] != 0] cost =",
"Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from",
"and pass into localstore all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w",
"self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in",
"for item in rows for i in item if i is not None]",
"self.store['costs']['RAZEM'] = f'{sum([i for item in rows for i in item if i",
"graph BoxLayout: id: view ScrollView: MDList: id: list MDScreen: Manager: id: manager #panel_color:",
"import StringProperty from kivymd.app import MDApp from Mdialog import GraphDialog \"\"\" set test",
"# from kivy.core.window import Window # Window.size = (375, 667) # Window.softinput_mode =",
"= Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette",
"\"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self):",
"#from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation",
"items = [i for item in rows for i in item if i",
"miesiącu') \"\"\" fetch and pass into localstore all costs from - last month",
"Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette =",
"self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project',",
"source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in",
"for i in item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app() #ddir =",
"set keyboard mode for ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock')",
"rows for i in item if i is not None])):.2f}' def fetch_general_costs(self): \"\"\"",
"+ 'STORE') # return self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\" def",
"0, 0, 0, 1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash'",
"**kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage() in storage.py for ios device",
"import Mydb from storage import Storage from kivy.properties import StringProperty from kivymd.app import",
"kivy.clock import Clock from functools import partial import SecondScreen import FirstScreen import ThirdScreen",
"self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows for i in item if",
"all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f,",
"item in rows for i in item if i is not None] if",
"from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from",
"on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args):",
"roku') \"\"\" fetch and pass into local store all cost from last year",
"self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self):",
"\"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view",
"into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into",
"r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for",
"Mydb from storage import Storage from kivy.properties import StringProperty from kivymd.app import MDApp",
"last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch",
"fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self):",
"DICTstorage from class Storage() in storage.py for ios device self.storage = Storage(self.user_data_dir) #",
"0] cost = [r[i][0] for i in range(len(r))] #if r[i][0] != 0] \"pass",
"Storage from kivy.properties import StringProperty from kivymd.app import MDApp from Mdialog import GraphDialog",
"'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave:",
"i is not None]):.2f}' self.costs_sum = f'{(sum([i for item in rows for i",
"i in item if i is not None]):.2f}' self.costs_sum = f'{(sum([i for item",
"#:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\"",
"Storage('') local env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local",
"all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore from",
"size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView:",
"\"\"\" fetch and pass into local store all cost from last year \"\"\"",
"__init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage() in storage.py for ios",
"for ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import",
"= self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows for i in item",
"self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE' \"\"\" section graph",
"localstore all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\"",
"into localstore all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\"",
"'dzisiaj') \"\"\" fetch and pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w",
"'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') -",
"# set keyboard mode for ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode',",
"device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from",
"i in item if i is not None] if i == 'category': self.store['category']['cat']",
"self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\"",
"'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp):",
"None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into localstore all today costs \"\"\"",
"self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass into localstore all costs from",
"from kivy.clock import Clock from functools import partial import SecondScreen import FirstScreen import",
"tygodniu') \"\"\" fetch and pass into localstore all costs from - current month",
"manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1",
"\"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args): for i in args: rows",
"i in args: rows = self.db.fetch_col(i) items = [i for item in rows",
"= 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category',",
"rows for i in item if i is not None]):.2f}' self.costs_sum = f'{(sum([i",
"get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\"",
"tym tygodniu') \"\"\" fetch and pass into localstore all costs from - current",
"current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass into local",
"item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir =",
"Mydb('') local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue =",
"'w tym miesiącu') \"\"\" fetch and pass into localstore all costs from -",
"None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList:",
"icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view()",
"current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass into localstore",
"self.store['costs'][ar1] = f'{sum([i for item in r_ for i in item]):.2f}' return ar1",
"\"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout:",
"for i in args: rows = self.db.fetch_col(i) items = [i for item in",
"for i in item if i is not None]):.2f}' self.costs_sum = f'{(sum([i for",
"wcześniej') \"\"\" fetch and pass into localstore all costs from - current year",
"'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock",
"local env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env",
"self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch",
"MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir +",
"in item if i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass",
"import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from functools import",
"1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project',",
"datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item",
"update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero db ? self.fetch_costs()",
"set test window and input android keyboard\"\"\" # from kivy.core.window import Window #",
"#if r[i][0] != 0] \"pass param as a graph attr\" GraphDialog(cost, time, item).show_graph()",
"for ios device self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local env self.store",
"in rows for i in item if i is not None]):.2f}' self.costs_sum =",
"storage.py for ios device self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local env",
"in storage.py for ios device self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local",
"= f'{sum([i for item in rows for i in item if i is",
"from storage import Storage from kivy.properties import StringProperty from kivymd.app import MDApp from",
"def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero db ?",
"from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass into",
"r_ = f() self.store['costs'][ar1] = f'{sum([i for item in r_ for i in",
"MDList: id: list MDScreen: Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0,",
"in item if i is not None]):.2f}' self.costs_sum = f'{(sum([i for item in",
"= self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir +",
"# self.storage = Storage('') local env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db",
"text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r",
"name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name:",
"screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') # store",
"None] if i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def",
"#ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE')",
"\"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass into local store all",
"import ThirdScreen from class_mydb import Mydb from storage import Storage from kivy.properties import",
"height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList: id: list MDScreen:",
"def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r",
"pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass",
"ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for item in",
"from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and pass",
"ios device self.storage = Storage(self.user_data_dir) # self.storage = Storage('') local env self.store =",
"kivy.properties import StringProperty from kivymd.app import MDApp from Mdialog import GraphDialog \"\"\" set",
"f, ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for item",
"\"\"\" all costs for pro, cat and datas source in mydb class\"\"\" rows",
"# Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include",
"on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen:",
"self.storage = Storage('') local env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db =",
"i in item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir",
"#if r[i][0] != 0] cost = [r[i][0] for i in range(len(r))] #if r[i][0]",
"costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass",
"\"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv",
"'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum =",
"'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() '''",
"FirstScreen import ThirdScreen from class_mydb import Mydb from storage import Storage from kivy.properties",
"#panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1 name:",
"667) # Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv",
"self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ =",
"method\"\"\" r_ = f() self.store['costs'][ar1] = f'{sum([i for item in r_ for i",
"self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir",
"week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and pass into localstore all",
"store all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self,",
"kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y:",
"= [r[i][0] for i in range(len(r))] #if r[i][0] != 0] \"pass param as",
"update_store_cat_pro(self, *args): for i in args: rows = self.db.fetch_col(i) items = [i for",
"into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\" fetch and",
"else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs()",
"screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3'",
"+ 'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':')",
"fetch db methods \"\"\" def update_store_cat_pro(self, *args): for i in args: rows =",
"import SecondScreen import FirstScreen import ThirdScreen from class_mydb import Mydb from storage import",
"super().__init__(**kwargs) # init DICTstorage from class Storage() in storage.py for ios device self.storage",
"roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ = f() self.store['costs'][ar1] =",
"cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku') def fetch_items(self, f, ar1):",
"id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id:",
"self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods",
"update_all(self): #todo: TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category',",
"self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text): item =",
"ar1 def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with",
"self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro, cat and datas source",
"app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return",
"class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') # store = '' def",
"for i in range(len(r))] #if r[i][0] != 0] cost = [r[i][0] for i",
"name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings'",
"import FirstScreen import ThirdScreen from class_mydb import Mydb from storage import Storage from",
"'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2'",
"self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args): for i in args:",
"item = text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item)",
"kivy.core.window import Window # Window.size = (375, 667) # Window.softinput_mode = \"resize\" kv",
"0, 0, 1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave:",
"= f() self.store['costs'][ar1] = f'{sum([i for item in r_ for i in item]):.2f}'",
"i in range(len(r))] #if r[i][0] != 0] \"pass param as a graph attr\"",
"ios device #from kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder",
"i in range(len(r))] #if r[i][0] != 0] cost = [r[i][0] for i in",
"== 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro'])",
"input android keyboard\"\"\" # from kivy.core.window import Window # Window.size = (375, 667)",
"Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\"",
"pass class Budget(MDApp): costs_sum = StringProperty('0') # store = '' def __init__(self, **kwargs):",
"item) else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1] for i in range(len(r))]",
"self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero",
"'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view()",
"text): item = text[:(text.find(':') - 1)] if item in self.store['category']['cat']: r = self.db.fetch_cost_and_data('category',",
"\"\"\" fetch and pass into localstore all today costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\"",
"None]):.2f}' self.costs_sum = f'{(sum([i for item in rows for i in item if",
"self.costs_sum = f'{(sum([i for item in rows for i in item if i",
"self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat'])",
"self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro, cat and datas",
"\"\"\" def open_graph_dialog(self, text): item = text[:(text.find(':') - 1)] if item in self.store['category']['cat']:",
"orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id: graph",
"in item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app() #ddir = app.user_data_dir self.ddir",
"get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa'",
"def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args): for i",
"#self.db = Mydb('') local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\"",
"Clock from functools import partial import SecondScreen import FirstScreen import ThirdScreen from class_mydb",
"fetch and pass into localstore all costs from - current year \"\"\" self.fetch_items(self.db.all_year,",
"import Window # Window.size = (375, 667) # Window.softinput_mode = \"resize\" kv =",
"fetch and pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu')",
"rows for i in item if i is not None] if i ==",
"Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from functools import partial",
"android keyboard\"\"\" # from kivy.core.window import Window # Window.size = (375, 667) #",
"class Budget(MDApp): costs_sum = StringProperty('0') # store = '' def __init__(self, **kwargs): super().__init__(**kwargs)",
"item in r_ for i in item]):.2f}' return ar1 def storage(self): #app =",
"test window and input android keyboard\"\"\" # from kivy.core.window import Window # Window.size",
"= self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self): self.icon",
"and input android keyboard\"\"\" # from kivy.core.window import Window # Window.size = (375,",
"import GraphDialog \"\"\" set test window and input android keyboard\"\"\" # from kivy.core.window",
"f'{(sum([i for item in rows for i in item if i is not",
"Mdialog import GraphDialog \"\"\" set test window and input android keyboard\"\"\" # from",
"= Storage(self.user_data_dir) # self.storage = Storage('') local env self.store = self.storage.store self.db =",
"\"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass into localstore all costs",
"def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv)",
"fetch and pass into local store all cost from last year \"\"\" self.fetch_items(self.db.last_year,",
"import partial import SecondScreen import FirstScreen import ThirdScreen from class_mydb import Mydb from",
"MDApp from Mdialog import GraphDialog \"\"\" set test window and input android keyboard\"\"\"",
"init DICTstorage from class Storage() in storage.py for ios device self.storage = Storage(self.user_data_dir)",
"self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from",
"= ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation:",
"Window.size = (375, 667) # Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex",
"self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST: fetch from zero db",
"r[i][0] != 0] \"pass param as a graph attr\" GraphDialog(cost, time, item).show_graph() Budget().run()",
"and pass into localstore from curent week \"\"\" self.fetch_items(self.db.fetch_week, 'w tym tygodniu') \"\"\"",
"ThirdScreen: name: 'screen3' text: 'Ustawienia' icon: 'table-settings' on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class",
"for i in item if i is not None] if i == 'category':",
"width: \"500dp\" height: \"300dp\" BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList: id:",
"self.store['category']['cat']: r = self.db.fetch_cost_and_data('category', item) else: r = self.db.fetch_cost_and_data('project', item) time = [r[i][1]",
"def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class Storage() in storage.py for",
"self.fetch_general_costs() self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro, cat",
"self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self): self.icon =",
"in item if i is not None] if i == 'category': self.store['category']['cat'] =",
"app:', self.ddir) print('ddir:', self.user_data_dir + 'STORE') # return self.user_data_dir + 'STORE' \"\"\" section",
"MDBottomNavigation from kivy.clock import Clock from functools import partial import SecondScreen import FirstScreen",
"into localstore all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu')",
"# return self.user_data_dir + 'STORE' \"\"\" section graph dialog \"\"\" def open_graph_dialog(self, text):",
"for item in rows for i in item if i is not None]):.2f}'",
"\"\"\" fetch and pass into localstore all costs from - current year \"\"\"",
"i == 'category': self.store['category']['cat'] = list(dict.fromkeys(items)) else: self.store['project']['pro'] = list(dict.fromkeys(items)) def update_procat_costs(self): self.db.procat('project',",
"!= 0] cost = [r[i][0] for i in range(len(r))] #if r[i][0] != 0]",
"is not None]):.2f}' self.costs_sum = f'{(sum([i for item in rows for i in",
"[i for item in rows for i in item if i is not",
"import Storage from kivy.properties import StringProperty from kivymd.app import MDApp from Mdialog import",
"for i in range(len(r))] #if r[i][0] != 0] \"pass param as a graph",
"*args): for i in args: rows = self.db.fetch_col(i) items = [i for item",
"self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro, cat and",
"SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height:",
"'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue = \"500\" return Builder.load_string(kv) def on_start(self): self.update_store_cat_pro('category', 'project')",
"for pro, cat and datas source in mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM']",
"f() self.store['costs'][ar1] = f'{sum([i for item in r_ for i in item]):.2f}' return",
"mydb class\"\"\" rows = self.db.fetch_col(col='cost') self.store['costs']['RAZEM'] = f'{sum([i for item in rows for",
"not None]):.2f}' self.costs_sum = f'{(sum([i for item in rows for i in item",
"costs \"\"\" self.fetch_items(self.db.fetch_by_date, 'dzisiaj') \"\"\" fetch and pass into localstore from curent week",
"Manager: id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen:",
"= [i for item in rows for i in item if i is",
"'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type'",
"self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into localstore all costs from -",
"kivy.config import Config #Config.set('kivy', 'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import",
"''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\"",
"costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch and",
"from functools import partial import SecondScreen import FirstScreen import ThirdScreen from class_mydb import",
"<Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None width: \"500dp\" height: \"300dp\" BoxLayout: id:",
"0, 1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view()",
"tym miesiącu') \"\"\" fetch and pass into localstore all costs from - last",
"into local store all cost from last year \"\"\" self.fetch_items(self.db.last_year, 'w poprzednim roku')",
"from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import Clock from functools import partial import",
"self.store['category']['cat']) def fetch_costs(self): \"\"\" all costs for pro, cat and datas source in",
"update_procat_costs(self): self.db.procat('project', self.store['project']['pro']) self.db.procat('category', self.store['category']['cat']) def update_gen_cost(self): self.fetch_costs() self.fetch_general_costs() def update_all(self): #todo: TEST:",
"#:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing: \"12dp\" size_hint_y: None",
"screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0') #",
"ThirdScreen from class_mydb import Mydb from storage import Storage from kivy.properties import StringProperty",
"= MDApp.get_running_app() #ddir = app.user_data_dir self.ddir = self.user_data_dir print('with app:', self.ddir) print('ddir:', self.user_data_dir",
"\"\"\" fetch and pass into localstore all costs from - last month \"\"\"",
"SecondScreen import FirstScreen import ThirdScreen from class_mydb import Mydb from storage import Storage",
"fetch_costs(self): \"\"\" all costs for pro, cat and datas source in mydb class\"\"\"",
"(375, 667) # Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include",
"= self.db.fetch_col(i) items = [i for item in rows for i in item",
"= \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include",
"= Storage('') local env self.store = self.storage.store self.db = Mydb(self.user_data_dir) #self.db = Mydb('')",
"not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into localstore all today costs",
"from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and pass into",
"Window # Window.size = (375, 667) # Window.softinput_mode = \"resize\" kv = '''",
"range(len(r))] #if r[i][0] != 0] \"pass param as a graph attr\" GraphDialog(cost, time,",
"class Storage() in storage.py for ios device self.storage = Storage(self.user_data_dir) # self.storage =",
"= Mydb('') local env def build(self): self.icon = 'logo.png' self.theme_cls.primary_palette = \"Orange\" self.theme_cls.primary_hue",
"on_leave: screen1.ids.catpro_view.populate_view() screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() ''' class Manager(MDBottomNavigation): pass class Budget(MDApp): costs_sum = StringProperty('0')",
"fetch and pass into localstore all costs from - current month \"\"\" self.fetch_items(self.db.fetch_current_month,",
"# store = '' def __init__(self, **kwargs): super().__init__(**kwargs) # init DICTstorage from class",
"'project') self.update_all() def on_pause(self): self.db.conn.close() def on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\"",
"r_ for i in item]):.2f}' return ar1 def storage(self): #app = MDApp.get_running_app() #ddir",
"BoxLayout: id: graph BoxLayout: id: view ScrollView: MDList: id: list MDScreen: Manager: id:",
"self.db = Mydb(self.user_data_dir) #self.db = Mydb('') local env def build(self): self.icon = 'logo.png'",
"#text_color_active: 0, 0, 0, 1 FirstScreen: id: screen1 name: 'screen1' text: 'Kasa' icon:",
"id: screen2 name: 'screen2' text: 'Portfel' icon: 'format-list-bulleted-type' ThirdScreen: name: 'screen3' text: 'Ustawienia'",
"def update_all(self): #todo: TEST: fetch from zero db ? self.fetch_costs() self.fetch_general_costs() self.db.procat('project', self.store['project']['pro'])",
"if i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into localstore",
"month \"\"\" self.fetch_items(self.db.fetch_current_month, 'w tym miesiącu') \"\"\" fetch and pass into localstore all",
"item if i is not None])):.2f}' def fetch_general_costs(self): \"\"\" fetch and pass into",
"'keyboard_mode', 'dock') from kivy.lang.builder import Builder from kivymd.uix.bottomnavigation import MDBottomNavigation from kivy.clock import",
"all costs from - current year \"\"\" self.fetch_items(self.db.all_year, 'w tym roku') \"\"\" fetch",
"#:import get_color_from_hex kivy.utils.get_color_from_hex #:include FirstScreen.kv #:include SecondScreen.kv #:include ThirdScreen.kv <Content>: orientation: \"vertical\" spacing:",
"window and input android keyboard\"\"\" # from kivy.core.window import Window # Window.size =",
"id: manager #panel_color: get_color_from_hex(\"#eeeaea\") #selected_color_background: get_color_from_hex(\"#97ecf8\") #text_color_active: 0, 0, 0, 1 FirstScreen: id:",
"on_stop(self): self.db.conn.close() \"\"\" fetch db methods \"\"\" def update_store_cat_pro(self, *args): for i in",
"= f'{(sum([i for item in rows for i in item if i is",
"all costs from - last month \"\"\" self.fetch_items(self.db.fetch_last_mont, 'miesiąc wcześniej') \"\"\" fetch and",
"= (375, 667) # Window.softinput_mode = \"resize\" kv = ''' #:import get_color_from_hex kivy.utils.get_color_from_hex",
"[r[i][0] for i in range(len(r))] #if r[i][0] != 0] \"pass param as a",
"screen1 name: 'screen1' text: 'Kasa' icon: 'account-cash' on_leave: screen2.ids.general_view.populate_view() screen2.ids.costs_view.populate_view() SecondScreen: id: screen2",
"'w poprzednim roku') def fetch_items(self, f, ar1): \"\"\" fetch method\"\"\" r_ = f()"
] |
[
"unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def",
"self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res,",
"def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div",
"test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res =",
"save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res",
"= self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def",
"self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected =",
"('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True)",
"class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html(",
"bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div",
"self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self):",
"def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div",
"save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res =",
"test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected",
"def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res",
"self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"",
"expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar",
"{}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res",
"self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def",
"def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>')",
"self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res",
"self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">'",
"expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html(",
"-*- coding: utf-8 -*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import",
"res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res,",
"save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '')",
"def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected =",
"test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res,",
"def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>')",
"#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res",
"bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div",
"class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html(",
"self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res,",
"{}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def",
"= ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True)",
"save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True)",
"test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div",
"id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam",
"self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar > section#bam section.quux",
"def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res",
"class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True)",
"('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True)",
"self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res",
"import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res =",
"class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected =",
"= ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar",
"('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected",
"id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected",
"save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res =",
"<filename>tests/test_htmlreflector.py # -*- coding: utf-8 -*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from",
"id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar > section#bam",
"def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div",
"res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover",
"'#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo",
"expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res =",
"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected =",
"def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res,",
"> #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self):",
"res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">'",
"def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res,",
"test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected)",
"self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res,",
"> section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>')",
"save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True)",
"self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div",
"def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res,",
"#bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim",
"expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res =",
"= ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html(",
"test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>')",
".bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def",
"self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected =",
"class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div",
"self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res =",
"= self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div",
"id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res",
"def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res,",
"self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"",
"expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo >",
"save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim",
"= self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>')",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res =",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self):",
"= ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html(",
"self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div",
"self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div",
"res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def",
"def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res =",
"-*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase):",
"html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo",
"> .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">'",
"self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res",
"test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected)",
"= ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True)",
"= self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>')",
"res = self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected =",
"id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar >",
"expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>')",
"= self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html(",
"expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>')",
"id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected =",
"res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div",
"res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def",
"expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res =",
"{} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar",
"save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo",
"expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html(",
"expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res",
"test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string(",
"def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>')",
"class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected",
"# -*- coding: utf-8 -*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector",
"self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res",
"self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected",
"('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected",
"('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html(",
"self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def",
"res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def",
"test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div",
"= self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section",
"{}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html(",
"code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res",
"expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar",
"expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>')",
"id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div",
"id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html(",
"class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected =",
"test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res,",
"self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo",
"expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo",
"{}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res,",
"test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res =",
"class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self):",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res",
"= \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self):",
"= ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res =",
"> .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>')",
"import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector()",
"test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def",
"('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html(",
"'<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def",
"__author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def",
"self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>')",
"= ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar",
"= self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html(",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res =",
"= self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {}",
"from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self):",
"= self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self):",
"'<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self):",
"= self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self): res",
"section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected)",
"self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar",
"class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo",
"'<div id=\"bar\"></div>') def test_nested_id(self): res = self.ref.process_string('#foo #bar #bim {}').extract().make_html( save_as_string=True) expected =",
"class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div",
"{}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res =",
"#bar #bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected)",
"self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\"",
"('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string(",
"test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected)",
"def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True)",
"= self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self):",
"id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim",
"#bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def",
"res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"bar\"></div>') def test_nested_id(self):",
"= ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo >",
"(<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref =",
"{}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res,",
"self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>')",
"class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected =",
"save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar",
"save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div",
"'.foo > .bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section",
"id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_class(self): res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected",
"setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div",
"res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo",
"expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html(",
"id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True)",
"html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self):",
"utf-8 -*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class",
"self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True)",
"'.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section",
"\"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector class SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref",
"class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self): res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div",
"save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar",
"= html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def",
"expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div",
"save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string(",
"'</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected",
"test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected)",
"'</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div",
"id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True) expected =",
"expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected",
"id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True)",
"SelectorOutputTestCase(unittest.TestCase): def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True)",
"res = self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected)",
"self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self):",
"expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def test_compound_id_multiclass(self): res = self.ref.process_string('#foo.bar.bim",
"expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>')",
"section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res,",
"= ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html( save_as_string=True)",
"save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self):",
"'') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div",
"{}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res =",
"= self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected)",
"test_nested_class(self): res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div",
"coding: utf-8 -*- __author__ = \"\"\"<NAME> (<EMAIL>)\"\"\" import unittest from code_reflector import html_reflector",
"def setUp(self): self.ref = html_reflector.HTMLReflector() def test_single_class(self): res = self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res,",
"= self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"bar\" class=\"foo\"></div>') self.assertEqual(res, expected) def test_compound_multiclass(self):",
"res = self.ref.process_string('#foo.bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def",
"self.ref.process_string('#foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div id=\"foo\"></div>') def test_pseudoselector(self): res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True)",
"save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res",
"res = self.ref.process_string('#foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\" class=\"bar bim\"></div>') self.assertEqual(res, expected)",
"expected = ('<div id=\"foo\" class=\"bar\"></div>') self.assertEqual(res, expected) def test_nested_simple_class(self): res = self.ref.process_string('.foo>.bar {}').extract().make_html(",
"self.ref.process_string('.foo {}').extract().make_html( save_as_string=True) self.assertEqual(res, '<div class=\"foo\"></div>') def test_single_id(self): res = self.ref.process_string('#foo {}').extract().make_html( save_as_string=True)",
"class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo >",
"{}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self):",
".bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected)",
"res = self.ref.process_string('.foo .bar .bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><div class=\"bim\">'",
"= self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected = ('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id_spaces(self):",
"('<div class=\"foo\"><div class=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_simple_id(self): res = self.ref.process_string('#foo>#bar {}').extract().make_html( save_as_string=True) expected",
"('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo .bar",
"= ('<div id=\"foo\"><div id=\"bar\"><div id=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_nested_class(self): res = self.ref.process_string('.foo",
"res = self.ref.process_string('#foo:hover {}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover",
"expected) def test_nested_simple_id_spaces(self): res = self.ref.process_string('#foo > #bar {}').extract().make_html( save_as_string=True) expected = ('<div",
"class=\"bar\"><div class=\"bim\">' '</div></div></div>') self.assertEqual(res, expected) def test_compound_class_id(self): res = self.ref.process_string('.foo#bar {}').extract().make_html( save_as_string=True) expected",
"= self.ref.process_string('.foo.bar.bim {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo bar bim\"></div>') self.assertEqual(res, expected) def",
".bar>section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section class=\"quux\"></section></section></div></div>') self.assertEqual(res,",
"{}').extract().make_html( save_as_string=True) self.assertEqual(res, '') def test_pseudoselector_mixed(self): res = self.ref.process_string( '#foo:hover {} #bar {}').extract().make_html(",
"'<section class=\"quux\"></section></section></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag_mixedspaces(self): res = self.ref.process_string( '.foo > .bar>section#bam section.quux",
".bar > section#bam section.quux {}').extract().make_html( save_as_string=True) expected = ('<div class=\"foo\"><div class=\"bar\"><section id=\"bam\">' '<section",
"('<div id=\"foo\"><div id=\"bar\"></div></div>') self.assertEqual(res, expected) def test_nested_multiid_multiclass_tag(self): res = self.ref.process_string( '.foo > .bar"
] |
[
"{}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded",
"indices to training data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid",
"def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir,",
"cropped indices to training data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal",
"if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from",
"normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training",
"Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in",
"= Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd'",
"problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir:",
"n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader =",
"jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) #",
"else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add cropped indices to",
"train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped",
"if n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets =",
"else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\")",
"DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir,",
"return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir,",
"load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid + n_train]",
"preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir,",
"jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset",
"valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\")",
"the excluded data to the training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd",
"jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add the excluded",
"'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon",
"\"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf)",
"n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid]",
"in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename =",
"import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized",
"batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset =",
"logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset,",
"set and add the excluded data to the training set if 'w-vs-qcd' in",
"crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add cropped indices",
"= load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def",
"the data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already",
"jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add",
"train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if",
"valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader",
"from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = {",
"from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training data logging.warning(\"\\tfinal",
"in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import",
"def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False)",
"= DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs):",
"(quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd'",
"= load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop",
"= data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid + n_train] if n_train >",
"problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir",
"data logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset,",
"size = %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size,",
"load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation",
"data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir,",
"import numpy as np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon =",
"filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set",
"load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir,",
"% len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset",
"'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename)",
"{} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets",
"crop validation set and add the excluded data to the training set if",
"logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset,",
"batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset,",
"n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return",
"filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in",
"valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd",
"cropped indices to training data logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return",
"preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess)",
"# add cropped indices to training data logging.warning(\"\\tfinal train size = %d\" %",
"load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd +",
"+ n_train] if n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) #",
"dataset.transform(train_dataset.tf) # crop validation set and add the excluded data to the training",
".io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'),",
"n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader = DataLoader(dataset, batch_size,",
"dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader = DataLoader(dataset, batch_size, leaves=leaves) return test_data_loader",
"problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir:",
"= jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add the",
"batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset,",
"n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename),",
"os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess)",
"= 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'),",
"= os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if",
"dataset, _ = crop_dataset(dataset) # add cropped indices to training data logging.warning(\"\\tfinal test",
"in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import",
"train_jets = jets[n_valid:n_valid + n_train] if n_train > 0 else jets[n_valid:] train_dataset =",
"os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed)",
"#from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw')",
"saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets =",
"#preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed",
"def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader",
"import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as np from .io import",
"import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized",
"total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset]",
"intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets =",
"elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from",
"Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in",
"valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000,",
"train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add",
"raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir",
"import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir =",
"import logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as",
"%d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset",
"crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!')",
"load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon'",
"import pickle import logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import",
"# crop validation set and add the excluded data to the training set",
"('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd",
"preprocess) jets = jets[:n_test] dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and",
"problem = data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid + n_train] if n_train",
"not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it",
"if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename)",
"os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets",
"if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved",
"DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins',",
"crop_dataset(dataset) # add cropped indices to training data logging.warning(\"\\tfinal test size = %d\"",
"in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset =",
"'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import",
"jets[n_valid:n_valid + n_train] if n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem)",
"jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem)",
"def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif",
"DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as np from .io import load_jets_from_pickle",
"-1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test",
"= crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf)",
"crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) #",
"training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir)",
"{ 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') }",
"pickle import logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy",
"test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir,",
"return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir",
"= os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not",
"'quark-gluon' in data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module",
"data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset",
"dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess)",
"training data logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir,",
"'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'),",
"os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not",
"} def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess",
"ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir =",
".w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise",
"% len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ =",
"= DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets",
"import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir =",
"train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1,",
"training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in",
"to the training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif",
"leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size,",
"size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return",
"train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset))",
"'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein':",
"logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets =",
"= os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename",
"data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir,",
"valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif",
"training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir)",
"do_preprocessing=False): if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir:",
"filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem =",
"train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test,",
"dataset = Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add the excluded data",
"add the excluded data to the training set if 'w-vs-qcd' in data_dir: from",
"= crop_dataset(dataset) # add cropped indices to training data logging.warning(\"\\tfinal test size =",
"data to the training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset",
"= Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add the excluded data to",
"from src.jets.data_ops.Dataset import Dataset import numpy as np from .io import load_jets_from_pickle w_vs_qcd",
"os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the",
"+ '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename,",
"preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return",
"os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed))",
"leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test,",
"subproblem = filename train_jets = jets[n_valid:n_valid + n_train] if n_train > 0 else",
"not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed",
"filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename)",
"valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size,",
"train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves)",
"= training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir,",
"jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir =",
"os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir,",
"training data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size =",
"to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully",
"logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound",
"add cropped indices to training data logging.warning(\"\\tfinal test size = %d\" % len(dataset))",
"validation set and add the excluded data to the training set if 'w-vs-qcd'",
"= { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11')",
"%d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset,",
"test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test]",
"jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid",
"training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training data logging.warning(\"\\tfinal train",
"_ = crop_dataset(dataset) # add cropped indices to training data logging.warning(\"\\tfinal test size",
"leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader = DataLoader(dataset, batch_size, leaves=leaves) return",
"= jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import",
"= filename train_jets = jets[n_valid:n_valid + n_train] if n_train > 0 else jets[n_valid:]",
"data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset)",
"= \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset = Dataset(jets)",
"= Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon'",
"n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves)",
"= %d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset,",
".quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add",
"get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader =",
"return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset,",
"## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices",
"ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add cropped indices to training data",
"27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\")",
"filename) logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {}",
"in data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import",
"= DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1]",
"to training data logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return dataset def",
"= 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp':",
"len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir,",
".quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle()",
"data_dir!') dataset, _ = crop_dataset(dataset) # add cropped indices to training data logging.warning(\"\\tfinal",
"dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset,",
"'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or",
".w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess else: raise",
"train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training data logging.warning(\"\\tfinal train size =",
"if 'w-vs-qcd' in data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from",
"os import pickle import logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset",
"#'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir: from",
"and add the excluded data to the training set if 'w-vs-qcd' in data_dir:",
"(quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in data_dir:",
"False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename",
"data_dir: from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess",
"filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir,",
"len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir,",
"= load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid +",
"set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training data logging.warning(\"\\tfinal train size",
"import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ##",
"DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset",
"or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data",
"cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform()",
"in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ =",
"logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train,",
"dataset, n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets",
"preprocess) problem = data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid + n_train] if",
"len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset =",
"'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _",
".quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir",
"= %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return train_dataset,",
"filename train_jets = jets[n_valid:n_valid + n_train] if n_train > 0 else jets[n_valid:] train_dataset",
"and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in",
"transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to training data",
"logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as np",
"def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train,",
"get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid,",
"= %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs):",
"and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets",
"logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" %",
"logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed)) else:",
"dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading",
"train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir",
"data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem =",
"crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed')",
"import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add cropped",
"from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as np from",
"DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets =",
"jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir, filename",
"data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\"",
"src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import Dataset import numpy as np from .io",
"'/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False):",
"dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename",
"data_dir.split('/')[-1] subproblem = filename train_jets = jets[n_valid:n_valid + n_train] if n_train > 0",
"the training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon'",
"numpy as np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon'",
"to training data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset)) logging.warning(\"\\tfinal valid size",
"filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset =",
"already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets)))",
"0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset =",
"logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and",
"as np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS",
"elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset,",
"w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'),",
"else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed')",
"os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it to",
"preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing:",
"elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset,",
"raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if",
"n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename =",
"at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {}",
"n_train, n_valid, batch_size, leaves=None,preprocess=None,**kwargs): train_dataset, valid_dataset = training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader",
"# valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets, problem=problem,subproblem=subproblem) if 'w-vs-qcd' in data_dir: from",
"Dataset import numpy as np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon",
"intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename =",
"data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed))",
"'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if 'w-vs-qcd' in",
"'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def",
"jets = load_jets_from_pickle(path_to_preprocessed) logging.warning(\"\\tSuccessfully loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets",
"preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data",
"preprocessed_dir, filename) logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at",
"set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir:",
"leaves=leaves) return train_data_loader, valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir,",
"intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem",
"train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader",
"return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset,",
"% len(train_dataset)) logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset def",
"# add cropped indices to training data logging.warning(\"\\tfinal test size = %d\" %",
"batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader = DataLoader(dataset, batch_size, leaves=leaves)",
"indices to training data logging.warning(\"\\tfinal test size = %d\" % len(dataset)) return dataset",
"np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS =",
"data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess,",
"preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!')",
"n_train] if n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets",
"= os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir, 'preprocessed') path_to_preprocessed =",
"preprocess): train_dataset, _ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset]",
"quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb':",
"excluded data to the training set if 'w-vs-qcd' in data_dir: from .w_vs_qcd import",
"dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size,",
"do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir, preprocessed_dir, filename) logging.warning(\"Preprocessed the data and",
"'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir, filename, do_preprocessing=False): if",
"_ = training_and_validation_dataset(data_dir, dataset, -1, 27000, False) intermediate_dir, filename = DATASETS[dataset] data_dir =",
"DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets = load_jets(data_dir,\"{}-train.pickle\".format(filename), preprocess) problem = data_dir.split('/')[-1] subproblem",
"from .quark_gluon import preprocess else: raise ValueError('Unrecognized data_dir!') #from problem_module import preprocess, crop_dataset",
"valid_data_loader def get_test_data_loader(data_dir, dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess)",
"it to {}\".format(path_to_preprocessed)) else: logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed)) jets = load_jets_from_pickle(path_to_preprocessed)",
"> 0 else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset",
"preprocess, crop_dataset #preprocessed_dir = os.path.join(data_dir, 'preprocessed') raw_data_dir = os.path.join(data_dir, 'raw') preprocessed_dir = os.path.join(data_dir,",
"'w-vs-qcd' in data_dir: from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon",
"preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader,",
"loaded data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train,",
"logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess):",
"= training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader =",
"'wp':(w_vs_qcd + '/pileup','pileup'), 'pp': (quark_gluon,'pp'), 'pbpb': (quark_gluon,'pbpb'), #'protein': ('proteins', 'casp11') } def load_jets(data_dir,",
"else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing",
"data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset)",
"raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) # add cropped indices to training",
"import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd' quark_gluon = 'quark-gluon' DATASETS = { 'w':(w_vs_qcd,'antikt-kt'), 'wp':(w_vs_qcd",
"from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset)",
"= DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset, batch_size, leaves=leaves) return train_data_loader, valid_data_loader def",
"= jets[n_valid:n_valid + n_train] if n_train > 0 else jets[n_valid:] train_dataset = Dataset(train_jets,",
"%d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess): train_dataset, _",
"raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform",
"import os import pickle import logging from src.jets.data_ops.DataLoader import DataLoader from src.jets.data_ops.Dataset import",
"add cropped indices to training data logging.warning(\"\\tfinal train size = %d\" % len(train_dataset))",
"intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets",
"logging.warning(\"Building normalizing transform from training set...\") train_dataset.transform() valid_dataset.transform(train_dataset.tf) # add cropped indices to",
"{} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess): intermediate_dir,",
"src.jets.data_ops.Dataset import Dataset import numpy as np from .io import load_jets_from_pickle w_vs_qcd =",
"from .w_vs_qcd import crop_dataset elif 'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else:",
"from .w_vs_qcd import preprocess elif 'quark-gluon' in data_dir: from .quark_gluon import preprocess else:",
"os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\") preprocess_fn(raw_data_dir,",
"n_train, n_valid, preprocess): intermediate_dir, filename = DATASETS[dataset] data_dir = os.path.join(data_dir, intermediate_dir) jets =",
"'quark-gluon' in data_dir: from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset",
"data\") logging.warning(\"\\tFound {} jets in total\".format(len(jets))) return jets def training_and_validation_dataset(data_dir, dataset, n_train, n_valid,",
"valid_dataset.transform(train_dataset.tf) # add cropped indices to training data logging.warning(\"\\tfinal train size = %d\"",
"from .quark_gluon import crop_dataset else: raise ValueError('Unrecognized data_dir!') dataset, _ = crop_dataset(dataset) #",
"else jets[n_valid:] train_dataset = Dataset(train_jets, problem=problem,subproblem=subproblem) # valid_jets = jets[:n_valid] valid_dataset = Dataset(valid_jets,",
"ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from",
"training_and_validation_dataset(data_dir, dataset, n_train, n_valid, preprocess) train_data_loader = DataLoader(train_dataset, batch_size, leaves=leaves) valid_data_loader = DataLoader(valid_dataset,",
"= os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir) logging.warning(\"Preprocessing...\")",
"crop_dataset else: raise ValueError('Unrecognized data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building",
"= os.path.join(data_dir, intermediate_dir) logging.warning(\"Loading test data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename,",
"data_dir!') valid_dataset, cropped_dataset = crop_dataset(valid_dataset) train_dataset.extend(cropped_dataset) train_dataset.shuffle() ## logging.warning(\"Building normalizing transform from training",
"valid size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test,",
"dataset, n_test, batch_size, leaves=None,preprocess=None,**kwargs): dataset = test_dataset(data_dir, dataset, n_test, preprocess) test_data_loader = DataLoader(dataset,",
"path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir): os.makedirs(preprocessed_dir)",
"size = %d\" % len(valid_dataset)) return train_dataset, valid_dataset def test_dataset(data_dir, dataset, n_test, preprocess):",
"Dataset(jets) dataset.transform(train_dataset.tf) # crop validation set and add the excluded data to the",
"'preprocessed') path_to_preprocessed = os.path.join(preprocessed_dir, filename) if not os.path.exists(path_to_preprocessed) or do_preprocessing: if not os.path.exists(preprocessed_dir):",
"data...\") filename = \"{}-test.pickle\".format(filename) jets = load_jets(data_dir, filename, preprocess) jets = jets[:n_test] dataset",
"import Dataset import numpy as np from .io import load_jets_from_pickle w_vs_qcd = 'w-vs-qcd'",
"test size = %d\" % len(dataset)) return dataset def get_train_data_loader(data_dir, dataset, n_train, n_valid,"
] |
[
"= response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded = True except: print(\"download",
"parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded",
"for i in range(n - 1): dl_dir = dl_dir + parts[i] + '/'",
"path = os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for f in subfile:",
"itr = re.finditer(pat, data) for match in itr: pre = match.group(1) if not",
"-*- coding:utf-8 -*- import os, sys, re, urllib2 def download(path, ext): path =",
"for match in itr: pre = match.group(1) if not pre: pre = 'https:'",
"match.group(2) parts = url.split('/') n = len(parts) filename = parts[n - 1] dl_dir",
"' + pre + '//' + url) print('download to: ' + dl_file) response",
"+ pre + '//' + url) else: downloaded = True if downloaded: if",
"def download(path, ext): path = os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for",
"dl_file = dl_dir + filename downloaded = False if not os.path.exists(dl_file): try: print('download",
"try: print('download from: ' + pre + '//' + url) print('download to: '",
"re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found: f.seek(0) f.truncate() f.write(data) if __name__",
"if re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True",
"= os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for f in subfile: subf",
"r'=\"/dl/\\2\"', data) found = True if found: f.seek(0) f.truncate() f.write(data) if __name__ ==",
"True if downloaded: if re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data)",
"re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True if",
"i in range(n - 1): dl_dir = dl_dir + parts[i] + '/' if",
"+ filename downloaded = False if not os.path.exists(dl_file): try: print('download from: ' +",
"ext) def fix_file(path): with open(path, 'r+') as f: data = f.read() found =",
"print('download to: ' + dl_file) response = urllib2.urlopen(pre + '//' + url) html",
"match.group(1) if not pre: pre = 'https:' url = match.group(2) parts = url.split('/')",
"subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path, 'r+') as f:",
"<filename>download.py #!/usr/env/bin python # -*- coding:utf-8 -*- import os, sys, re, urllib2 def",
"None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found: f.seek(0) f.truncate()",
"for f in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f",
"# -*- coding:utf-8 -*- import os, sys, re, urllib2 def download(path, ext): path",
"!= None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found: f.seek(0)",
"from: ' + pre + '//' + url) print('download to: ' + dl_file)",
"'https:' url = match.group(2) parts = url.split('/') n = len(parts) filename = parts[n",
"data = f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data)",
"+ url) else: downloaded = True if downloaded: if re.search(pat, data) != None:",
"+ '//' + url) print('download to: ' + dl_file) response = urllib2.urlopen(pre +",
"(dirname, subdir, subfile) in os.walk(path): for f in subfile: subf = os.path.join(dirname, f)",
"pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in itr: pre =",
"if found: f.seek(0) f.truncate() f.write(data) if __name__ == '__main__': download('./themes', '.ejs') download('./src/v2', '.md')",
"download(subf, ext) def fix_file(path): with open(path, 'r+') as f: data = f.read() found",
"subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in subdir: subf =",
"os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded = False if not os.path.exists(dl_file): try:",
"os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in subdir: subf = os.path.join(dirname, f)",
"dl_dir + filename downloaded = False if not os.path.exists(dl_file): try: print('download from: '",
"- 1): dl_dir = dl_dir + parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir)",
"= dl_dir + filename downloaded = False if not os.path.exists(dl_file): try: print('download from:",
"= True if found: f.seek(0) f.truncate() f.write(data) if __name__ == '__main__': download('./themes', '.ejs')",
"in range(n - 1): dl_dir = dl_dir + parts[i] + '/' if not",
"url) else: downloaded = True if downloaded: if re.search(pat, data) != None: data",
"dl_dir + parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir +",
"+ dl_file) response = urllib2.urlopen(pre + '//' + url) html = response.read() with",
"'dl/' for i in range(n - 1): dl_dir = dl_dir + parts[i] +",
"html = response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded = True except:",
"\" + pre + '//' + url) else: downloaded = True if downloaded:",
"subdir: subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path, 'r+') as",
"dl_dir = dl_dir + parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file =",
"= re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found: f.seek(0) f.truncate() f.write(data) if",
"len(parts) filename = parts[n - 1] dl_dir = 'dl/' for i in range(n",
"- 1] dl_dir = 'dl/' for i in range(n - 1): dl_dir =",
"as df: df.write(html) downloaded = True except: print(\"download failed: \" + pre +",
"found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in",
"subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in subdir: subf",
"if not os.path.exists(dl_file): try: print('download from: ' + pre + '//' + url)",
"filename downloaded = False if not os.path.exists(dl_file): try: print('download from: ' + pre",
"not pre: pre = 'https:' url = match.group(2) parts = url.split('/') n =",
"open(path, 'r+') as f: data = f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"'",
"re.finditer(pat, data) for match in itr: pre = match.group(1) if not pre: pre",
"if not pre: pre = 'https:' url = match.group(2) parts = url.split('/') n",
"url.split('/') n = len(parts) filename = parts[n - 1] dl_dir = 'dl/' for",
"n = len(parts) filename = parts[n - 1] dl_dir = 'dl/' for i",
"+ '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded =",
"with open(dl_file, 'w+') as df: df.write(html) downloaded = True except: print(\"download failed: \"",
"fix_file(path): with open(path, 'r+') as f: data = f.read() found = False pat",
"1] dl_dir = 'dl/' for i in range(n - 1): dl_dir = dl_dir",
"= urllib2.urlopen(pre + '//' + url) html = response.read() with open(dl_file, 'w+') as",
"df.write(html) downloaded = True except: print(\"download failed: \" + pre + '//' +",
"found = True if found: f.seek(0) f.truncate() f.write(data) if __name__ == '__main__': download('./themes',",
"download(path, ext): path = os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for f",
"parts = url.split('/') n = len(parts) filename = parts[n - 1] dl_dir =",
"match in itr: pre = match.group(1) if not pre: pre = 'https:' url",
"os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for f in subfile: subf =",
"= True if downloaded: if re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"',",
"filename = parts[n - 1] dl_dir = 'dl/' for i in range(n -",
"response = urllib2.urlopen(pre + '//' + url) html = response.read() with open(dl_file, 'w+')",
"as f: data = f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr =",
"re, urllib2 def download(path, ext): path = os.path.expanduser(path) for (dirname, subdir, subfile) in",
"urllib2.urlopen(pre + '//' + url) html = response.read() with open(dl_file, 'w+') as df:",
"subfile) in os.walk(path): for f in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext):",
"= False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in itr:",
"in itr: pre = match.group(1) if not pre: pre = 'https:' url =",
"downloaded = True except: print(\"download failed: \" + pre + '//' + url)",
"urllib2 def download(path, ext): path = os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path):",
"= f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for",
"= 'dl/' for i in range(n - 1): dl_dir = dl_dir + parts[i]",
"= match.group(2) parts = url.split('/') n = len(parts) filename = parts[n - 1]",
"os.path.exists(dl_file): try: print('download from: ' + pre + '//' + url) print('download to:",
"True if found: f.seek(0) f.truncate() f.write(data) if __name__ == '__main__': download('./themes', '.ejs') download('./src/v2',",
"os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path, 'r+') as f: data =",
"f) download(subf, ext) def fix_file(path): with open(path, 'r+') as f: data = f.read()",
"with open(path, 'r+') as f: data = f.read() found = False pat =",
"in subdir: subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path, 'r+')",
"+ parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename",
"= True except: print(\"download failed: \" + pre + '//' + url) else:",
"not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded = False if not",
"downloaded: if re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found =",
"itr: pre = match.group(1) if not pre: pre = 'https:' url = match.group(2)",
"parts[n - 1] dl_dir = 'dl/' for i in range(n - 1): dl_dir",
"+ url) html = response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded =",
"response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded = True except: print(\"download failed:",
"dl_dir = 'dl/' for i in range(n - 1): dl_dir = dl_dir +",
"f) if subf.endswith(ext): fix_file(subf) for f in subdir: subf = os.path.join(dirname, f) download(subf,",
"failed: \" + pre + '//' + url) else: downloaded = True if",
"coding:utf-8 -*- import os, sys, re, urllib2 def download(path, ext): path = os.path.expanduser(path)",
"subdir, subfile) in os.walk(path): for f in subfile: subf = os.path.join(dirname, f) if",
"= dl_dir + parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir",
"import os, sys, re, urllib2 def download(path, ext): path = os.path.expanduser(path) for (dirname,",
"= os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in subdir: subf = os.path.join(dirname,",
"r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in itr: pre = match.group(1) if",
"to: ' + dl_file) response = urllib2.urlopen(pre + '//' + url) html =",
"dl_file) response = urllib2.urlopen(pre + '//' + url) html = response.read() with open(dl_file,",
"'//' + url) print('download to: ' + dl_file) response = urllib2.urlopen(pre + '//'",
"f in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in",
"#!/usr/env/bin python # -*- coding:utf-8 -*- import os, sys, re, urllib2 def download(path,",
"pre = match.group(1) if not pre: pre = 'https:' url = match.group(2) parts",
"pre + '//' + url) print('download to: ' + dl_file) response = urllib2.urlopen(pre",
"pre = 'https:' url = match.group(2) parts = url.split('/') n = len(parts) filename",
"except: print(\"download failed: \" + pre + '//' + url) else: downloaded =",
"pre + '//' + url) else: downloaded = True if downloaded: if re.search(pat,",
"for (dirname, subdir, subfile) in os.walk(path): for f in subfile: subf = os.path.join(dirname,",
"in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for f in subdir:",
"'//' + url) else: downloaded = True if downloaded: if re.search(pat, data) !=",
"= re.finditer(pat, data) for match in itr: pre = match.group(1) if not pre:",
"f: data = f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat,",
"data) found = True if found: f.seek(0) f.truncate() f.write(data) if __name__ == '__main__':",
"url) html = response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded = True",
"True except: print(\"download failed: \" + pre + '//' + url) else: downloaded",
"subf.endswith(ext): fix_file(subf) for f in subdir: subf = os.path.join(dirname, f) download(subf, ext) def",
"for f in subdir: subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path): with",
"open(dl_file, 'w+') as df: df.write(html) downloaded = True except: print(\"download failed: \" +",
"'w+') as df: df.write(html) downloaded = True except: print(\"download failed: \" + pre",
"'r+') as f: data = f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr",
"downloaded = False if not os.path.exists(dl_file): try: print('download from: ' + pre +",
"pre: pre = 'https:' url = match.group(2) parts = url.split('/') n = len(parts)",
"url) print('download to: ' + dl_file) response = urllib2.urlopen(pre + '//' + url)",
"= r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in itr: pre = match.group(1)",
"+ url) print('download to: ' + dl_file) response = urllib2.urlopen(pre + '//' +",
"+ '//' + url) else: downloaded = True if downloaded: if re.search(pat, data)",
"if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded = False if",
"else: downloaded = True if downloaded: if re.search(pat, data) != None: data =",
"python # -*- coding:utf-8 -*- import os, sys, re, urllib2 def download(path, ext):",
"1): dl_dir = dl_dir + parts[i] + '/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file",
"data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found: f.seek(0) f.truncate() f.write(data)",
"'//' + url) html = response.read() with open(dl_file, 'w+') as df: df.write(html) downloaded",
"os.walk(path): for f in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf) for",
"= 'https:' url = match.group(2) parts = url.split('/') n = len(parts) filename =",
"-*- import os, sys, re, urllib2 def download(path, ext): path = os.path.expanduser(path) for",
"= url.split('/') n = len(parts) filename = parts[n - 1] dl_dir = 'dl/'",
"'/' if not os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded = False",
"False if not os.path.exists(dl_file): try: print('download from: ' + pre + '//' +",
"fix_file(subf) for f in subdir: subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path):",
"+ pre + '//' + url) print('download to: ' + dl_file) response =",
"in os.walk(path): for f in subfile: subf = os.path.join(dirname, f) if subf.endswith(ext): fix_file(subf)",
"ext): path = os.path.expanduser(path) for (dirname, subdir, subfile) in os.walk(path): for f in",
"' + dl_file) response = urllib2.urlopen(pre + '//' + url) html = response.read()",
"os.path.exists(dl_dir): os.makedirs(dl_dir) dl_file = dl_dir + filename downloaded = False if not os.path.exists(dl_file):",
"if subf.endswith(ext): fix_file(subf) for f in subdir: subf = os.path.join(dirname, f) download(subf, ext)",
"= len(parts) filename = parts[n - 1] dl_dir = 'dl/' for i in",
"df: df.write(html) downloaded = True except: print(\"download failed: \" + pre + '//'",
"= False if not os.path.exists(dl_file): try: print('download from: ' + pre + '//'",
"url = match.group(2) parts = url.split('/') n = len(parts) filename = parts[n -",
"= match.group(1) if not pre: pre = 'https:' url = match.group(2) parts =",
"f in subdir: subf = os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path,",
"print(\"download failed: \" + pre + '//' + url) else: downloaded = True",
"f.read() found = False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match",
"= parts[n - 1] dl_dir = 'dl/' for i in range(n - 1):",
"data) for match in itr: pre = match.group(1) if not pre: pre =",
"downloaded = True if downloaded: if re.search(pat, data) != None: data = re.sub(pat,",
"sys, re, urllib2 def download(path, ext): path = os.path.expanduser(path) for (dirname, subdir, subfile)",
"def fix_file(path): with open(path, 'r+') as f: data = f.read() found = False",
"= os.path.join(dirname, f) download(subf, ext) def fix_file(path): with open(path, 'r+') as f: data",
"not os.path.exists(dl_file): try: print('download from: ' + pre + '//' + url) print('download",
"+ '//' + url) html = response.read() with open(dl_file, 'w+') as df: df.write(html)",
"data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found = True if found:",
"range(n - 1): dl_dir = dl_dir + parts[i] + '/' if not os.path.exists(dl_dir):",
"False pat = r'=\"(https?:)?//([^\"<]*\\.(js|css|svg))\"' itr = re.finditer(pat, data) for match in itr: pre",
"if downloaded: if re.search(pat, data) != None: data = re.sub(pat, r'=\"/dl/\\2\"', data) found",
"print('download from: ' + pre + '//' + url) print('download to: ' +",
"os, sys, re, urllib2 def download(path, ext): path = os.path.expanduser(path) for (dirname, subdir,"
] |
[
"deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step = 0.0 while not finish: all_observations.append(observation)",
"all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means,",
"= demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control)",
"behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards",
"[] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate))",
"behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations)",
"deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0)",
"from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping",
"deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name +",
"time_step) # add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset)",
"np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls}",
"sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x,",
"all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f:",
"= behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control *",
"import sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size,",
"* def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if",
"logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for",
"= behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control =",
"Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import * def",
"Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y,",
"time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control,",
"all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0.",
"moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x,",
"+ domain_name + '_' + str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks",
"tensorflow as tf from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys",
"= {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with",
"moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward",
"if not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] =",
"# add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) *",
"feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation,",
"= [] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], []",
"drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation",
"step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step",
"= tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations",
"demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control)",
"os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' + str(task_identity) + '_' +",
"info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if",
"= env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if not",
"-(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x))",
"as tf from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../')",
"task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation = env.reset() finish = False moving_window_x",
"TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f: # pickle.dump(logs_for_all_tasks, f,",
"get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation = env.reset() finish = False",
"+ '_' + str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {}",
"False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x,",
"= LOGS_DIRECTORY + domain_name + '_' + str(task_identity) + '_' + str(window_size) +",
"deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' +",
"all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with",
"observation = np.append(observation, time_step) # add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node:",
"pickle import gpflow import os import tensorflow as tf from Load_Controllers import Load_Demonstrator",
"= 0. observation = env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0,",
"observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control",
"behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x,",
"validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards",
"gpflow import os import tensorflow as tf from Load_Controllers import Load_Demonstrator from multiple_tasks",
"BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f: #",
"[] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls = []",
"import _pickle as pickle import gpflow import os import tensorflow as tf from",
"os import tensorflow as tf from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment",
"in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards =",
"str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {}",
"sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller,",
"not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' + str(task_identity) +",
"numpy as np import _pickle as pickle import gpflow import os import tensorflow",
"demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control)",
"all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f: # pickle.dump(logs_for_all_tasks,",
"logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph()",
"tf from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from",
"def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not",
"all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time step feature demonstrator_control",
"- demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish,",
"'_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task",
"from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name,",
"behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step = 0.0",
"validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY):",
"deviation_y time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation,",
"logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)]",
"= Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = []",
"behavior_var_control = behavior_var_control * deviation_y time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control)",
"axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY:",
"= np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY:",
"as np import _pickle as pickle import gpflow import os import tensorflow as",
"range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards = []",
"{} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in",
"moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY",
"axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] =",
"mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations",
"np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls",
"multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity,",
"observation = env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] =",
"finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control",
"target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0,",
"= {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] =",
"all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node,",
"mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_'",
"Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations",
"for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller",
"all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [],",
"= behavior_var_control * deviation_y time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control))",
"_pickle as pickle import gpflow import os import tensorflow as tf from Load_Controllers",
"np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards,",
"all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means,",
"behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY +",
"= logs_for_a_task #with open(file_to_save_logs, 'wb') as f: # pickle.dump(logs_for_all_tasks, f, protocol=-1) return logs_for_all_tasks",
"task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller =",
"[] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation = env.reset()",
"np import _pickle as pickle import gpflow import os import tensorflow as tf",
"demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means =",
"import os import tensorflow as tf from Load_Controllers import Load_Demonstrator from multiple_tasks import",
"= [] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls =",
"0. observation = env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:]",
"* deviation_y time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation =",
"demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3",
"np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])]",
"moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] =",
"all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls =",
"task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations =",
"all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY:",
"all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb')",
"#all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. *",
"behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control",
"reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control =",
"logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f: # pickle.dump(logs_for_all_tasks, f, protocol=-1) return",
"import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size,",
"(observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward,",
"demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info",
"env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if not window_size",
"from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x,",
"domain_name + '_' + str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks =",
"LOGS_DIRECTORY + domain_name + '_' + str(task_identity) + '_' + str(window_size) + '_GP.pkl'",
"all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time step feature demonstrator_control =",
"deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step =",
"-1. * np.dot(K, observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step] =",
"#all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance =",
"not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0]",
"= REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means",
"= [] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations",
"= observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y)",
"1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] =",
"+ '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES:",
"moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control,",
"0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add",
"[] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], [] env",
"reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation),",
"all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as f: # pickle.dump(logs_for_all_tasks, f, protocol=-1)",
"finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]])",
"= np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY:",
"all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations,",
"env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation = env.reset() finish",
"as pickle import gpflow import os import tensorflow as tf from Load_Controllers import",
"all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost",
"+= 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control",
"mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name",
"np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control",
"== 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])]",
"* deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations",
":-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0,",
"{OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task",
"total_variance = 0. observation = env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size))",
"[], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation =",
"* np.dot(K, observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0,",
"task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY)",
"window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs",
"not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time step",
"BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs,",
"= np.append(observation, time_step) # add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1)",
"= env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation",
"behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control =",
"= [] #all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost =",
"observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0,",
"= np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x))",
"1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control =",
"#file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' + str(task_identity) + '_' + str(window_size)",
"import gpflow import os import tensorflow as tf from Load_Controllers import Load_Demonstrator from",
"+ str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate",
"with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = []",
"= REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step = 0.0 while",
"np.append(observation, time_step) # add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) -",
"* demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info =",
"all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if not window_size ==",
"[] #all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance",
"= np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0)",
"os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' + str(task_identity) + '_'",
"import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import *",
"feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control) time_step +=",
"mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step",
"ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate))",
"REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step = 0.0 while not",
"= moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:]",
"str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in",
"= False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control =",
"add time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale})",
"= {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial",
"'_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph =",
"moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control =",
"time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step)",
"REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means =",
"= total_variance = 0. observation = env.reset() finish = False moving_window_x = np.zeros((1,",
"all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY: all_behavior_control_means, BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations,",
"all_demonstrator_controls.append(demonstrator_control) time_step += 1e-3 #all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward)",
"'_' + str(task_identity) + '_' + str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for",
"moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control,",
"-drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0, -(drift_per_time_step-behavior_mean_control.shape[1])] = reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control",
"-observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y,",
"np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations, BEHAVIORAL_CONTROL_MEANS_LOG_KEY:",
"if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs = LOGS_DIRECTORY + domain_name + '_' + str(task_identity)",
"= [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name,",
"for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations = []",
"env.reset() finish = False moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control,",
"window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:] moving_window_x[0, -drift_per_time_step:-(drift_per_time_step-behavior_mean_control.shape[1])] = behavior_mean_control[0] moving_window_x[0,",
"demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations = [] all_behavior_control_means",
"+ str(window_size) + '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task =",
"= np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)] = {OBSERVATIONS_LOG_KEY: all_observations,",
"moving_window_x = np.zeros((1, moving_windows_x_size)) moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x,",
"= -1. * np.dot(K, observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step]",
"+ '_GP.pkl' logs_for_all_tasks = {} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph",
"<gh_stars>1-10 import numpy as np import _pickle as pickle import gpflow import os",
"import tensorflow as tf from Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import",
"while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time",
"{} for task_to_validate in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default():",
"behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards)",
"observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1. * np.dot(K,",
"behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y",
"= np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls)",
"tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS): all_observations =",
"= 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) #",
"Load_Controllers import Load_Demonstrator from multiple_tasks import get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import",
"import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y):",
"get_task_on_MUJOCO_environment import sys sys.path.insert(0,'./../') from Housekeeping import * def validate_GP_controller(domain_name, task_identity, window_size, drift_per_time_step,",
"in ALL_MUJOCO_TASK_IDENTITIES: logs_for_a_task = {} demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name,",
"total_cost = total_variance = 0. observation = env.reset() finish = False moving_window_x =",
"mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y time_step = 0.0 while not finish:",
"behavior_var_control * deviation_y time_step = 0.0 while not finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation",
"finish: all_observations.append(observation) all_behavior_control_means.append(behavior_mean_control) all_behavior_control_deviations.append(np.sqrt(behavior_var_control)) observation = np.append(observation, time_step) # add time step feature",
"= reward moving_window_x[0, -observation.shape[0]:] = observation behavior_mean_control, behavior_var_control = behavior_controller.predict_y(NORMALIZE(moving_window_x, mean_x, deviation_x)) behavior_mean_control",
"deviation_x)) behavior_mean_control = REVERSE_NORMALIZE(behavior_mean_control, mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations =",
"time step feature demonstrator_control = demonstrator_controller.sess.run(demonstrator_controller.output_action_node, feed_dict={demonstrator_controller.scaled_observation_node: (observation.reshape(1,-1) - demonstrator_controller.offset) * demonstrator_controller.scale}) all_demonstrator_controls.append(demonstrator_control)",
"#target_mean_control, target_var_control = -1. * np.dot(K, observation), np.array([[0.]]) if not window_size == 1:",
"deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations =",
"all_observations = [] all_behavior_control_means = [] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls",
"mean_y, deviation_y) behavior_var_control = behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means,",
"[] all_behavior_control_deviations = [] all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations =",
"import numpy as np import _pickle as pickle import gpflow import os import",
"= behavior_var_control * deviation_y all_observations = np.array(all_observations) all_behavior_control_means = np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards =",
"np.concatenate(all_behavior_control_means, axis=0) all_behavior_rewards = np.array(all_behavior_rewards) all_behavior_control_deviations = np.concatenate(all_behavior_control_deviations, axis=0) all_demonstrator_controls = np.array(all_demonstrator_controls) logs_for_a_task[str(validation_trial)]",
"np.dot(K, observation), np.array([[0.]]) if not window_size == 1: moving_window_x[0, :-drift_per_time_step] = moving_window_x[0, drift_per_time_step:]",
"drift_per_time_step, moving_windows_x_size, behavior_controller, mean_x, deviation_x, mean_y, deviation_y): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) #file_to_save_logs =",
"= [], [] env = get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation",
"demonstrator_graph = tf.Graph() with demonstrator_graph.as_default(): demonstrator_controller = Load_Demonstrator(domain_name=domain_name, task_identity=str(task_to_validate)) for validation_trial in range(NUMBER_VALIDATION_TRIALS):",
"= get_task_on_MUJOCO_environment(env_name=domain_name, task_identity=str(task_to_validate)) total_cost = total_variance = 0. observation = env.reset() finish =",
"BEHAVIORAL_CONTROL_REWARDS_LOG_KEY: all_behavior_rewards, BEHAVIORAL_CONTROL_DEVIATIONS_LOG_KEY: all_behavior_control_deviations, TARGET_CONTROL_MEANS_LOG_KEY: all_demonstrator_controls} logs_for_all_tasks[str(task_to_validate)] = logs_for_a_task #with open(file_to_save_logs, 'wb') as",
"all_behavior_rewards = [] all_demonstrator_controls = [] #all_target_control_means, all_target_control_deviations = [], [] env =",
"#all_target_control_means.append(target_mean_control) #all_target_control_deviations.append(target_var_control) observation, reward, finish, info = env.step(behavior_mean_control) all_behavior_rewards.append(reward) #target_mean_control, target_var_control = -1."
] |
[
"self.current_destination = '' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options =",
"number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' # get the details of typical",
"wait to be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present)",
"= self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True:",
"= self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent =",
"items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data):",
"encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature':",
"== True: get_dests = self.get_destinations() if get_dests == True: counter = 0 for",
"until to changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content ==",
"= EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem please",
"# get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating",
"self.country months['Destination'] = self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for row in",
"7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert':",
"== 2: rating.style.decompose() rating = rating.text else: rating = '' # number of",
"'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39,",
"21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing':",
"from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class",
"'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22,",
"= row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp']",
"dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country",
"# wait until to changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if",
"= options) def search(self): \"\"\" Find the search input element and enter the",
"if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException: # if",
"'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear':",
"0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return False def",
"key in option_fields]) writer.writerow(fields) # write options options = ['no' for key in",
"20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True",
"elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans ==",
"at=0): attempt = at try: # click the top sight element on menu",
"fields = ['Country', 'Destination', 'Things to Do', 'Rating', 'Number of Review', 'Typical Time",
"= tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] =",
"else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists =",
"# -*- coding: utf-8 -*- # !/usr/bin/env python # Columbus - Personalised Travel",
"import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country = country self.destinations = {}",
"get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver,",
"of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else:",
"try: self.driver.get(self.url) # wait to loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH,",
"+= 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text",
"if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) #",
"49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding':",
"temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException: # if stale exception occur,",
"False except Exception as e: print(e) return False def get_destination_details(self, url, at=0): attempt",
"self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details !=",
"EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on",
"= len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'):",
"'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'],",
"'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing':",
"tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td',",
"'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21,",
"0: # re open browser for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter,",
"destination = data['Destination'] if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx =",
"class GoogleDestination: def __init__(self, country): self.country = country self.destinations = {} self.url =",
"None return True else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1)",
"stale exception occur, try again three times if attempt == 4: return False",
"= number_of_reviews.text.strip() else: number_of_reviews = '' # get the details of typical time",
"enumerate(top_sights): top_sight.click() # click each top sight item by one by try: #",
"Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time",
"select first result time.sleep(1) # wait to loading of search results menu search_results_present",
"# get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists:",
"details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating",
"options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the search input",
"destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not",
"if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations",
"EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem with destination",
"'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if rating:",
"top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent",
"to loading of the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver,",
"= self.country months['Destination'] = self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for row",
"url, at=0): attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present)",
"['no' for key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None: for",
"import os import logging from bs4 import BeautifulSoup from selenium import webdriver from",
"in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical",
"data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time",
"as e: print(e) return False def get_destinations(self, at=0): \"\"\" Get urls of destinations",
"def get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\"))",
"in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None: options[idx] = 'yes' #",
"= destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True",
"12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17,",
"= csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields",
"spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup",
"os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Things to",
"== 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' # get the",
"41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46,",
"search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) #",
"rating = '' # number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if",
"options options = ['no' for key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options']",
"loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe",
"destination months = {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country']",
"'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32,",
"Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) # write options options =",
"'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57,",
"leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee",
"for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to",
"Exception as e: print(e) return False def get_destination_details(self, url, at=0): attempt = at",
"== True: counter = 0 for key, item in self.destinations.items(): if counter %",
"36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking':",
"options[idx] = 'yes' # write data for key, items in data['Topsights'].items(): row =",
"for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if",
"= self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details !=",
"number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) ==",
"'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41,",
"writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing':",
"if block for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) ==",
"number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews",
"as f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0",
"9, 'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef': 14,",
"dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of",
"precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return False def get_topsgihts_details(self,",
"'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger':",
"month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name]",
"idx != None: options[idx] = 'yes' # write data for key, items in",
"destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name)",
"from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from",
"continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name =",
"return months else: return False def get_topsgihts_details(self, at=0): attempt = at try: #",
"= time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent = '' #",
"{} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews",
"# wait to loading of top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH,",
"= EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element",
"{} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in",
"top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight",
"'a', newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path +",
"self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country: \") a =",
"self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select",
"StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country = country self.destinations = {} self.url",
"20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem please try again.\") return False",
"self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3:",
"5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks':",
"len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' # get",
"search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH,",
"\"\"\" Get urls of destinations according to each option and append to list.",
"0 if file_is_empty: fields = ['Country', 'Destination', 'Things to Do', 'Rating', 'Number of",
"top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for",
"run(self): self.open_browser() search = self.search() if search == True: get_dests = self.get_destinations() if",
"= '' # get the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() ==",
"EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if there",
"selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException",
"if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx",
"get_dests == True: counter = 0 for key, item in self.destinations.items(): if counter",
"'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31,",
"selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country",
"False except Exception as e: if attempt == 2: print(e, \" .3.\") return",
"43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting':",
"not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options']",
"else: break return True except StaleElementReferenceException: # if stale exception occur, try again",
"self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try again.\") return False except Exception",
"RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are there any option? options",
"{} tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text other_elems =",
"# Contact <NAME> <<EMAIL>> # import time import re import csv import os",
"False def get_destinations(self, at=0): \"\"\" Get urls of destinations according to each option",
"= destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click()",
"precipitation return months else: return False def get_topsgihts_details(self, at=0): attempt = at try:",
"'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin':",
"write options options = ['no' for key in option_fields] destination = data['Destination'] if",
"Reviews'], items['Typical Time Spent']] row += options writer.writerow(row) def run(self): self.open_browser() search =",
"Itineraries based on experience, country or preferred destination. # Contact <NAME> <<EMAIL>> #",
"elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity",
"wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return",
"of Review', 'Typical Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) # write",
"elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return False def get_topsgihts_details(self, at=0): attempt",
"again three times if attempt == 4: return False attempt += 1 return",
"= '' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans = len(elem.find_all('span')) #",
"'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26,",
"place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] =",
"topsight at 'destination' return False except Exception as e: if attempt == 2:",
"57, 'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty:",
"get_destinations(self, at=0): \"\"\" Get urls of destinations according to each option and append",
"time_spent # wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click()",
"memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details",
"counter = 0 for key, item in self.destinations.items(): if counter % 20 ==",
"return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination",
"time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first result time.sleep(1)",
"20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination top_sights_detail =",
"time.sleep(1) return top_sights_detail except NoSuchElementException: # if there are no topsight at 'destination'",
"popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature",
"selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country = country self.destinations =",
"# click the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to",
"items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8',",
"be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem =",
"get all topsight element on destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination']",
"number_of_reviews.text.strip() else: number_of_reviews = '' # get the details of typical time spent",
"'' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem in",
"Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By",
"= self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click()",
"'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga':",
"except Exception as e: print(e) return False def get_destination_details(self, url, at=0): attempt =",
"place_name = soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if rating: if",
"time.sleep(1) # wait until to changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\")",
"attempt == 3: print(\"Problem with destination \", url) return False attempt += 1",
"== True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent",
"from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as",
"number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' # get the details of",
"'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale",
"with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',')",
"= self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination",
"color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping':",
"for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None: options[idx] =",
"def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self):",
"months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation']",
"name. \"\"\" try: self.driver.get(self.url) # wait to loading of search input element search_input_present",
"time_spent.find('b').text else: time_spent = '' # add details to dict top_sights_detail['Topsights'][idx] = {}",
"on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML')",
"24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29,",
"\"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem please try again.\")",
"1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try again.\") return False",
"input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country",
"wait to loading of top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\"))",
"in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']:",
"top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') #",
"data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f:",
"write country end select first result time.sleep(1) # wait to loading of search",
"return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a',",
"for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def",
"46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51,",
"country end select first result time.sleep(1) # wait to loading of search results",
"len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity",
"e: print(e) return False def get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url)",
"destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL']",
"if rating: if len(rating) == 2: rating.style.decompose() rating = rating.text else: rating =",
"reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30,",
"clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH,",
"self.driver = '' self.current_destination = '' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver",
"0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name",
"temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option",
"tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] =",
"bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys",
"!= None: options[idx] = 'yes' # write data for key, items in data['Topsights'].items():",
"= '' # number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews:",
"{} for idx,top_sight in enumerate(top_sights): top_sight.click() # click each top sight item by",
"self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the search input element",
"get_dests = self.get_destinations() if get_dests == True: counter = 0 for key, item",
"for key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None: for o",
"20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem with destination \", url) return",
"top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click() # click",
"self.destinations = {} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination = '' def",
"import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from",
"months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation']",
"there are no topsight at 'destination' return False except Exception as e: if",
"== 0 if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation']",
"print(e) return False def get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url) destination_detail_present",
"{'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5,",
"# guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException:",
"to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail",
"destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name =",
"months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation",
"\"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight page of destination top_sights_list_present =",
"experience, country or preferred destination. # Contact <NAME> <<EMAIL>> # import time import",
"typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html =",
"elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity",
"selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination:",
"Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions",
"self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True else: for i in range(len(options)):",
"self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination top_sights_detail = {} top_sights_detail['Country'] =",
"rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait",
"{} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until",
"= data['Destination'] if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o)",
"== 2: tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp']",
"50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55,",
"of top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights",
"three times if attempt == 4: return False attempt += 1 return self.get_destinations(attempt)",
"# wait to be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver,",
"self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get",
"destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1)",
"data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with",
"39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44,",
"preferred destination. # Contact <NAME> <<EMAIL>> # import time import re import csv",
"top_sights_detail except NoSuchElementException: # if there are no topsight at 'destination' return False",
"Time Spent']] row += options writer.writerow(row) def run(self): self.open_browser() search = self.search() if",
"loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem =",
"if counter % 20 == 0: # re open browser for memory self.driver.close()",
"input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first result time.sleep(1) # wait to",
"if there are no topsight at 'destination' return False except Exception as e:",
"loading of the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present)",
"= soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country months['Destination'] = self.current_destination",
"'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields",
"browser for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL'])",
"return True except TimeoutException: print(\"1. Timeout problem please try again.\") return False except",
"= destination_url self.destinations[destination_name]['Options'] = None return True else: for i in range(len(options)): temp_class_of_content",
"first result time.sleep(1) # wait to loading of search results menu search_results_present =",
"23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28,",
"1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0]",
"newline='') as f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1,",
"writer.writerow(fields) # write options options = ['no' for key in option_fields] destination =",
"= 'yes' # write data for key, items in data['Topsights'].items(): row = [data['Country'],",
"to loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1)",
"for key, item in self.destinations.items(): if counter % 20 == 0: # re",
"import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import",
"temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while",
"webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait",
"= EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link",
"self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in",
"print(\"2. Timeout problem please try again.\") return False except Exception as e: print(e)",
"1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text #",
"popularity if length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label']",
"+= 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path +",
"search(self): \"\"\" Find the search input element and enter the country name. \"\"\"",
"{} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = ''",
"'yes' # write data for key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'],",
"+ '/Months.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp',",
"WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination top_sights_detail",
"Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National",
"current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException: # if stale",
"class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = ''",
"if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews =",
"Exception as e: if attempt == 2: print(e, \" .3.\") return False attempt",
"= EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\"))",
"= self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") #",
"options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find",
"class_='rtng') if rating: if len(rating) == 2: rating.style.decompose() rating = rating.text else: rating",
"if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details)",
"WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to",
"def get_destinations(self, at=0): \"\"\" Get urls of destinations according to each option and",
"= EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are there",
"\"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are there any option?",
"in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of",
"write data for key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'],",
"'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42,",
"['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in",
"def get_topsgihts_details(self, at=0): attempt = at try: # click the top sight element",
"= None return True else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click()",
"import csv import os import logging from bs4 import BeautifulSoup from selenium import",
"items['Typical Time Spent']] row += options writer.writerow(row) def run(self): self.open_browser() search = self.search()",
"20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write",
"and append to list. \"\"\" attempt = at try: # wait to be",
"print(\"Problem with destination \", url) return False attempt += 1 return self.get_destination_details(url, attempt)",
"guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1.",
"topsight element on destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination",
"write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as",
"urls of destinations according to each option and append to list. \"\"\" attempt",
"TimeoutException: print(\"1. Timeout problem please try again.\") return False except Exception as e:",
"# add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating']",
"# guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first result time.sleep(1) #",
"self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text",
"Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16,",
"\"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first",
"= {} tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text other_elems",
"top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights =",
"problem please try again.\") return False except Exception as e: print(e) return False",
"rating = soup.find('span', class_='rtng') if rating: if len(rating) == 2: rating.style.decompose() rating =",
"'' # number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if",
"of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2:",
"item in self.destinations.items(): if counter % 20 == 0: # re open browser",
"selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support",
"input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click()",
"= self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end",
"csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields =",
"item by one by try: # wait to loading of the content of",
"os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity',",
"return False attempt += 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination",
"\", url) return False attempt += 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source,",
"list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for",
"31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37,",
"self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to loading of destinations list",
"key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of",
"def run(self): self.open_browser() search = self.search() if search == True: get_dests = self.get_destinations()",
"search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER)",
"# get all topsight element on destination top_sights_detail = {} top_sights_detail['Country'] = self.country",
"'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key,",
"skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if",
"TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name",
"wait until to changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content",
"1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details =",
"import re import csv import os import logging from bs4 import BeautifulSoup from",
"4: return False attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem",
"wait to loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present)",
"of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get",
"e: print(e) return False def get_destinations(self, at=0): \"\"\" Get urls of destinations according",
"1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr')",
"['Country', 'Destination', 'Things to Do', 'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key",
"self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser')",
"# wait to loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver,",
"counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details)",
"WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem with destination \", url)",
"break return True except StaleElementReferenceException: # if stale exception occur, try again three",
"open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty",
"idx,top_sight in enumerate(top_sights): top_sight.click() # click each top sight item by one by",
"True else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait",
"to Do', 'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key for key in",
"Spent']] row += options writer.writerow(row) def run(self): self.open_browser() search = self.search() if search",
"popularity # tempature if length_of_spans == 2: tempatures = [i.text for i in",
"option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination",
"write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as",
"40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45,",
"os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f,",
"= rating.text else: rating = '' # number of reviews number_of_reviews = soup.find('span',",
"<gh_stars>0 # -*- coding: utf-8 -*- # !/usr/bin/env python # Columbus - Personalised",
"32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38,",
"please try again.\") return False except Exception as e: print(e) return False def",
"current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\")",
"soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination months = {} month_table =",
"Do', 'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key for key in option_fields])",
"in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] =",
"python # Columbus - Personalised Travel Itineraries based on experience, country or preferred",
"29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35,",
"!= None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None:",
"== 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if",
"idx = option_fields.get(o) if idx != None: options[idx] = 'yes' # write data",
"= tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation =",
"<NAME> <<EMAIL>> # import time import re import csv import os import logging",
"selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException",
"\" .3.\") return False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path",
"writer.writerow(row) def run(self): self.open_browser() search = self.search() if search == True: get_dests =",
"= self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination top_sights_detail = {} top_sights_detail['Country']",
"until to changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content ==",
"row in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {}",
"expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions",
"print(e, \" .3.\") return False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data):",
"'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25,",
"months else: return False def get_topsgihts_details(self, at=0): attempt = at try: # click",
"at try: # click the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() #",
"Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to close element",
"csv import os import logging from bs4 import BeautifulSoup from selenium import webdriver",
"sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li')",
"topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country: \")",
"'/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture':",
"'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef':",
"option_fields.get(o) if idx != None: options[idx] = 'yes' # write data for key,",
"of the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except",
"soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if rating: if len(rating) ==",
"self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx !=",
"fields.extend([key for key in option_fields]) writer.writerow(fields) # write options options = ['no' for",
"self.get_destinations() if get_dests == True: counter = 0 for key, item in self.destinations.items():",
"EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException",
"destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem",
"are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists =",
"== temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException: # if stale exception",
"writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if file_is_empty:",
"in option_fields]) writer.writerow(fields) # write options options = ['no' for key in option_fields]",
"items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a',",
"time_spent = '' # add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name']",
"NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country = country",
"destination_url self.destinations[destination_name]['Options'] = None return True else: for i in range(len(options)): temp_class_of_content =",
"time_spent = time_spent.find('b').text else: time_spent = '' # add details to dict top_sights_detail['Topsights'][idx]",
"country or preferred destination. # Contact <NAME> <<EMAIL>> # import time import re",
"'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest':",
"or preferred destination. # Contact <NAME> <<EMAIL>> # import time import re import",
"= os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer =",
"key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self,",
"time.sleep(3) else: break return True except StaleElementReferenceException: # if stale exception occur, try",
"else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent:",
"options) def search(self): \"\"\" Find the search input element and enter the country",
"number_of_reviews = '' # get the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed()",
"webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the search input element and enter",
"self.open_browser() search = self.search() if search == True: get_dests = self.get_destinations() if get_dests",
"20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to loading",
"47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting':",
"10, 'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15,",
"try again.\") return False except Exception as e: print(e) return False def get_destination_details(self,",
"= soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if rating: if len(rating)",
"14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier':",
"'' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity",
"20).until(destinations_list_present) # maybe if block for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")",
"maybe if block for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options)",
"popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity']",
"'/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Things to Do', 'Rating',",
"if idx != None: options[idx] = 'yes' # write data for key, items",
"add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] =",
"while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name",
"soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination =",
"Find the search input element and enter the country name. \"\"\" try: self.driver.get(self.url)",
"in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity =",
"= soup.find('span', class_='rtng') if rating: if len(rating) == 2: rating.style.decompose() rating = rating.text",
"from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from",
"True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent =",
"False def get_topsgihts_details(self, at=0): attempt = at try: # click the top sight",
"len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML')",
"the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML')",
"'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters':",
"class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if rating: if len(rating) == 2:",
"'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife':",
"'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife':",
"= time_spent # wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present)",
"destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True else:",
"import time import re import csv import os import logging from bs4 import",
"-*- coding: utf-8 -*- # !/usr/bin/env python # Columbus - Personalised Travel Itineraries",
"of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click()",
"tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine",
"Get urls of destinations according to each option and append to list. \"\"\"",
"at=0): attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except",
"False except Exception as e: print(e) return False def get_destinations(self, at=0): \"\"\" Get",
"top sight item by one by try: # wait to loading of the",
"'' # add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name",
"self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight page of destination top_sights_list_present",
"number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = ''",
"search = self.search() if search == True: get_dests = self.get_destinations() if get_dests ==",
"months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for",
"content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break",
"# destination name self.current_destination = destination months = {} month_table = soup.find_all('table', class_='qt3FE')",
"except StaleElementReferenceException: # if stale exception occur, try again three times if attempt",
"'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin':",
"'Typical Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) # write options options",
"def __init__(self, country): self.country = country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver",
"popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if",
"time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent",
"destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem",
"'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'],",
"all topsight element on destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] =",
"utf-8 -*- # !/usr/bin/env python # Columbus - Personalised Travel Itineraries based on",
"import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import",
"WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if there are no",
"import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from",
"items['Number of Reviews'], items['Typical Time Spent']] row += options writer.writerow(row) def run(self): self.open_browser()",
"Contact <NAME> <<EMAIL>> # import time import re import csv import os import",
"import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from",
"# if stale exception occur, try again three times if attempt == 4:",
"delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields = ['Country',",
"+= options writer.writerow(row) def run(self): self.open_browser() search = self.search() if search == True:",
"WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions",
"input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first result",
"= row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp']",
"for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists",
"based on experience, country or preferred destination. # Contact <NAME> <<EMAIL>> # import",
"option and append to list. \"\"\" attempt = at try: # wait to",
"option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for",
"Review', 'Typical Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) # write options",
"to changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content:",
"wait to loading of the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\"))",
"country name. \"\"\" try: self.driver.get(self.url) # wait to loading of search input element",
"csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking':",
"\"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup",
"\"\"\" attempt = at try: # wait to be clickable of destinations link",
"tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation = elem.text",
"= number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to close element close_present",
"EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country,",
"% 20 == 0: # re open browser for memory self.driver.close() self.open_browser() counter",
"try again three times if attempt == 4: return False attempt += 1",
"\"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to loading of destinations list destinations_list_present",
"length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity = elem.find('span') if",
"options = ['no' for key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] !=",
"'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7,",
"if attempt == 3: print(\"Problem with destination \", url) return False attempt +=",
"22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba",
"attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException:",
"self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click() #",
"= elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans",
"in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans ==",
"0 for key, item in self.destinations.items(): if counter % 20 == 0: #",
"else: return False def get_topsgihts_details(self, at=0): attempt = at try: # click the",
"selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by",
"52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing':",
"top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html =",
"= BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination",
"try: # wait to loading of the content of top sight top_sight_present =",
"return False except Exception as e: print(e) return False def get_destinations(self, at=0): \"\"\"",
"time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent = ''",
"# wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1)",
"11, 'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter",
"# number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews)",
"and enter the country name. \"\"\" try: self.driver.get(self.url) # wait to loading of",
"# if there are no topsight at 'destination' return False except Exception as",
"'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks': 11,",
"close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: #",
"GoogleDestination: def __init__(self, country): self.country = country self.destinations = {} self.url = 'https://www.google.com/destination'",
"= month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd')",
"import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country =",
"56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size ==",
"if attempt == 4: return False attempt += 1 return self.get_destinations(attempt) except TimeoutException:",
"import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import",
"soup.find('span', class_='rtng') if rating: if len(rating) == 2: rating.style.decompose() rating = rating.text else:",
"= EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get",
"\"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if there are",
"country): self.country = country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver = ''",
"rating.text else: rating = '' # number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe",
"'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53,",
"print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details()",
"at 'destination' return False except Exception as e: if attempt == 2: print(e,",
"= self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click() # click each",
"search input element and enter the country name. \"\"\" try: self.driver.get(self.url) # wait",
"of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to close",
"row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] =",
"enter the country name. \"\"\" try: self.driver.get(self.url) # wait to loading of search",
"# get the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html",
"55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path",
"selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui",
"changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3)",
"= '' for elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans",
"except NoSuchElementException: # if there are no topsight at 'destination' return False except",
"current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on",
"break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\")",
"= self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to loading of destinations",
"self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True: temp_class_of_content",
"'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56,",
"self.search() if search == True: get_dests = self.get_destinations() if get_dests == True: counter",
"end select first result time.sleep(1) # wait to loading of search results menu",
"logging from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options",
"return top_sights_detail except NoSuchElementException: # if there are no topsight at 'destination' return",
"25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari':",
"= '' # add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] =",
"destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block",
"path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer",
"self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click() # click each top",
"26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar':",
"input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout",
"element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1)",
"return True except StaleElementReferenceException: # if stale exception occur, try again three times",
"month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = ''",
"else: number_of_reviews = '' # get the details of typical time spent if",
"= soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination months = {} month_table",
"of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html",
"months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans = len(elem.find_all('span'))",
"destinations according to each option and append to list. \"\"\" attempt = at",
"len(month_table) > 1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] = {} tr",
"there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\")",
"= elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return False def get_topsgihts_details(self, at=0):",
"= top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text",
"attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path",
"items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path +",
"'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching':",
"data for key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'],",
"== 0 if file_is_empty: fields = ['Country', 'Destination', 'Things to Do', 'Rating', 'Number",
"+ '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Things to Do',",
"of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if",
"= os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer =",
"encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size ==",
".3.\") return False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path =",
"time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else:",
"if attempt == 2: print(e, \" .3.\") return False attempt += 1 return",
"wait to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present)",
"element on destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights']",
"menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present =",
"== 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+',",
"details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating =",
"number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to close element close_present =",
"20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html,",
"newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size",
"'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52,",
"block for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0:",
"from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from",
"loading of top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present)",
"WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return",
"15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism':",
"return False def get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url) destination_detail_present =",
"path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer",
"self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True: current_class_of_content",
"of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html",
"data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path =",
"= Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the",
"import logging from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import",
"according to each option and append to list. \"\"\" attempt = at try:",
"= BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng')",
"return False except Exception as e: if attempt == 2: print(e, \" .3.\")",
"By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions",
"<<EMAIL>> # import time import re import csv import os import logging from",
"soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months']",
"== 2: print(e, \" .3.\") return False attempt += 1 return self.get_topsgihts_details(attempt) def",
"= destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {}",
"in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity']",
"# maybe if block for are there any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if",
"= ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items",
"19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve':",
"shark': 56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size",
"print(\"1. Timeout problem please try again.\") return False except Exception as e: print(e)",
"False attempt += 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination =",
"the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException:",
"options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in",
"try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt ==",
"self.destinations[destination_name]['Options'] = None return True else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\")",
"name self.current_destination = destination months = {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table)",
"except TimeoutException: print(\"1. Timeout problem please try again.\") return False except Exception as",
"[] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True:",
"!= False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country =",
"element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight page",
"each top sight item by one by try: # wait to loading of",
"self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content",
"self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name",
"= destination months = {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1:",
"attempt = at try: # wait to be clickable of destinations link destinations_elem_present",
"attempt == 2: print(e, \" .3.\") return False attempt += 1 return self.get_topsgihts_details(attempt)",
"attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try again.\")",
"months['Destination'] = self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for row in tr[1:13]:",
"return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try again.\") return False except",
"to loading of top sight page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver,",
"'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color':",
"20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if there are no topsight",
"= country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination =",
"one by try: # wait to loading of the content of top sight",
"'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature",
"with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',')",
"Columbus - Personalised Travel Itineraries based on experience, country or preferred destination. #",
"on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight page of",
"key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path",
"= at try: # click the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click()",
"watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot spring':",
"if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name =",
"months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if",
"return True else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) #",
"again.\") return False except Exception as e: print(e) return False def get_destinations(self, at=0):",
"for key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number",
"content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue",
"self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if",
"file_is_empty: fields = ['Country', 'Destination', 'Things to Do', 'Rating', 'Number of Review', 'Typical",
"len(rating) == 2: rating.style.decompose() rating = rating.text else: rating = '' # number",
"if len(rating) == 2: rating.style.decompose() rating = rating.text else: rating = '' #",
"page of destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') #",
"= self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException:",
"row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']]",
"selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC",
"destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url =",
"= rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent #",
"from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country): self.country = country self.destinations",
"= self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists:",
"'' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def",
"bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48,",
"BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys",
"soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span',",
"destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name]",
"element and enter the country name. \"\"\" try: self.driver.get(self.url) # wait to loading",
"= {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True else: for i",
"= self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc')",
"else: time_spent = '' # add details to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place",
"range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content",
"# write options options = ['no' for key in option_fields] destination = data['Destination']",
"Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) # write options options = ['no'",
"destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url",
"exception occur, try again three times if attempt == 4: return False attempt",
"as f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping':",
"\"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem with destination \",",
"TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self,",
"except Exception as e: if attempt == 2: print(e, \" .3.\") return False",
"from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import",
"of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH,",
"diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing':",
"30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36,",
"popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans == 2:",
"= popularity # tempature if length_of_spans == 2: tempatures = [i.text for i",
"as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import",
"country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination = ''",
"data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f:",
"times if attempt == 4: return False attempt += 1 return self.get_destinations(attempt) except",
"= csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3,",
"= 0 for key, item in self.destinations.items(): if counter % 20 == 0:",
"loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) #",
"51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark':",
"if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country: \") a = GoogleDestination(country)",
"-*- # !/usr/bin/env python # Columbus - Personalised Travel Itineraries based on experience,",
"jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty =",
"time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except",
"= self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name",
"time.sleep(1) # wait to loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\"))",
"click destinations link # wait to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH,",
"attempt = at try: # click the top sight element on menu self.driver.find_element(By.XPATH,",
"BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent =",
"re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans == 2: tempatures =",
"'destination' return False except Exception as e: if attempt == 2: print(e, \"",
"self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = []",
"'/Months.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp',",
"# for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']])",
"20 == 0: # re open browser for memory self.driver.close() self.open_browser() counter +=",
"destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() #",
"time_spent: time_spent = time_spent.find('b').text else: time_spent = '' # add details to dict",
"destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] =",
"= ['Country', 'Destination', 'Things to Do', 'Rating', 'Number of Review', 'Typical Time Spent']",
"== 3: print(\"Problem with destination \", url) return False attempt += 1 return",
"month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country months['Destination'] =",
"'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33,",
"self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False:",
"import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def",
"months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems:",
"BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating = soup.find('span', class_='rtng') if",
"# click destinations link # wait to loading of destinations list destinations_list_present =",
"rating rating = soup.find('span', class_='rtng') if rating: if len(rating) == 2: rating.style.decompose() rating",
"for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if",
"sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala':",
"= {} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination = '' def open_browser(self):",
"elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0:",
"\"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination",
"attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination",
"attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else:",
"EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem please try",
"destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait to loading of",
"BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination months",
"# !/usr/bin/env python # Columbus - Personalised Travel Itineraries based on experience, country",
"= time_spent.find('b').text else: time_spent = '' # add details to dict top_sights_detail['Topsights'][idx] =",
"are no topsight at 'destination' return False except Exception as e: if attempt",
"in enumerate(top_sights): top_sight.click() # click each top sight item by one by try:",
"'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8,",
"len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if",
"else: for i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until",
"guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) # write country end select first result time.sleep(1) # wait",
"re import csv import os import logging from bs4 import BeautifulSoup from selenium",
"'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'],",
"'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40,",
"44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf",
"None: options[idx] = 'yes' # write data for key, items in data['Topsights'].items(): row",
"from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException class GoogleDestination: def __init__(self, country):",
"get_topsgihts_details(self, at=0): attempt = at try: # click the top sight element on",
"option_fields]) writer.writerow(fields) # write options options = ['no' for key in option_fields] destination",
"WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are there any option? options =",
"'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54,",
"EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver,",
"= [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row",
"in self.destinations.items(): if counter % 20 == 0: # re open browser for",
"if file_is_empty: fields = ['Country', 'Destination', 'Things to Do', 'Rating', 'Number of Review',",
"delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4,",
"f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if",
"for key in option_fields]) writer.writerow(fields) # write options options = ['no' for key",
"EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details",
"= {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] =",
"= '' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options)",
"any option? options = self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\") if len(options) == 0: destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for",
"link # wait to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\"))",
"# rating rating = soup.find('span', class_='rtng') if rating: if len(rating) == 2: rating.style.decompose()",
"def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='')",
"= os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Month',",
"# popularity if length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity =",
"open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\"",
"append to list. \"\"\" attempt = at try: # wait to be clickable",
"selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if",
"= [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] #",
"34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer':",
"= self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in",
"get the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html =",
"f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2,",
"False def get_destination_details(self, url, at=0): attempt = at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH,",
"to dict top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number",
"False attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try",
"WebDriverWait(self.driver, 20).until(destination_page_present) return True except TimeoutException: print(\"1. Timeout problem please try again.\") return",
"top_sight.click() # click each top sight item by one by try: # wait",
"tempature if length_of_spans == 2: tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp']",
"4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums':",
"top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top",
"of Reviews'], items['Typical Time Spent']] row += options writer.writerow(row) def run(self): self.open_browser() search",
"temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True except",
"# wait to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver,",
"e: if attempt == 2: print(e, \" .3.\") return False attempt += 1",
"True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True",
"popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans == 2: tempatures = [i.text",
"time import re import csv import os import logging from bs4 import BeautifulSoup",
"file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination',",
"= self.search() if search == True: get_dests = self.get_destinations() if get_dests == True:",
"search == True: get_dests = self.get_destinations() if get_dests == True: counter = 0",
"'Things to Do', 'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key for key",
"destination \", url) return False attempt += 1 return self.get_destination_details(url, attempt) soup =",
"'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant':",
"'Alpine skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0",
"from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import",
"if stale exception occur, try again three times if attempt == 4: return",
"tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1]",
"length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return",
"by try: # wait to loading of the content of top sight top_sight_present",
"NoSuchElementException: # if there are no topsight at 'destination' return False except Exception",
"'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'],",
"'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10,",
"True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break option_name =",
"3: print(\"Problem with destination \", url) return False attempt += 1 return self.get_destination_details(url,",
"top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical",
"file_is_empty = os.stat(path + '/Months.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination',",
"search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\")",
"3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves':",
"months['Months'][month_name]['Precipitation'] = precipitation return months else: return False def get_topsgihts_details(self, at=0): attempt =",
"self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False:",
"i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation if length_of_spans",
"!/usr/bin/env python # Columbus - Personalised Travel Itineraries based on experience, country or",
"= {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] =",
"the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of",
"other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans == 1: popularity = elem.find('span')",
"items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/ThingsToDo.csv',",
"\"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='RrdlOe']\")) WebDriverWait(self.driver, 20).until(destination_page_present)",
"attempt == 4: return False attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2.",
"= {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait",
"destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination months = {}",
"'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing':",
"class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent = '' # add details",
"Keys.ARROW_DOWN) # write country end select first result time.sleep(1) # wait to loading",
"self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name =",
"self.driver.get(self.url) # wait to loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\"))",
"# write data for key, items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place",
"in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url = destination.get_attribute('href')",
"self.destinations.items(): if counter % 20 == 0: # re open browser for memory",
"58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country',",
"months = {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] =",
"= self.get_destinations() if get_dests == True: counter = 0 for key, item in",
"of destinations according to each option and append to list. \"\"\" attempt =",
"= EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee",
"top_sights_detail['Topsights'][idx] = {} top_sights_detail['Topsights'][idx]['Place Name'] = place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews']",
"'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6,",
"months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans == 2: tempatures = [i.text for",
"33, 'Kitesurfing': 34, 'Windsurfing': 35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching':",
"self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True else: for",
"again.\") return False except Exception as e: print(e) return False def get_destination_details(self, url,",
"class_='AofZnb').text # destination name self.current_destination = destination months = {} month_table = soup.find_all('table',",
"\"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link # wait",
"Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the search",
"result time.sleep(1) # wait to loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH,",
"on destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] =",
"occur, try again three times if attempt == 4: return False attempt +=",
"items in data['Topsights'].items(): row = [data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'],",
"if get_dests == True: counter = 0 for key, item in self.destinations.items(): if",
"[data['Country'], data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row +=",
"self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination = '' def open_browser(self): options =",
"time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup = BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div',",
"click each top sight item by one by try: # wait to loading",
"element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException:",
"= {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country",
"6, 'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art':",
"reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19,",
"= re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity # tempature if length_of_spans == 2: tempatures",
"1 return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv',",
"open browser for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details =",
"months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] = {} tr = month_table[1].find_all('tr') for",
"if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML') time_spent_soup =",
"time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent = '' # add",
"= os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields = ['Country', 'Destination', 'Things",
"= ['no' for key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None:",
"o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None: options[idx] = 'yes'",
"on experience, country or preferred destination. # Contact <NAME> <<EMAIL>> # import time",
"try: # wait to be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\"))",
"import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import",
"print(e) return False def get_destinations(self, at=0): \"\"\" Get urls of destinations according to",
"rating.style.decompose() rating = rating.text else: rating = '' # number of reviews number_of_reviews",
"# Columbus - Personalised Travel Itineraries based on experience, country or preferred destination.",
"precipitation if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months",
"= '' months['Months'][month_name]['MinTemp'] = '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem",
"os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f,",
"rating = rating.text else: rating = '' # number of reviews number_of_reviews =",
"= destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing",
"time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected option destination_lists",
"at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt",
"key in option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None: for o in",
"'' # get the details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True:",
"{} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country months['Destination']",
"Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row += options writer.writerow(row) def",
"spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn",
"TimeoutException: if attempt == 3: print(\"Problem with destination \", url) return False attempt",
"Time Spent'] = time_spent # wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\"))",
"= [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while",
"20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano':",
"destination name self.current_destination = destination months = {} month_table = soup.find_all('table', class_='qt3FE') if",
"= BeautifulSoup(time_spent_html,'html.parser') time_spent = time_spent_soup.find('div', class_='UYKlhc') if time_spent: time_spent = time_spent.find('b').text else: time_spent",
"url) return False attempt += 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser')",
"no topsight at 'destination' return False except Exception as e: if attempt ==",
"in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path",
"48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine tasting': 52, 'Climbing':",
"the search input element and enter the country name. \"\"\" try: self.driver.get(self.url) #",
"each option and append to list. \"\"\" attempt = at try: # wait",
"if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else:",
"self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations:",
"'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20,",
"self.current_destination = destination months = {} month_table = soup.find_all('table', class_='qt3FE') if len(month_table) >",
"option_fields] destination = data['Destination'] if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx",
"def search(self): \"\"\" Find the search input element and enter the country name.",
"if length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity",
"time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else: time_spent_html = self.driver.find_element_by_id('gws-trips-desktop__dest-mrgkp').get_attribute('innerHTML')",
"sight top_sight_present = EC.visibility_of_element_located((By.XPATH, \"//div[contains(@class,'au3Yqc')]\")) WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML')",
"if search == True: get_dests = self.get_destinations() if get_dests == True: counter =",
"i in range(len(options)): temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing",
"option_fields = {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor",
"to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) #",
"8, 'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral",
"13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports': 17, 'Wildlife': 18,",
"28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34,",
"> 1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] = {} tr =",
"else: rating = '' # number of reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'})",
"writer.writerow(fields) # for key, items in data['Months'].items(): writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'],",
"'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding': 16, 'Winter sports':",
"= elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] =",
"self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country:",
"try again.\") return False except Exception as e: print(e) return False def get_destinations(self,",
"# click each top sight item by one by try: # wait to",
"if len(month_table) > 1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] = {}",
"os import logging from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options",
"wait to loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present)",
"row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] =",
"content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break",
"= at try: # wait to be clickable of destinations link destinations_elem_present =",
"except TimeoutException: if attempt == 3: print(\"Problem with destination \", url) return False",
"== temp_class_of_content: time.sleep(3) else: break option_name = self.driver.find_element_by_xpath(\"//chip-button[@aria-checked='true']\").find_element_by_class_name(\"gws-travel-controls__chip-label\").get_attribute(\"innerHTML\") # get destinations on selected",
"try: # click the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait",
"sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight",
"sight item by one by try: # wait to loading of the content",
"'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27, 'Scuba diving':",
"items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row += options writer.writerow(row) def run(self):",
"37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar",
"input element and enter the country name. \"\"\" try: self.driver.get(self.url) # wait to",
"to loading of search input element search_input_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem",
"site': 58} file_is_empty = os.stat(path + '/ThingsToDo.csv').st_size == 0 if file_is_empty: fields =",
"attempt += 1 return self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div',",
"'Beaches': 7, 'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art': 12,",
"Spent'] = time_spent # wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver,",
"__init__(self, country): self.country = country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver =",
"TimeoutException: print(\"2. Timeout problem please try again.\") return False except Exception as e:",
"53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic",
"'Number of Review', 'Typical Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields) #",
"True except TimeoutException: print(\"1. Timeout problem please try again.\") return False except Exception",
"writer.writerow([data['Country'], data['Destination'], key, items['Popularity'], items['MinTemp'], items['MaxTemp'], items['Precipitation']]) def write_top_sight(self, data): path = os.path.dirname(os.path.abspath(__file__))",
"# wait to loading of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver,",
"destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return",
"0 if file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields)",
"45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50,",
"Exception as e: print(e) return False def get_destinations(self, at=0): \"\"\" Get urls of",
"link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click",
"self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None",
"= option_fields.get(o) if idx != None: options[idx] = 'yes' # write data for",
"months['Months'] = {} tr = month_table[1].find_all('tr') for row in tr[1:13]: month_name = row.find('td').text",
"get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text # rating rating",
"= '' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans",
"'/Months.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty = os.stat(path",
"True except StaleElementReferenceException: # if stale exception occur, try again three times if",
"WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN) #",
"self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return True except StaleElementReferenceException: #",
"False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with",
"tempatures[1].split(\"/\")[1] # precipitation if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation",
"== 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return months else: return False",
"EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations link #",
"= EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if",
"'Snorkeling': 22, 'Koala': 23, 'Surfing': 24, 'Nature reserve': 25, 'Volcano': 26, 'Sailing': 27,",
"coding: utf-8 -*- # !/usr/bin/env python # Columbus - Personalised Travel Itineraries based",
"changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3)",
"rating: if len(rating) == 2: rating.style.decompose() rating = rating.text else: rating = ''",
"items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row += options writer.writerow(row)",
"= {'Architecture': 0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation':",
"# re open browser for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations)))",
"'Kayaking': 42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan':",
"= self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country: \") a",
"\"//div[@class='gb_Xe']//input\")) WebDriverWait(self.driver, 20).until(search_input_present) input_elem = self.driver.find_element(By.XPATH, \"//div[@class='gb_Xe']//input\") input_elem.click() time.sleep(1) # guarantee input_elem.send_keys(self.country, Keys.ARROW_DOWN)",
"menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading of top sight page of destination",
"class_='qt3FE') if len(month_table) > 1: months['Country'] = self.country months['Destination'] = self.current_destination months['Months'] =",
"from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from",
"of search results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee",
"self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except NoSuchElementException: # if there are no topsight at",
"def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='', encoding='utf-8')",
"open(path + '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',') option_fields",
"'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf':",
"if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' #",
"True: get_dests = self.get_destinations() if get_dests == True: counter = 0 for key,",
"with destination \", url) return False attempt += 1 return self.get_destination_details(url, attempt) soup",
"if destination_name not in self.destinations: destination_url = destination.get_attribute('href') self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] =",
"'a', encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',') option_fields = {'Architecture': 0,",
"self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None: options[idx] = 'yes' # write",
"True: counter = 0 for key, item in self.destinations.items(): if counter % 20",
"except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser')",
"= EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if attempt == 3: print(\"Problem with",
"p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews",
"'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key, items in data['Months'].items():",
"reviews number_of_reviews = soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose()",
"except Exception as e: print(e) return False def get_destinations(self, at=0): \"\"\" Get urls",
"return False def get_destinations(self, at=0): \"\"\" Get urls of destinations according to each",
"destination top_sights_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='w9GWWb']\")) WebDriverWait(self.driver, 20).until(top_sights_list_present) top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all",
"fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for key,",
"17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23,",
"'Destination', 'Things to Do', 'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key for",
"topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter Country: \") a = GoogleDestination(country) a.run()",
"destinations link # wait to loading of destinations list destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c",
"for idx,top_sight in enumerate(top_sights): top_sight.click() # click each top sight item by one",
"at=0): \"\"\" Get urls of destinations according to each option and append to",
"'Camping': 8, 'Caves': 9, 'Museums': 10, 'National Parks': 11, 'Art': 12, 'Desert': 13,",
"'Dolphin': 51, 'Wine tasting': 52, 'Climbing': 53, 'Paragliding': 54, 'Bungee jumping': 55, 'Whale",
"re open browser for memory self.driver.close() self.open_browser() counter += 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details",
"16, 'Winter sports': 17, 'Wildlife': 18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling':",
"{} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination = '' def open_browser(self): options",
"'https://www.google.com/destination' self.driver = '' self.current_destination = '' def open_browser(self): options = Options() options.add_argument(\"--headless\")",
"return False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__))",
"top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to",
"length_of_spans == 2: tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0]",
"42, 'Polar bear': 43, 'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47,",
"top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2', class_='NbdpWc').text #",
"35, 'Birdwatching': 36, 'Rainforest': 37, 'Nightlife': 38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla':",
"'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty",
"soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip()",
"except TimeoutException: print(\"2. Timeout problem please try again.\") return False except Exception as",
"data['Destination'], items['Place Name'], items['Rating'], items['Number of Reviews'], items['Typical Time Spent']] row += options",
"\"\"\" Find the search input element and enter the country name. \"\"\" try:",
"row += options writer.writerow(row) def run(self): self.open_browser() search = self.search() if search ==",
"as e: if attempt == 2: print(e, \" .3.\") return False attempt +=",
"Personalised Travel Itineraries based on experience, country or preferred destination. # Contact <NAME>",
"wait until to changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content",
"EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are there any",
"self.get_topsgihts_details(attempt) def write_month(self, data): path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/Months.csv', 'a', newline='',",
"results menu search_results_present = EC.visibility_of_element_located((By.XPATH, \"//ul[@class='sbsb_b']\")) WebDriverWait(self.driver, 20).until(search_results_present) time.sleep(1) # guarantee input_elem.send_keys(Keys.ENTER) destination_page_present",
"self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True: current_class_of_content =",
"{} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = None return True else: for i in",
"'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name self.current_destination = destination months =",
"# tempature if length_of_spans == 2: tempatures = [i.text for i in elem.find_all('span')]",
"54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic site': 58}",
"length_of_spans == 1: popularity = elem.find('span') if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity =",
"to be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem",
"1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches':",
"'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping': 8, 'Caves': 9,",
"to list. \"\"\" attempt = at try: # wait to be clickable of",
"= place_name top_sights_detail['Topsights'][idx]['Rating'] = rating top_sights_detail['Topsights'][idx]['Number of Reviews'] = number_of_reviews top_sights_detail['Topsights'][idx]['Typical Time Spent']",
"return False except Exception as e: print(e) return False def get_destination_details(self, url, at=0):",
"2: print(e, \" .3.\") return False attempt += 1 return self.get_topsgihts_details(attempt) def write_month(self,",
"'National Parks': 11, 'Art': 12, 'Desert': 13, 'Coral reef': 14, 'Skiing': 15, 'Snowboarding':",
"'' for elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans ==",
"2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure': 6, 'Beaches': 7, 'Camping':",
"Timeout problem please try again.\") return False except Exception as e: print(e) return",
"to each option and append to list. \"\"\" attempt = at try: #",
"'' self.current_destination = '' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver = webdriver.Chrome(chrome_options",
"as e: print(e) return False def get_destination_details(self, url, at=0): attempt = at try:",
"0, 'Nature': 1, 'Shopping': 2, 'Fishing': 3, 'Hiking': 4, 'Outdoor Recreation': 5, 'Adventure':",
"'Paragliding': 54, 'Bungee jumping': 55, 'Whale shark': 56, 'Alpine skiing': 57, 'Historic site':",
"'Whale shark': 56, 'Alpine skiing': 57, 'Historic site': 58} file_is_empty = os.stat(path +",
"# wait until to changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if",
"18, 'Penguin': 19, 'Glacier': 20, 'Ecotourism': 21, 'Snorkeling': 22, 'Koala': 23, 'Surfing': 24,",
"= precipitation return months else: return False def get_topsgihts_details(self, at=0): attempt = at",
"2: number_of_reviews.style.decompose() number_of_reviews = number_of_reviews.text.strip() else: number_of_reviews = '' # get the details",
"top_sights = self.driver.find_element_by_tag_name('ol').find_elements_by_tag_name('li') # get all topsight element on destination top_sights_detail = {}",
"'' months['Months'][month_name]['MaxTemp'] = '' months['Months'][month_name]['Precipitation'] = '' for elem in other_elems: length_of_spans =",
"= {} for idx,top_sight in enumerate(top_sights): top_sight.click() # click each top sight item",
"'Hot spring': 44, 'Tiger': 45, 'Yoga': 46, 'Orangutan': 47, 'Golf': 48, 'Rafting': 49,",
"top_sights_detail['Topsights'][idx]['Typical Time Spent'] = time_spent # wait to close element close_present = EC.element_to_be_clickable((By.TAG_NAME,",
"self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to",
"= webdriver.Chrome(chrome_options = options) def search(self): \"\"\" Find the search input element and",
"get destinations on selected option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name",
"list. \"\"\" attempt = at try: # wait to be clickable of destinations",
"27, 'Scuba diving': 28, 'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos':",
"counter % 20 == 0: # re open browser for memory self.driver.close() self.open_browser()",
"self.destinations[destination_name] = {} self.destinations[destination_name]['URL'] = destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) #",
"StaleElementReferenceException: # if stale exception occur, try again three times if attempt ==",
"+= 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please try again.\") return",
"other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] = {} months['Months'][month_name]['Popularity'] = '' months['Months'][month_name]['MinTemp'] = ''",
"return False attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout problem please",
"[i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] = tempatures[1].split(\"/\")[1] # precipitation",
"click the top sight element on menu self.driver.find_element(By.XPATH, \"//li[@id='TOP_SIGHTS']\").find_element_by_tag_name('a').click() # wait to loading",
"False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details != False: self.write_top_sight(topsight_details) country = input(\"Enter",
"- Personalised Travel Itineraries based on experience, country or preferred destination. # Contact",
"at try: # wait to be clickable of destinations link destinations_elem_present = EC.element_to_be_clickable((By.XPATH,",
"destination_url self.destinations[destination_name]['Options'] = [] self.destinations[destination_name]['Options'].append(option_name) self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of",
"= soup.find('span', attrs={'class':'Vfp4xe p13zmc'}) if number_of_reviews: if len(number_of_reviews) == 2: number_of_reviews.style.decompose() number_of_reviews =",
"time.sleep(1) # wait until to changing of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\")",
"option destination_lists = self.driver.find_elements_by_xpath(\"//a[@class='sjglme']\") for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name",
"= '' self.current_destination = '' def open_browser(self): options = Options() options.add_argument(\"--headless\") self.driver =",
"to changing of content while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content:",
"'Theaters': 29, 'Elephant': 30, 'Safari': 31, 'Jaguar': 32, 'Casinos': 33, 'Kitesurfing': 34, 'Windsurfing':",
"dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details = self.get_topsgihts_details() if topsight_details",
"destinations_elem_present = EC.element_to_be_clickable((By.XPATH, \"//li[@id='DESTINATIONS']\")) WebDriverWait(self.driver, 20).until(destinations_elem_present) destinations_elem = self.driver.find_element(By.XPATH, \"//li[@id='DESTINATIONS']\").find_element_by_tag_name('a').click() # click destinations",
"2: tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] = tempatures[0] months['Months'][month_name]['MinTemp'] =",
"top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights): top_sight.click() # click each top sight",
"file_is_empty: fields = ['Country', 'Destination', 'Month', 'Popularity', 'MinTemp', 'MaxTemp', 'Precipitation'] writer.writerow(fields) # for",
"= at try: self.driver.get(url) destination_detail_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='AofZnb']\")) WebDriverWait(self.driver, 20).until(destination_detail_present) except TimeoutException: if",
"self.get_destination_details(url, attempt) soup = BeautifulSoup(self.driver.page_source, 'html.parser') destination = soup.find('div', class_='AofZnb').text # destination name",
"'Orangutan': 47, 'Golf': 48, 'Rafting': 49, 'Autumn leaf color': 50, 'Dolphin': 51, 'Wine",
"the country name. \"\"\" try: self.driver.get(self.url) # wait to loading of search input",
"WebDriverWait(self.driver, 20).until(top_sight_present) except TimeoutException: continue top_sight_html = top_sight.get_attribute('innerHTML') # get details soup =",
"if popularity.has_attr('aria-label'): popularity = elem.find('span')['aria-label'] popularity = re.findall(r'\\d+\\.\\d+|\\d+', popularity)[0] months['Months'][month_name]['Popularity'] = popularity #",
"self.driver.find_element_by_xpath(\"//span[@class='irTQQe']\").find_elements_by_tag_name(\"chip-button\")[i].click() time.sleep(1) # wait until to changing of content while True: temp_class_of_content =",
"# wait to loading of the content of top sight top_sight_present = EC.visibility_of_element_located((By.XPATH,",
"'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43, 'Hot",
"top_sight_html = top_sight.get_attribute('innerHTML') # get details soup = BeautifulSoup(top_sight_html, 'html.parser') place_name = soup.find('h2',",
"'Rating', 'Number of Review', 'Typical Time Spent'] fields.extend([key for key in option_fields]) writer.writerow(fields)",
"== 0: # re open browser for memory self.driver.close() self.open_browser() counter += 1",
"Travel Itineraries based on experience, country or preferred destination. # Contact <NAME> <<EMAIL>>",
"\"\"\" try: self.driver.get(self.url) # wait to loading of search input element search_input_present =",
"while True: temp_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else: break return",
"if length_of_spans == 2: tempatures = [i.text for i in elem.find_all('span')] months['Months'][month_name]['MaxTemp'] =",
"for destination in destination_lists: destination_name = destination.find_element_by_tag_name(\"h2\").get_attribute('innerHTML') if destination_name not in self.destinations: destination_url",
"options writer.writerow(row) def run(self): self.open_browser() search = self.search() if search == True: get_dests",
"38, 'Whale watching': 39, 'Reindeer': 40, 'Gorilla': 41, 'Kayaking': 42, 'Polar bear': 43,",
"self.country = country self.destinations = {} self.url = 'https://www.google.com/destination' self.driver = '' self.current_destination",
"top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight in enumerate(top_sights):",
"# precipitation if length_of_spans == 0: precipitation = elem.text months['Months'][month_name]['Precipitation'] = precipitation return",
"+ '/Months.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f, delimiter=',') file_is_empty =",
"+= 1 print('{}/{}'.format(counter, len(self.destinations))) dest_details = self.get_destination_details(item['URL']) if dest_details != False: self.write_month(dest_details) topsight_details",
"destination. # Contact <NAME> <<EMAIL>> # import time import re import csv import",
"= {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {} for idx,top_sight",
"details of typical time spent if self.driver.find_element_by_tag_name('async-local-kp').is_displayed() == True: time_spent_html = self.driver.find_element_by_tag_name('async-local-kp').get_attribute('innerHTML') else:",
"for elem in other_elems: length_of_spans = len(elem.find_all('span')) # popularity if length_of_spans == 1:",
"# import time import re import csv import os import logging from bs4",
"destination top_sights_detail = {} top_sights_detail['Country'] = self.country top_sights_detail['Destination'] = self.current_destination top_sights_detail['Topsights'] = {}",
"key, item in self.destinations.items(): if counter % 20 == 0: # re open",
"None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if idx != None: options[idx]",
"of content while True: current_class_of_content = self.driver.find_element_by_xpath(\"//div[contains(@class,'LOIWPe')]\").get_attribute(\"class\") if current_class_of_content == temp_class_of_content: time.sleep(3) else:",
"== 4: return False attempt += 1 return self.get_destinations(attempt) except TimeoutException: print(\"2. Timeout",
"for row in tr[1:13]: month_name = row.find('td').text other_elems = row.find_all('td', class_='qRa1yd') months['Months'][month_name] =",
"return False def get_topsgihts_details(self, at=0): attempt = at try: # click the top",
"destinations_list_present = EC.visibility_of_element_located((By.XPATH, \"//div[@class='BvC61c RrdlOe']\")) WebDriverWait(self.driver, 20).until(destinations_list_present) # maybe if block for are",
"2: rating.style.decompose() rating = rating.text else: rating = '' # number of reviews",
"if time_spent: time_spent = time_spent.find('b').text else: time_spent = '' # add details to",
"close element close_present = EC.element_to_be_clickable((By.TAG_NAME, \"g-fab\")) WebDriverWait(self.driver, 20).until(close_present) self.driver.find_element_by_tag_name('g-fab').click() time.sleep(1) return top_sights_detail except",
"+ '/ThingsToDo.csv', 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f, delimiter=',') option_fields =",
"data['Destination'] if self.destinations[destination]['Options'] != None: for o in self.destinations[destination]['Options']: idx = option_fields.get(o) if",
"by one by try: # wait to loading of the content of top",
"= 'https://www.google.com/destination' self.driver = '' self.current_destination = '' def open_browser(self): options = Options()",
"# write country end select first result time.sleep(1) # wait to loading of"
] |
[
"print('entering...') if request.method == 'GET': # if the user has not yet been",
"None: print('1') return redirect(url_for('welcome.index')) # if the user already complete the welcome setup",
"current_user from flask_security import login_required login_check = Blueprint( 'login_check', __name__, ) ############################# #",
"or user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if the user already complete",
"login_check = Blueprint( 'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required",
"from flask import Blueprint, render_template, redirect, url_for, flash, request from solarvibes import db",
"complete the welcome setup if user.completed_welcome: print('2') return redirect(url_for('main.index')) else: print('3') return redirect(url_for('welcome.index'))",
"Blueprint( 'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index():",
"index(): user = current_user print('entering...') if request.method == 'GET': # if the user",
"is the first time he logs in if not user.completed_welcome or user.login_count ==",
"@login_required def index(): user = current_user print('entering...') if request.method == 'GET': # if",
"import current_user from flask_security import login_required login_check = Blueprint( 'login_check', __name__, ) #############################",
"logged in!') return redirect(url_for('login')) # if the user is authenticated if user.is_authenticated: #",
"== 'GET': # if the user has not yet been authenticated -> goto",
"yet been authenticated -> goto login if user.is_anonymous: print('you must be logged in!')",
"not user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if the user",
"# INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user = current_user print('entering...') if",
"############################# @login_check.route('/', methods=['GET']) @login_required def index(): user = current_user print('entering...') if request.method ==",
"login if user.is_anonymous: print('you must be logged in!') flash('you must be logged in!')",
"request from solarvibes import db from flask_login import current_user from flask_security import login_required",
"# if the user is authenticated if user.is_authenticated: # if is the first",
"return redirect(url_for('welcome.index')) # if the user already complete the welcome setup if user.completed_welcome:",
"authenticated if user.is_authenticated: # if is the first time he logs in if",
"__name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user =",
"user.is_authenticated: # if is the first time he logs in if not user.completed_welcome",
"has not yet been authenticated -> goto login if user.is_anonymous: print('you must be",
"== None: print('1') return redirect(url_for('welcome.index')) # if the user already complete the welcome",
"in if not user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if",
"= Blueprint( 'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def",
"the user already complete the welcome setup if user.completed_welcome: print('2') return redirect(url_for('main.index')) else:",
"############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user = current_user print('entering...')",
"if user.is_anonymous: print('you must be logged in!') flash('you must be logged in!') return",
"'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user",
"request.method == 'GET': # if the user has not yet been authenticated ->",
"in!') flash('you must be logged in!') return redirect(url_for('login')) # if the user is",
"be logged in!') flash('you must be logged in!') return redirect(url_for('login')) # if the",
"user = current_user print('entering...') if request.method == 'GET': # if the user has",
"if not user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if the",
"flask_security import login_required login_check = Blueprint( 'login_check', __name__, ) ############################# # INDEX #############################",
"from flask_security import login_required login_check = Blueprint( 'login_check', __name__, ) ############################# # INDEX",
"user.is_anonymous: print('you must be logged in!') flash('you must be logged in!') return redirect(url_for('login'))",
"redirect, url_for, flash, request from solarvibes import db from flask_login import current_user from",
"been authenticated -> goto login if user.is_anonymous: print('you must be logged in!') flash('you",
"redirect(url_for('login')) # if the user is authenticated if user.is_authenticated: # if is the",
"# if the user has not yet been authenticated -> goto login if",
"flask import Blueprint, render_template, redirect, url_for, flash, request from solarvibes import db from",
"url_for, flash, request from solarvibes import db from flask_login import current_user from flask_security",
"flash, request from solarvibes import db from flask_login import current_user from flask_security import",
"Blueprint, render_template, redirect, url_for, flash, request from solarvibes import db from flask_login import",
"authenticated -> goto login if user.is_anonymous: print('you must be logged in!') flash('you must",
"# if the user already complete the welcome setup if user.completed_welcome: print('2') return",
"if the user has not yet been authenticated -> goto login if user.is_anonymous:",
"logged in!') flash('you must be logged in!') return redirect(url_for('login')) # if the user",
"user has not yet been authenticated -> goto login if user.is_anonymous: print('you must",
"<filename>app/solarvibes/login_check/views.py from flask import Blueprint, render_template, redirect, url_for, flash, request from solarvibes import",
"if the user is authenticated if user.is_authenticated: # if is the first time",
") ############################# # INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user = current_user",
"def index(): user = current_user print('entering...') if request.method == 'GET': # if the",
"'GET': # if the user has not yet been authenticated -> goto login",
"if request.method == 'GET': # if the user has not yet been authenticated",
"import db from flask_login import current_user from flask_security import login_required login_check = Blueprint(",
"current_user print('entering...') if request.method == 'GET': # if the user has not yet",
"first time he logs in if not user.completed_welcome or user.login_count == None: print('1')",
"= current_user print('entering...') if request.method == 'GET': # if the user has not",
"user is authenticated if user.is_authenticated: # if is the first time he logs",
"he logs in if not user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index'))",
"flask_login import current_user from flask_security import login_required login_check = Blueprint( 'login_check', __name__, )",
"import Blueprint, render_template, redirect, url_for, flash, request from solarvibes import db from flask_login",
"the first time he logs in if not user.completed_welcome or user.login_count == None:",
"if is the first time he logs in if not user.completed_welcome or user.login_count",
"flash('you must be logged in!') return redirect(url_for('login')) # if the user is authenticated",
"logs in if not user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index')) #",
"not yet been authenticated -> goto login if user.is_anonymous: print('you must be logged",
"in!') return redirect(url_for('login')) # if the user is authenticated if user.is_authenticated: # if",
"the user is authenticated if user.is_authenticated: # if is the first time he",
"print('you must be logged in!') flash('you must be logged in!') return redirect(url_for('login')) #",
"if the user already complete the welcome setup if user.completed_welcome: print('2') return redirect(url_for('main.index'))",
"@login_check.route('/', methods=['GET']) @login_required def index(): user = current_user print('entering...') if request.method == 'GET':",
"be logged in!') return redirect(url_for('login')) # if the user is authenticated if user.is_authenticated:",
"must be logged in!') return redirect(url_for('login')) # if the user is authenticated if",
"time he logs in if not user.completed_welcome or user.login_count == None: print('1') return",
"goto login if user.is_anonymous: print('you must be logged in!') flash('you must be logged",
"solarvibes import db from flask_login import current_user from flask_security import login_required login_check =",
"from solarvibes import db from flask_login import current_user from flask_security import login_required login_check",
"must be logged in!') flash('you must be logged in!') return redirect(url_for('login')) # if",
"methods=['GET']) @login_required def index(): user = current_user print('entering...') if request.method == 'GET': #",
"if user.is_authenticated: # if is the first time he logs in if not",
"redirect(url_for('welcome.index')) # if the user already complete the welcome setup if user.completed_welcome: print('2')",
"from flask_login import current_user from flask_security import login_required login_check = Blueprint( 'login_check', __name__,",
"user.completed_welcome or user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if the user already",
"print('1') return redirect(url_for('welcome.index')) # if the user already complete the welcome setup if",
"import login_required login_check = Blueprint( 'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/',",
"the user has not yet been authenticated -> goto login if user.is_anonymous: print('you",
"user.login_count == None: print('1') return redirect(url_for('welcome.index')) # if the user already complete the",
"-> goto login if user.is_anonymous: print('you must be logged in!') flash('you must be",
"db from flask_login import current_user from flask_security import login_required login_check = Blueprint( 'login_check',",
"return redirect(url_for('login')) # if the user is authenticated if user.is_authenticated: # if is",
"# if is the first time he logs in if not user.completed_welcome or",
"INDEX ############################# @login_check.route('/', methods=['GET']) @login_required def index(): user = current_user print('entering...') if request.method",
"login_required login_check = Blueprint( 'login_check', __name__, ) ############################# # INDEX ############################# @login_check.route('/', methods=['GET'])",
"user already complete the welcome setup if user.completed_welcome: print('2') return redirect(url_for('main.index')) else: print('3')",
"render_template, redirect, url_for, flash, request from solarvibes import db from flask_login import current_user",
"already complete the welcome setup if user.completed_welcome: print('2') return redirect(url_for('main.index')) else: print('3') return",
"is authenticated if user.is_authenticated: # if is the first time he logs in"
] |
[
"-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations",
"[ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation",
"relation is present'), ('NO', 'No relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped",
"preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No",
"default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No relation present'),",
"null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No relation present'), ('NS',",
"'Evidence is nonsense'), ('SK', 'Skipped labeling of this evidence') ] ), ), ]",
"migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is",
"('YE', 'Yes, relation is present'), ('NO', 'No relation present'), ('NS', 'Evidence is nonsense'),",
"= [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes,",
"('NO', 'No relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of this",
"coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class",
"import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus',",
"] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[",
"model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'),",
"present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of this evidence') ] ),",
"unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'),",
"-*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies",
"Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label',",
"field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No relation",
"present'), ('NO', 'No relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of",
"from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ]",
"('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of this evidence') ] ), ),",
"name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO',",
"max_length=2, choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No relation present'), ('NS', 'Evidence",
"models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [",
"= [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField(",
"from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies =",
"choices=[ ('YE', 'Yes, relation is present'), ('NO', 'No relation present'), ('NS', 'Evidence is",
"'Yes, relation is present'), ('NO', 'No relation present'), ('NS', 'Evidence is nonsense'), ('SK',",
"__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [",
"'0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2,",
"class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel',",
"'No relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of this evidence')",
"relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling of this evidence') ]",
"django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations",
"dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True,",
"is present'), ('NO', 'No relation present'), ('NS', 'Evidence is nonsense'), ('SK', 'Skipped labeling",
"('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True,",
"utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):",
"import models, migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations =",
"[ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK',",
"operations = [ migrations.AlterField( model_name='evidencelabel', name='label', preserve_default=True, field=models.CharField( default='SK', null=True, max_length=2, choices=[ ('YE',",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models,",
"migrations class Migration(migrations.Migration): dependencies = [ ('corpus', '0002_data_migration_dont_know_skip_merge'), ] operations = [ migrations.AlterField("
] |
[
"-*- coding: utf-8 -*- # Form implementation generated from reading ui file 'response_info.ui',",
"by: pyside2-uic running on PySide2 5.12.1 # # WARNING! All changes made in",
"Created: Sun Feb 17 10:16:18 2019 # by: pyside2-uic running on PySide2 5.12.1",
"0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time =",
"implementation generated from reading ui file 'response_info.ui', # licensing of 'response_info.ui' applies. #",
"self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo) QtCore.QMetaObject.connectSlotsByName(ResponseInfo) def retranslateUi(self, ResponseInfo):",
"licensing of 'response_info.ui' applies. # # Created: Sun Feb 17 10:16:18 2019 #",
"WARNING! All changes made in this file will be lost! from PySide2 import",
"def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth())",
"self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)",
"coding: utf-8 -*- # Form implementation generated from reading ui file 'response_info.ui', #",
"-*- # Form implementation generated from reading ui file 'response_info.ui', # licensing of",
"self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\")",
"28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5)",
"ui file 'response_info.ui', # licensing of 'response_info.ui' applies. # # Created: Sun Feb",
"this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object):",
"QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\")",
"self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40,",
"PySide2 5.12.1 # # WARNING! All changes made in this file will be",
"# WARNING! All changes made in this file will be lost! from PySide2",
"spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo) QtCore.QMetaObject.connectSlotsByName(ResponseInfo) def retranslateUi(self, ResponseInfo): pass",
"# # Created: Sun Feb 17 10:16:18 2019 # by: pyside2-uic running on",
"self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo) QtCore.QMetaObject.connectSlotsByName(ResponseInfo) def",
"import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy",
"file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def",
"0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\")",
"-1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0,",
"utf-8 -*- # Form implementation generated from reading ui file 'response_info.ui', # licensing",
"changes made in this file will be lost! from PySide2 import QtCore, QtGui,",
"5.12.1 # # WARNING! All changes made in this file will be lost!",
"'response_info.ui' applies. # # Created: Sun Feb 17 10:16:18 2019 # by: pyside2-uic",
"self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\")",
"self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\")",
"running on PySide2 5.12.1 # # WARNING! All changes made in this file",
"lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\")",
"setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy)",
"be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo):",
"self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo) QtCore.QMetaObject.connectSlotsByName(ResponseInfo) def retranslateUi(self,",
"= QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\")",
"QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem =",
"ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout =",
"QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType",
"# licensing of 'response_info.ui' applies. # # Created: Sun Feb 17 10:16:18 2019",
"ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout",
"# -*- coding: utf-8 -*- # Form implementation generated from reading ui file",
"# Form implementation generated from reading ui file 'response_info.ui', # licensing of 'response_info.ui'",
"'response_info.ui', # licensing of 'response_info.ui' applies. # # Created: Sun Feb 17 10:16:18",
"self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo)",
"Form implementation generated from reading ui file 'response_info.ui', # licensing of 'response_info.ui' applies.",
"# by: pyside2-uic running on PySide2 5.12.1 # # WARNING! All changes made",
"10:16:18 2019 # by: pyside2-uic running on PySide2 5.12.1 # # WARNING! All",
"17 10:16:18 2019 # by: pyside2-uic running on PySide2 5.12.1 # # WARNING!",
"pyside2-uic running on PySide2 5.12.1 # # WARNING! All changes made in this",
"# # WARNING! All changes made in this file will be lost! from",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode",
"will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self,",
"= QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem",
"self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5)",
"Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"on PySide2 5.12.1 # # WARNING! All changes made in this file will",
"All changes made in this file will be lost! from PySide2 import QtCore,",
"file 'response_info.ui', # licensing of 'response_info.ui' applies. # # Created: Sun Feb 17",
"self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,",
"= QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\")",
"QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem) self.retranslateUi(ResponseInfo) QtCore.QMetaObject.connectSlotsByName(ResponseInfo)",
"self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time",
"QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0)",
"made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6,",
"reading ui file 'response_info.ui', # licensing of 'response_info.ui' applies. # # Created: Sun",
"of 'response_info.ui' applies. # # Created: Sun Feb 17 10:16:18 2019 # by:",
"2019 # by: pyside2-uic running on PySide2 5.12.1 # # WARNING! All changes",
"from PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102,",
"QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy =",
"applies. # # Created: Sun Feb 17 10:16:18 2019 # by: pyside2-uic running",
"PySide2 import QtCore, QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28)",
"self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType)",
"self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\")",
"QtGui, QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1,",
"generated from reading ui file 'response_info.ui', # licensing of 'response_info.ui' applies. # #",
"sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode =",
"in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class",
"ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo) self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo)",
"QtWidgets class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)",
"class Ui_ResponseInfo(object): def setupUi(self, ResponseInfo): ResponseInfo.setObjectName(\"ResponseInfo\") ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0)",
"self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20,",
"# Created: Sun Feb 17 10:16:18 2019 # by: pyside2-uic running on PySide2",
"= QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time)",
"ResponseInfo.resize(102, 28) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(ResponseInfo.sizePolicy().hasHeightForWidth()) ResponseInfo.setSizePolicy(sizePolicy) self.reqStatusLayout = QtWidgets.QHBoxLayout(ResponseInfo)",
"self.reqStatusLayout.setSpacing(5) self.reqStatusLayout.setContentsMargins(6, 0, -1, 0) self.reqStatusLayout.setObjectName(\"reqStatusLayout\") self.statusCode = QtWidgets.QLabel(ResponseInfo) self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode)",
"self.contentType = QtWidgets.QLabel(ResponseInfo) self.contentType.setText(\"\") self.contentType.setObjectName(\"contentType\") self.reqStatusLayout.addWidget(self.contentType) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.reqStatusLayout.addItem(spacerItem)",
"Sun Feb 17 10:16:18 2019 # by: pyside2-uic running on PySide2 5.12.1 #",
"Feb 17 10:16:18 2019 # by: pyside2-uic running on PySide2 5.12.1 # #",
"self.statusCode.setStyleSheet(\"\") self.statusCode.setText(\"\") self.statusCode.setObjectName(\"statusCode\") self.reqStatusLayout.addWidget(self.statusCode) self.time = QtWidgets.QLabel(ResponseInfo) self.time.setText(\"\") self.time.setMargin(5) self.time.setObjectName(\"time\") self.reqStatusLayout.addWidget(self.time) self.contentType =",
"from reading ui file 'response_info.ui', # licensing of 'response_info.ui' applies. # # Created:"
] |
[
"print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme in",
"\" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of",
"rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue",
"len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\",",
"link) else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) #",
"\" \"(approx.)\" ) def spider(self, site): \"\"\" grabs all the outgoing links from",
"tasks from bs4 import BeautifulSoup as soup from pprint import pprint # Command",
"len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links),",
"feed a bunch of content into the site # This will go to",
"# pprint(all_links) # return all_links for link in self.all_links: if link not in",
"rss_links = [] spidered = [] max_links = 500 max_feeds = 500 help",
"find class Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds \"\"\" all_links =",
"start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url')",
"except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for",
"RSS\" \"feeds to process \" \"(approx.)\" ) def spider(self, site): \"\"\" grabs all",
"\"\"\" Spider a bunch o' goddam feeds \"\"\" all_links = [] rss_links =",
"import urllib.parse import feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed",
") def spider(self, site): \"\"\" grabs all the outgoing links from a site",
"spider(self, site): \"\"\" grabs all the outgoing links from a site \"\"\" #",
"self.spidered: self.spider(link) def handle(self, *args, **options): start = time.time() print(options) self.max_links = options.get('max_links')",
"if purl.netloc != rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\",",
"urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and",
"\"(approx.)\" ) def spider(self, site): \"\"\" grabs all the outgoing links from a",
"try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme in ['http',",
"from django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser import tasks",
"bs4 import BeautifulSoup as soup from pprint import pprint # Command to feed",
"spidered = [] max_links = 500 max_feeds = 500 help = 'Add feeds",
"urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(),",
"<filename>xfeeds/management/commands/seed.py<gh_stars>0 import time import urllib.parse import feedparser from django.core.management.base import BaseCommand, CommandError from",
"= html.find_all('a') links = [link.get('href') for link in alist] for link in links:",
"seeder site' def add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links',",
"link in alist] for link in links: # print(link) try: purl = urllib.parse.urlparse(link)",
"purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue except: continue finally:",
"url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in",
"url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception",
"print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds in",
"site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist",
"for link in links: # print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc !=",
"site): \"\"\" grabs all the outgoing links from a site \"\"\" # print(\"Spidering\",",
"links = [link.get('href') for link in alist] for link in links: # print(link)",
"grabs all the outgoing links from a site \"\"\" # print(\"Spidering\", site) if",
"= options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered",
"finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds in {}",
"all_links for link in self.all_links: if link not in self.spidered: self.spider(link) def handle(self,",
"django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser import tasks from",
"number of RSS\" \"feeds to process \" \"(approx.)\" ) def spider(self, site): \"\"\"",
"= 'Add feeds starting with a seeder site' def add_arguments(self, parser): \"\"\" Build",
"it can find class Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds \"\"\"",
"parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500,",
"\"feeds to process \" \"(approx.)\" ) def spider(self, site): \"\"\" grabs all the",
"'Add feeds starting with a seeder site' def add_arguments(self, parser): \"\"\" Build argument",
"links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number",
"self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url)",
"feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser import",
"will go to a seeder page, and spider the first # 100 feeds",
"500 max_feeds = 500 help = 'Add feeds starting with a seeder site'",
"spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds",
"and spider the first # 100 feeds it can find class Command(BaseCommand): \"\"\"",
"in alist] for link in links: # print(link) try: purl = urllib.parse.urlparse(link) if",
"continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links",
"pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links",
"type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of links \" \"to spider",
"import Feed from xfeeds.parser import tasks from bs4 import BeautifulSoup as soup from",
"parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of links",
"number of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500,",
"import pprint # Command to feed a bunch of content into the site",
"(approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds to",
"html.find_all('a') links = [link.get('href') for link in alist] for link in links: #",
"This will go to a seeder page, and spider the first # 100",
"pprint(all_links) # return all_links for link in self.all_links: if link not in self.spidered:",
"\"\"\" grabs all the outgoing links from a site \"\"\" # print(\"Spidering\", site)",
"self.all_links: if link not in self.spidered: self.spider(link) def handle(self, *args, **options): start =",
"from xfeeds.parser import tasks from bs4 import BeautifulSoup as soup from pprint import",
"parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of links \" \"to spider (approx.)\"",
"a bunch o' goddam feeds \"\"\" all_links = [] rss_links = [] spidered",
"\"\"\" all_links = [] rss_links = [] spidered = [] max_links = 500",
"= urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link)",
"link not in self.spidered: self.spider(link) def handle(self, *args, **options): start = time.time() print(options)",
"o' goddam feeds \"\"\" all_links = [] rss_links = [] spidered = []",
"\"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl",
"print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e:",
") parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds to process",
"# Command to feed a bunch of content into the site # This",
"for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e))",
"dest='max_links', type=int, default=500, help=\"Maximum number of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds',",
"a bunch of content into the site # This will go to a",
"from pprint import pprint # Command to feed a bunch of content into",
"> self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site)",
"print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\", url)",
"parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return",
"'html.parser') except: return alist = html.find_all('a') links = [link.get('href') for link in alist]",
"parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of links \" \"to",
"for link in self.all_links: if link not in self.spidered: self.spider(link) def handle(self, *args,",
"of content into the site # This will go to a seeder page,",
"# return all_links for link in self.all_links: if link not in self.spidered: self.spider(link)",
"help = 'Add feeds starting with a seeder site' def add_arguments(self, parser): \"\"\"",
"xfeeds.parser import tasks from bs4 import BeautifulSoup as soup from pprint import pprint",
"print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site)",
"self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish",
"xfeeds.models import Feed from xfeeds.parser import tasks from bs4 import BeautifulSoup as soup",
"import time import urllib.parse import feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models",
"{} RSS feeds in {} seconds\" .format(len(self.rss_links), finish - start)) for feed in",
"into the site # This will go to a seeder page, and spider",
"bunch of content into the site # This will go to a seeder",
"= urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site,",
"['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue except: continue finally: print(\"{} Processed",
"Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number",
"alist] for link in links: # print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc",
"site # This will go to a seeder page, and spider the first",
"to feed a bunch of content into the site # This will go",
"\\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue except: continue",
"[] rss_links = [] spidered = [] max_links = 500 max_feeds = 500",
"BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser import tasks from bs4 import",
"for link in alist] for link in links: # print(link) try: purl =",
"purl.netloc != rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link)",
"in self.all_links: if link not in self.spidered: self.spider(link) def handle(self, *args, **options): start",
"urllib.parse import feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed from",
"# print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme",
"return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist =",
"print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for link in self.all_links:",
"= [link.get('href') for link in alist] for link in links: # print(link) try:",
"can find class Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds \"\"\" all_links",
"max_feeds = 500 help = 'Add feeds starting with a seeder site' def",
"link in links: # print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc",
"dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds to process \" \"(approx.)\" )",
"the outgoing links from a site \"\"\" # print(\"Spidering\", site) if len(self.all_links) >",
"options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site",
"Command to feed a bunch of content into the site # This will",
"outgoing links from a site \"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links:",
"type=int, default=500, help=\"Maximum number of RSS\" \"feeds to process \" \"(approx.)\" ) def",
"alist = html.find_all('a') links = [link.get('href') for link in alist] for link in",
"pprint import pprint # Command to feed a bunch of content into the",
"feeds starting with a seeder site' def add_arguments(self, parser): \"\"\" Build argument parser",
"[] spidered = [] max_links = 500 max_feeds = 500 help = 'Add",
"self.all_links.append(link) and print(\"added\", link) else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc))",
"= time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting",
"def handle(self, *args, **options): start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds =",
"Spider a bunch o' goddam feeds \"\"\" all_links = [] rss_links = []",
"print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links), finish - start)) for feed",
"# print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl =",
"import BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser import tasks from bs4",
"argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of",
"of RSS\" \"feeds to process \" \"(approx.)\" ) def spider(self, site): \"\"\" grabs",
"except: return alist = html.find_all('a') links = [link.get('href') for link in alist] for",
"try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links)",
"\"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\"",
"continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for link",
"to process \" \"(approx.)\" ) def spider(self, site): \"\"\" grabs all the outgoing",
"in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue except: continue finally: print(\"{}",
"to a seeder page, and spider the first # 100 feeds it can",
"feeds it can find class Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds",
"from a site \"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\")",
"if link not in self.spidered: self.spider(link) def handle(self, *args, **options): start = time.time()",
"[] max_links = 500 max_feeds = 500 help = 'Add feeds starting with",
"finish = time.time() print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links), finish -",
"except Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish =",
"help=\"Maximum number of RSS\" \"feeds to process \" \"(approx.)\" ) def spider(self, site):",
"\"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum number of links \"",
"Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for link in self.all_links: if",
"options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try:",
"feeds \"\"\" all_links = [] rss_links = [] spidered = [] max_links =",
"= 500 max_feeds = 500 help = 'Add feeds starting with a seeder",
"CommandError from xfeeds.models import Feed from xfeeds.parser import tasks from bs4 import BeautifulSoup",
"handle(self, *args, **options): start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds')",
"**options): start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url =",
"return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try:",
"purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\ purl.scheme in ['http', 'https']:",
"self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a')",
"= soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links = [link.get('href') for",
"as soup from pprint import pprint # Command to feed a bunch of",
"starting with a seeder site' def add_arguments(self, parser): \"\"\" Build argument parser \"\"\"",
"*args, **options): start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url",
"Feed from xfeeds.parser import tasks from bs4 import BeautifulSoup as soup from pprint",
"default=500, help=\"Maximum number of RSS\" \"feeds to process \" \"(approx.)\" ) def spider(self,",
"Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds \"\"\" all_links = [] rss_links",
"= time.time() print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links), finish - start))",
"BeautifulSoup as soup from pprint import pprint # Command to feed a bunch",
"self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return",
"time.time() print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links), finish - start)) for",
"pprint # Command to feed a bunch of content into the site #",
"add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int,",
"self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links))",
"100 feeds it can find class Command(BaseCommand): \"\"\" Spider a bunch o' goddam",
"with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except",
"= [] max_links = 500 max_feeds = 500 help = 'Add feeds starting",
"e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {}",
"first # 100 feeds it can find class Command(BaseCommand): \"\"\" Spider a bunch",
"{}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for link in self.all_links: if link",
"return alist = html.find_all('a') links = [link.get('href') for link in alist] for link",
"if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't",
"def spider(self, site): \"\"\" grabs all the outgoing links from a site \"\"\"",
"try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html",
"print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except:",
"= options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links:",
"rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html =",
"= [] spidered = [] max_links = 500 max_feeds = 500 help =",
"RSS feeds in {} seconds\" .format(len(self.rss_links), finish - start)) for feed in self.rss_links:",
"a seeder page, and spider the first # 100 feeds it can find",
"sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site)",
"except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered) try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser')",
"# 100 feeds it can find class Command(BaseCommand): \"\"\" Spider a bunch o'",
"max_links = 500 max_feeds = 500 help = 'Add feeds starting with a",
"soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links = [link.get('href') for link",
"Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time()",
"import feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models import Feed from xfeeds.parser",
"= 500 help = 'Add feeds starting with a seeder site' def add_arguments(self,",
"'-l', dest='max_links', type=int, default=500, help=\"Maximum number of links \" \"to spider (approx.)\" )",
"purl.netloc)) # pprint(all_links) # return all_links for link in self.all_links: if link not",
"seeder page, and spider the first # 100 feeds it can find class",
"\"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links', type=int, default=500, help=\"Maximum",
"type=int, default=500, help=\"Maximum number of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f',",
"time.time() print(options) self.max_links = options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\",",
"all_links = [] rss_links = [] spidered = [] max_links = 500 max_feeds",
"default=500, help=\"Maximum number of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds',",
"the first # 100 feeds it can find class Command(BaseCommand): \"\"\" Spider a",
"of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum",
"try: html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links =",
"from bs4 import BeautifulSoup as soup from pprint import pprint # Command to",
"[link.get('href') for link in alist] for link in links: # print(link) try: purl",
"links: # print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and \\",
"self.spider(link) def handle(self, *args, **options): start = time.time() print(options) self.max_links = options.get('max_links') self.max_feeds",
"import tasks from bs4 import BeautifulSoup as soup from pprint import pprint #",
"print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds in {} seconds\"",
"time import urllib.parse import feedparser from django.core.management.base import BaseCommand, CommandError from xfeeds.models import",
"'-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds to process \" \"(approx.)\"",
"timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links = [link.get('href') for link in",
"site \"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try:",
"self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as",
"!= rurl.netloc and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else:",
"pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds in {} seconds\" .format(len(self.rss_links), finish",
"html = soup(urllib.request.urlopen(site, timeout=1).read(), 'html.parser') except: return alist = html.find_all('a') links = [link.get('href')",
"self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links)))",
"'https']: self.all_links.append(link) and print(\"added\", link) else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links),",
"else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return",
"link in self.all_links: if link not in self.spidered: self.spider(link) def handle(self, *args, **options):",
"= [] rss_links = [] spidered = [] max_links = 500 max_feeds =",
"bunch o' goddam feeds \"\"\" all_links = [] rss_links = [] spidered =",
"def add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l', dest='max_links',",
"not in self.spidered: self.spider(link) def handle(self, *args, **options): start = time.time() print(options) self.max_links",
"print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS",
"the site # This will go to a seeder page, and spider the",
"parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int, default=500, help=\"Maximum number of RSS\" \"feeds to process \"",
"all the outgoing links from a site \"\"\" # print(\"Spidering\", site) if len(self.all_links)",
"soup from pprint import pprint # Command to feed a bunch of content",
"site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e)) finally:",
"feeds in {} seconds\" .format(len(self.rss_links), finish - start)) for feed in self.rss_links: tasks.url_to_feed(feed)",
"content into the site # This will go to a seeder page, and",
"print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site)",
"site' def add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str) parser.add_argument('--max-links', '-l',",
"import BeautifulSoup as soup from pprint import pprint # Command to feed a",
"site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found {} RSS feeds",
"and print(\"added\", link) else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) #",
"go to a seeder page, and spider the first # 100 feeds it",
"and \\ purl.scheme in ['http', 'https']: self.all_links.append(link) and print(\"added\", link) else: continue except:",
"finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links) # return all_links for link in",
"page, and spider the first # 100 feeds it can find class Command(BaseCommand):",
"process \" \"(approx.)\" ) def spider(self, site): \"\"\" grabs all the outgoing links",
"with a seeder site' def add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url',",
"(max_links)\") return try: rurl = urllib.parse.urlparse(site) except: print(\"Couldn't parse\", site) return self.spidered.append(site) pprint(self.spidered)",
"in self.spidered: self.spider(link) def handle(self, *args, **options): start = time.time() print(options) self.max_links =",
"in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\",",
"print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site))",
"spider the first # 100 feeds it can find class Command(BaseCommand): \"\"\" Spider",
"options.get('max_links') self.max_feeds = options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {}",
"{} sites\".format(len(self.all_links))) for site in self.all_links: try: self.rss_links.extend(tasks.find_feed(site)) except Exception as e: print(\"Skipping\",",
"from xfeeds.models import Feed from xfeeds.parser import tasks from bs4 import BeautifulSoup as",
"# This will go to a seeder page, and spider the first #",
"500 help = 'Add feeds starting with a seeder site' def add_arguments(self, parser):",
"in links: # print(link) try: purl = urllib.parse.urlparse(link) if purl.netloc != rurl.netloc and",
"a seeder site' def add_arguments(self, parser): \"\"\" Build argument parser \"\"\" parser.add_argument('url', type=str)",
"return all_links for link in self.all_links: if link not in self.spidered: self.spider(link) def",
"as e: print(\"Skipping\", site) print(str(e)) finally: print(\"#\", len(self.rss_links)) pprint(self.rss_links) finish = time.time() print(\"Found",
"a site \"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return",
"help=\"Maximum number of links \" \"to spider (approx.)\" ) parser.add_argument('--max-feeds', '-f', dest='max_feeds', type=int,",
"goddam feeds \"\"\" all_links = [] rss_links = [] spidered = [] max_links",
"links from a site \"\"\" # print(\"Spidering\", site) if len(self.all_links) > self.max_links: print(\"Skipping",
"site) if len(self.all_links) > self.max_links: print(\"Skipping (max_links)\") return try: rurl = urllib.parse.urlparse(site) except:",
"= options.get('max_feeds') url = options.get('url') print(\"Starting with\", url) self.spider(url) print(\"Spidered {} sites\".format(len(self.all_links))) for",
"print(\"added\", link) else: continue except: continue finally: print(\"{} Processed {}\".format(len(self.all_links), purl.netloc)) # pprint(all_links)",
"class Command(BaseCommand): \"\"\" Spider a bunch o' goddam feeds \"\"\" all_links = []"
] |
[] |
[
"in n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"]",
"as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args = [polyfem_exe, '-json',",
"with open(\"test.json\", 'r') as f: json_data = json.load(f) for is_bad in [True, False]:",
"json import subprocess import tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder",
"2, 3] p_refs = [False, True] current_folder = cwd = os.getcwd() with open(\"test.json\",",
"= os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if pref else \"\") +",
"+ ('bad' if is_bad else 'good') for ref in n_refs: for pref in",
"= \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1, 2, 3] p_refs =",
"ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\"",
"else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f:",
"= os.getcwd() with open(\"test.json\", 'r') as f: json_data = json.load(f) for is_bad in",
"import json import subprocess import tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\"",
"True] current_folder = cwd = os.getcwd() with open(\"test.json\", 'r') as f: json_data =",
"in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder",
"mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" +",
"'__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1, 2, 3]",
"tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args = [polyfem_exe,",
"n_refs = [0, 1, 2, 3] p_refs = [False, True] current_folder = cwd",
"pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if pref else",
"in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] =",
"n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] =",
"json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref)",
"json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if pref else \"\")",
"pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"]",
"3] p_refs = [False, True] current_folder = cwd = os.getcwd() with open(\"test.json\", 'r')",
"if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w')",
"pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) +",
"for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref",
"is_bad else 'good') for ref in n_refs: for pref in p_refs: json_data[\"mesh\"] =",
"p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(),",
"for ref in n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] =",
"current_folder = cwd = os.getcwd() with open(\"test.json\", 'r') as f: json_data = json.load(f)",
"= out_folder + ('bad' if is_bad else 'good') for ref in n_refs: for",
"json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f,",
"+ \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if pref",
"+ str(ref) + (\"_pref\" if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as",
"= mesh json_data[\"n_refs\"] = ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\"",
"= \"cond_num\" n_refs = [0, 1, 2, 3] p_refs = [False, True] current_folder",
"'good') for ref in n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"]",
"open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args = [polyfem_exe, '-json', tmp_json.name, '-cmd'] subprocess.run(args)",
"+ (\"_pref\" if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with",
"= [False, True] current_folder = cwd = os.getcwd() with open(\"test.json\", 'r') as f:",
"= ref json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) +",
"os import json import subprocess import tempfile if __name__ == '__main__': polyfem_exe =",
"[True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder +",
"out_f, \"mat_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\") with",
"\"cond_num\" n_refs = [0, 1, 2, 3] p_refs = [False, True] current_folder =",
"= pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if pref",
"else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\"",
"as f: json_data = json.load(f) for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\"",
"ref in n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh json_data[\"n_refs\"] = ref",
"('bad' if is_bad else 'good') for ref in n_refs: for pref in p_refs:",
"[False, True] current_folder = cwd = os.getcwd() with open(\"test.json\", 'r') as f: json_data",
"json_data[\"use_p_ref\"] = pref json_data[\"output\"] = os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if",
"if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref)",
"else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad else 'good') for ref",
"\"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data,",
"= json.load(f) for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else",
"import subprocess import tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder =",
"out_folder + ('bad' if is_bad else 'good') for ref in n_refs: for pref",
"str(ref) + (\"_pref\" if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json:",
"subprocess import tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\"",
"__name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1,",
"json.load(f) for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\"",
"+ \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4))",
"p_refs = [False, True] current_folder = cwd = os.getcwd() with open(\"test.json\", 'r') as",
"os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\")",
"import tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs",
"<reponame>polyfem/Decoupling-Simulation-Accuracy-from-Mesh-Quality import os import json import subprocess import tempfile if __name__ == '__main__':",
"(\"_pref\" if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name,",
"else 'good') for ref in n_refs: for pref in p_refs: json_data[\"mesh\"] = mesh",
"(\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" +",
"json_data = json.load(f) for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad",
"json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if pref else \"\")",
"\".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args",
"== '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1, 2,",
"\"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad else",
"= cwd = os.getcwd() with open(\"test.json\", 'r') as f: json_data = json.load(f) for",
"[0, 1, 2, 3] p_refs = [False, True] current_folder = cwd = os.getcwd()",
"+ (\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\"",
"= \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad",
"if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad else 'good')",
"pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as",
"cwd = os.getcwd() with open(\"test.json\", 'r') as f: json_data = json.load(f) for is_bad",
"is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f =",
"= os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if pref else \"\") +",
"out_f = out_folder + ('bad' if is_bad else 'good') for ref in n_refs:",
"with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args = [polyfem_exe, '-json', tmp_json.name, '-cmd']",
"with tempfile.NamedTemporaryFile(suffix=\".json\") as tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args =",
"str(ref) + (\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f,",
"\"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad else 'good') for ref in",
"\".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if pref else",
"if is_bad else 'good') for ref in n_refs: for pref in p_refs: json_data[\"mesh\"]",
"+ str(ref) + (\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(),",
"= [0, 1, 2, 3] p_refs = [False, True] current_folder = cwd =",
"1, 2, 3] p_refs = [False, True] current_folder = cwd = os.getcwd() with",
"polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1, 2, 3] p_refs",
"\"mat_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\") with tempfile.NamedTemporaryFile(suffix=\".json\")",
"\"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0, 1, 2, 3] p_refs = [False,",
"is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if is_bad else 'good') for",
"out_folder = \"cond_num\" n_refs = [0, 1, 2, 3] p_refs = [False, True]",
"os.getcwd() with open(\"test.json\", 'r') as f: json_data = json.load(f) for is_bad in [True,",
"f: json_data = json.load(f) for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if",
"\"out_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"] =",
"os.path.join(os.getcwd(), out_f, \"out_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\")",
"\"\") + \".json\") json_data[\"stiffness_mat_save_path\"] = os.path.join(os.getcwd(), out_f, \"mat_\" + str(ref) + (\"_pref\" if",
"'r') as f: json_data = json.load(f) for is_bad in [True, False]: mesh =",
"tempfile if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs =",
"open(\"test.json\", 'r') as f: json_data = json.load(f) for is_bad in [True, False]: mesh",
"False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad'",
"import os import json import subprocess import tempfile if __name__ == '__main__': polyfem_exe",
"mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f = out_folder + ('bad' if",
"if __name__ == '__main__': polyfem_exe = \"./PolyFEM_bin\" out_folder = \"cond_num\" n_refs = [0,",
"tmp_json: with open(tmp_json.name, 'w') as f: f.write(json.dumps(json_data, indent=4)) args = [polyfem_exe, '-json', tmp_json.name,",
"for is_bad in [True, False]: mesh = \"../data/conditioning_44000_bad.mesh\" if is_bad else \"../data/conditioning_44000_good.mesh\" out_f",
"out_f, \"out_\" + str(ref) + (\"_pref\" if pref else \"\") + \".json\") json_data[\"stiffness_mat_save_path\"]"
] |
[
"super().__init__(master=parent, *args, **kw) # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9),",
"the input class Validator: # Return error message if the input is not",
"len(self.treeview.get_children()) ## # A layout to group some elements. # Support two layouts:",
"def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and",
"destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" %",
"if the input is blank # Return None if the input is valid",
"('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell',",
"None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget()",
"dataFile if not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData = True): raise",
"return 2: fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None",
"'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3),",
"input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\")",
"sqlite3 import Error ## # Validate the input class Validator: # Return error",
"input is not in a \"yyyy-MM-dd\" format # Return None if the input",
"if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow = tk.Toplevel(activityDisplayWindow)",
"self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if",
"80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01',",
"isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans,",
"\"Do you want to quit both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1)",
"window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"):",
"# Create input and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState)",
"# Create Table and initialize Data # Transaction Data: yyyy-MM-dd # Stock Symbol:",
"a stock record to Sqllite database, and one can search and list the",
"+ where + ' order by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select",
"and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0),",
"self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do",
"self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10),",
"for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else:",
"labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame,",
"trans, quantity, price)] ) return isSuccess # Run sql, support batch # return",
"size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and pack self.label = tk.Label(self,",
"summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" %",
"windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self): if",
"if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\"",
"{\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB def",
"{\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def",
"return None def listTransactions(self, paramDict={}): queryParam = [] for item, value in paramDict.items():",
"= None dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig()",
"input): errMsg = \"Please input a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\")",
"!= len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit =",
"textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the",
"should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler # The validator. It",
"[\"isNumber\", \"isEmpty\"], means the value needs two validation self.validatorArray = validateArray # Create",
"want to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No",
"self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage()",
"self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\",",
"dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def",
"**kw) # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\")",
"import ttk, messagebox, filedialog from functools import partial from datetime import datetime import",
"tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame",
"self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0)",
"inputDict = self.generateParametersDict() # 5 means all items are inputted if len(inputDict) ==",
"a number (float) # Return None if the input is valid def isNumber(self,input):",
"tk from tkinter import ttk, messagebox, filedialog from functools import partial from datetime",
"in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\")",
"if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete",
"* from stocks order by transaction_date asc limit 1', 'select * from stocks",
"dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName",
"Create Data if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") # get",
"self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update",
"= \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName =",
"validationErrors) return False return True # When focus, focus the input box def",
"__name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow = tk.Toplevel(activityDisplayWindow) ActivityEntryWindow(activityEntryWindow,",
"\"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20')",
"Data # Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell #",
"%s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade =",
"**kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if items != None: for",
"message if the input is not in a \"yyyy-MM-dd\" format # Return None",
"= [] try: conn = sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)):",
"order by transaction_date desc limit 1', 'select * from stocks order by price",
"tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item in columnsAttr) self.treeview",
"packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def",
"tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to group some",
"sql, support batch # return 1: True/False for update/delete/insert # return 2: fetch",
"[('Text Document', '*.txt')]) if destFile is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult:",
"0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn =",
"errMsg = \"Please input a number.\" try: if input=='NaN': return errMsg float(input) except",
"the data from DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not",
"clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict()))",
"if isSuccess: return dataResult return None def listTransactions(self, paramDict={}): queryParam = [] for",
"both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10),",
"return True, fetchResult finally: if conn: conn.close() # Create Table and initialize Data",
"tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick)",
"LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items):",
"error message. # The handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler =",
"symbol from stocks group by symbol order by trade_times desc limit 1' ])",
"cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s",
"stocks', 'select * from stocks order by transaction_date asc limit 1', 'select *",
"size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\",",
"= DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s,",
"= True if needCommit: conn.commit() except Error as e: # TODO: Log the",
"Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both",
"self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text,",
"ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor dbName = \"stocks_test.db\" def __init__(self,parent,",
"row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to",
"Below are the UI design ########################### ## # \"Activity Display\" contains two buttons",
"('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return False if __name__ == \"__main__\":",
"= TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\")",
"self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A",
"import os import sqlite3 from sqlite3 import Error ## # Validate the input",
"not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize",
"database connection # Usage: The user can add a stock record to Sqllite",
"= tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0),",
"%s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade =",
"exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s,",
"self.runSql([ 'select distinct symbol from stocks', 'select * from stocks order by transaction_date",
"(OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f",
"font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame,",
"+ str(value)) where = \"\" if len(queryParam) > 0: where = \"where \"",
"anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame",
"'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3),",
"= conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit() except",
"Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"",
"self.db = dataFile if not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData =",
"TODO: put it in debug log #print('select * from stocks ' + where",
"14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14),",
"pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0])",
"def focus(self): self.input.focus() # Return the input value def getDDValue(self): return self.inputValue.get() def",
"for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record) destFile.close()",
"the input value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## #",
"pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue,",
"createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\",",
"parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label",
"# self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton =",
"tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame,",
"return self ############################# Above are the widgets; Below are the UI design ###########################",
"LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22),",
"None def listTransactions(self, paramDict={}): queryParam = [] for item, value in paramDict.items(): if",
"needCommit = True if needCommit: conn.commit() except Error as e: # TODO: Log",
"withData = False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT,",
"in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\")",
"a \"yyyy-MM-dd\" format # Return None if the input is valid def isDate(self,",
"to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\",",
"def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parent.destroy()",
"\"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict()",
"len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\")",
"range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01',",
"( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity",
"box def focus(self): self.input.focus() # Return the input value def getDDValue(self): return self.inputValue.get()",
"\"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"]",
"+ validationErrors) return False return True # When focus, focus the input box",
"def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) #",
"packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay)",
"= self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)]",
"'select * from stocks ' + where + ' order by transaction_date asc'",
"self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is",
"TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction",
"The validator. It will call validator class and loop def validator(self): validator =",
"self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20')",
"self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self):",
"+ \" - \" + validationErrors) return False return True # When focus,",
"return False return True # When focus, focus the input box def focus(self):",
"order by transaction_date asc limit 1', 'select * from stocks order by transaction_date",
"else: needCommit = True if needCommit: conn.commit() except Error as e: # TODO:",
"valid def isEmpty(self, input): errMsg = \"Value required\" if input != \"\": return",
"valRules + \"('\" + self.inputValue.get() + \"')\") if validationErrors != None: # Output",
"# Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \"",
"= summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\"",
"self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB def updateInfo(self): dataController = DataController(self.dbName)",
"stocks order by price desc limit 1', 'select count(id) as trade_times, symbol from",
"text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self):",
"# The handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler #",
"%d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document',",
"True): raise Exception(\"Database Initialize Error\") # get all information in one connection def",
"size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay)",
"if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\":",
"Above are UI design, below are database access code ######################## ## # Controller:",
"= tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame,",
"self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary =",
"tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary,",
"INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for",
"11.3) ] )[0] return False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass",
"and loop def validator(self): validator = Validator() for valRules in self.validatorArray: #eval() validationErrors",
"(%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity):",
"and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName = \"stocks.db\"",
"height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll",
"parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) #",
"self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput,",
"Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName =",
"limit 1' ]) if isSuccess: return dataResult return None def listTransactions(self, paramDict={}): queryParam",
"= self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1])",
"self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text",
"error message if the input is not in a \"yyyy-MM-dd\" format # Return",
"= Validator() for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors !=",
"not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") # get all information in",
"self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" %",
"= summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\"",
"# Usage: The user can add a stock record to Sqllite database, and",
"def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in self.validatorArray: #eval() validationErrors",
"######################## ## # Controller: Manipulate the data and return to View class DataController:",
"dataResult = self.runSql([ 'select * from stocks ' + where + ' order",
"return False,[] fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit = False for",
"[] for item, value in paramDict.items(): if type(value) is str: queryParam.append(item + \"='\"",
"return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into",
"message if the input is blank # Return None if the input is",
"80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01',",
"(transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3),",
"super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the value needs two",
"% (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0]",
"\"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName",
"getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to group some elements. # Support",
"if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parent.destroy() def createWidgets(self):",
"self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5",
"tupleArray): if tupleArray is not None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def",
"complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs",
"if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower()",
"= LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\",",
"one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol from stocks',",
"summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" %",
"100 # Transation Price: 12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE",
"not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is not None:",
"def setInputErrorHandler(self, handler): self.errHandler = handler # The validator. It will call validator",
"class Validator: # Return error message if the input is not a number",
"pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None:",
"%s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame",
"100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01',",
"= None activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent",
"group by symbol order by trade_times desc limit 1' ]) if isSuccess: return",
"font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create",
"and loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in self.validatorArray:",
"<gh_stars>0 # This project is a assignment of College. # Purpose: Practice TK",
"def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"},",
"False,[] fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit = False for i",
"def layout(self, layout, *items): if items != None: for item in items: if",
"onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parent.destroy() def",
"tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s",
"LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\",",
"type(value) is str: queryParam.append(item + \"='\" + value + \"'\") else: queryParam.append(item +",
"value needs two validation self.validatorArray = validateArray # Create label and pack self.label",
"packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the",
"= LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\",",
"the input box def focus(self): self.input.focus() # Return the input value def getDDValue(self):",
"#eval() validationErrors = eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() + \"')\") if",
"= validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the error message to \"error",
"group some elements. # Support two layouts: # Use \"h\" to pack horizontally",
"margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h',",
"# Validate the input class Validator: # Return error message if the input",
"(expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not",
"except ValueError: return errMsg else: return None ## # One label and one",
"from stocks order by price desc limit 1', 'select count(id) as trade_times, symbol",
"= self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue()",
"# # Author: <NAME> # Date: 2021-03-17 import tkinter as tk from tkinter",
"\"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2))",
"__init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\")",
"Validate the input class Validator: # Return error message if the input is",
"self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the error",
"self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records",
"input): errMsg = \"Value required\" if input != \"\": return None else: return",
"the input is valid def isDate(self, input): errMsg = \"Please input a date",
"self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\",",
"conn = None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[]",
"queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit()",
"datetime import os import sqlite3 from sqlite3 import Error ## # Validate the",
"and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems)",
"14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\",",
"log #print('select * from stocks ' + where + ' order by transaction_date",
"for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout",
"buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\",",
"if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d,",
"self.generateParametersDict() # 5 means all items are inputted if len(inputDict) == 5: if",
"= LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2))",
"validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules",
"+ \"=\" + str(value)) where = \"\" if len(queryParam) > 0: where =",
"= LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\",",
"desc limit 1', 'select * from stocks order by price asc limit 1',",
"orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray):",
"# return 1: True/False for update/delete/insert # return 2: fetch data for select",
"if input=='NaN': return errMsg float(input) except ValueError: return errMsg else: return None #",
"distinct symbol from stocks', 'select * from stocks order by transaction_date asc limit",
"self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None:",
"'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80,",
"= DataController(self.dbName) if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if summaryResults is",
"Return the input value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ##",
"None if the input is valid def isEmpty(self, input): errMsg = \"Value required\"",
"def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and one input box class",
"= LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded",
"item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self ############################# Above are the widgets; Below",
"margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the value needs",
"self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput,",
"Manipulate the data and return to View class DataController: def __init__(self, dataFile): self.db",
"LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"],",
"getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol from stocks', 'select * from",
"% (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is",
"getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value)",
"%s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI",
"yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100 # Transation",
"def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to group some elements. #",
"stocks order by price asc limit 1', 'select * from stocks order by",
"dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame =",
"x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade =",
"- \" + validationErrors) return False return True # When focus, focus the",
"False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if",
"tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"},",
"*args, **kw) columns = list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows,",
"self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\",",
"items are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert",
"value is invalidate, this handler will display error message. # The handler should",
"pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"},",
"LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput =",
"= LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"],",
"self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy",
"[(transDate, symbol, trans, quantity, price)] ) return isSuccess # Run sql, support batch",
"Validator() for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules + \"('\"",
"transaction_date asc') isSuccess, dataResult = self.runSql([ 'select * from stocks ' + where",
"# Return the input value def getInputValue(self): return self.inputValue.get() def setValue(self, value): if",
"def getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\")",
"\" and \".join(queryParam) # TODO: put it in debug log #print('select * from",
"'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4),",
"two buttons on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None",
"entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\",",
"return False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow",
"return None else: return errMsg # Return error message if the input is",
"def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget()",
"errMsg else: return None # Return error message if the input is blank",
"layout(self, layout, *items): if items != None: for item in items: if layout",
"def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY",
"'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3)",
"= [('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile is not",
"text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton",
"str(value)) where = \"\" if len(queryParam) > 0: where = \"where \" +",
"buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick)",
"e: # TODO: Log the error print(e) return False, [] else: return True,",
"margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput =",
"!= \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict =",
"validationErrors != None: # Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] +",
"setValues(self, tupleArray): if tupleArray is not None: self.clearAll() for row in tupleArray[0]: self.addValues(row)",
"Display\" contains two buttons on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame",
"'sell', 80, 11.3) ] )[0] return False if __name__ == \"__main__\": activityDisplayWindow =",
"%.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below are",
"text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary,",
"tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest",
"error message if the input is blank # Return None if the input",
"symbol text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into",
"Error as e: # TODO: Log the error print(e) return False, [] else:",
"float(input) except ValueError: return errMsg else: return None # Return error message if",
"def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all items are inputted if",
"text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame =",
"10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL',",
"activity.lower() == \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity",
"len(queryParam) > 0: where = \"where \" + \" and \".join(queryParam) # TODO:",
"and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if",
"# Controller: Manipulate the data and return to View class DataController: def __init__(self,",
"by trade_times desc limit 1' ]) if isSuccess: return dataResult return None def",
"Run sql, support batch # return 1: True/False for update/delete/insert # return 2:",
"False return True # When focus, focus the input box def focus(self): self.input.focus()",
"pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0)",
"LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22),",
"'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3),",
"def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for",
"= False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i],",
"focus the input box def focus(self): self.input.focus() # Return the input value def",
"and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] =",
"labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput",
"10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\")",
"id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER,",
"in class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass",
"database, and one can search and list the records # # Author: <NAME>",
"\"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue()",
"self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() + \"')\")",
"pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def",
"for item, value in paramDict.items(): if type(value) is str: queryParam.append(item + \"='\" +",
"anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray)",
"all items are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick()",
"ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"])",
"text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into stocks",
"PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER, price REAL",
"= LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\",",
"[] else: return True, fetchResult finally: if conn: conn.close() # Create Table and",
"self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue()",
"None else: return errMsg # Return error message if the input is not",
"DATE, symbol text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert",
"errMsg = \"Please input a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except",
"# Return None if the input is valid def isNumber(self,input): errMsg = \"Please",
"{\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB",
"to View class DataController: def __init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile):",
"stocks ' + where + ' order by transaction_date asc' ]) if isSuccess:",
"self.inputValue.get() + \"')\") if validationErrors != None: # Output the error message to",
"is valid def isNumber(self,input): errMsg = \"Please input a number.\" try: if input=='NaN':",
"len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = [] try:",
"self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput =",
"None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not",
"setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and one input box class LabelInputCombo(tk.Frame):",
"input class Validator: # Return error message if the input is not a",
"to Sqllite database, and one can search and list the records # #",
"paramDict={}): queryParam = [] for item, value in paramDict.items(): if type(value) is str:",
"return to View class DataController: def __init__(self, dataFile): self.db = dataFile if not",
"= ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"],",
"%d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below",
"self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\",",
"fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray)",
"text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"),",
"margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest",
"self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def",
"14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0),",
"Support two layouts: # Use \"h\" to pack horizontally # Use \"v\" to",
"Initialize Error\") # get all information in one connection def getSummaryInfo(self): isSuccess, dataResult",
"the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None",
"Return None if the input is valid def isNumber(self,input): errMsg = \"Please input",
"both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton",
"self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent,",
"price REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x",
"and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() #",
"values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01',",
"value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table",
"\"Do you want to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay =",
"support batch # return 1: True/False for update/delete/insert # return 2: fetch data",
"loop def validator(self): validator = Validator() for valRules in self.validatorArray: #eval() validationErrors =",
"summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" %",
"and \".join(queryParam) # TODO: put it in debug log #print('select * from stocks",
"'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100,",
"= parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose)",
"record to Sqllite database, and one can search and list the records #",
"None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\",",
"isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert",
"else: item.pack(side='left', padx=5) return self ############################# Above are the widgets; Below are the",
"class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent):",
"queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if",
"* from stocks ' + where + ' order by transaction_date asc') isSuccess,",
"stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return isSuccess #",
"14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT',",
"return len(self.treeview.get_children()) ## # A layout to group some elements. # Support two",
"self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\",",
"Exception(\"Database Initialize Error\") # get all information in one connection def getSummaryInfo(self): isSuccess,",
"\" - \" + validationErrors) self.input.delete(0,\"end\") return False return True # When focus,",
"one can search and list the records # # Author: <NAME> # Date:",
"Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" +",
"def listTransactions(self, paramDict={}): queryParam = [] for item, value in paramDict.items(): if type(value)",
"command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame",
"if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\"",
"by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select * from stocks ' +",
"= \"where \" + \" and \".join(queryParam) # TODO: put it in debug",
"self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text",
"message if the input is not a number (float) # Return None if",
"= validateArray # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\",",
"' + where + ' order by transaction_date asc') isSuccess, dataResult = self.runSql([",
"from functools import partial from datetime import datetime import os import sqlite3 from",
"Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock",
"%s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade",
"and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor dbName =",
"if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two",
"Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100",
"**kw) columns = list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\",",
"Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\")",
"else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\")",
"value def getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\")",
"80, 11.3) ] )[0] return False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk()",
"None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons on the top:",
"self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0)",
"self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue()",
"dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1))",
"command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton,",
"from stocks order by transaction_date desc limit 1', 'select * from stocks order",
"queryParam.append(item + \"='\" + value + \"'\") else: queryParam.append(item + \"=\" + str(value))",
"validator(self): validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if",
"quantity, price)] ) return isSuccess # Run sql, support batch # return 1:",
"False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent",
"means the value needs two validation self.validatorArray = validateArray # Create label and",
"\"Activity Display\" contains two buttons on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame):",
"TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"]",
"validationErrors) self.input.delete(0,\"end\") return False return True # When focus, focus the input box",
"{\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from",
"When the value is invalidate, this handler will display error message. # The",
"packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput =",
"= parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity",
"queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all items are inputted",
"order by price desc limit 1', 'select count(id) as trade_times, symbol from stocks",
"self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most",
"font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\",",
"if summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols])",
"two validation self.validatorArray = validateArray # Create label and pack self.label = tk.Label(self,",
"# Support two layouts: # Use \"h\" to pack horizontally # Use \"v\"",
"Author: <NAME> # Date: 2021-03-17 import tkinter as tk from tkinter import ttk,",
"else: return None ## # One label and one combobox class LabelDDCombo(tk.Frame): def",
"len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit = False",
"not None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ##",
"input is blank # Return None if the input is valid def isEmpty(self,",
"= [\"isNumber\", \"isEmpty\"], means the value needs two validation self.validatorArray = validateArray #",
"validator class and loop def validator(self): validator = Validator() for valRules in self.validatorArray:",
"one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw):",
"windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea,",
"return 1: True/False for update/delete/insert # return 2: fetch data for select def",
"(float) # Return None if the input is valid def isNumber(self,input): errMsg =",
"# This project is a assignment of College. # Purpose: Practice TK and",
"required\" if input != \"\": return None else: return errMsg # Return error",
"== \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow = tk.Toplevel(activityDisplayWindow) ActivityEntryWindow(activityEntryWindow, displayWindowClass)",
"in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to group",
"== 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else:",
"debug log #print('select * from stocks ' + where + ' order by",
"__init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False)",
"input != \"\": return None else: return errMsg # Return error message if",
"# Return the input value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex)",
"self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[",
"'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80,",
"False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i])",
"conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit() except Error",
"one input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0),",
"TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data",
"and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] =",
")'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)],",
"Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100 # Transation Price: 12.34",
"contains two buttons on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame =",
"= conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit =",
"raise Exception(\"Database Initialize Error\") # get all information in one connection def getSummaryInfo(self):",
"try: conn = sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray)",
"= parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose)",
"> 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall())",
"Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2))",
"\" + validationErrors) return False return True # When focus, focus the input",
"self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\")",
"dataResult = self.runSql([ 'select distinct symbol from stocks', 'select * from stocks order",
"'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return False if",
"text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h',",
"self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit",
"trade_times, symbol from stocks group by symbol order by trade_times desc limit 1'",
"text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values",
"Above are the widgets; Below are the UI design ########################### ## # \"Activity",
"+ valRules + \"('\" + self.inputValue.get() + \"')\") if validationErrors != None: #",
"Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor dbName = \"stocks_test.db\"",
"== \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame):",
"return True # When focus, focus the input box def focus(self): self.input.focus() #",
"limit 1', 'select * from stocks order by price asc limit 1', 'select",
"setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) #",
"if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if",
"validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6),",
"is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\",",
"buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary =",
"os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\")",
"Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100 #",
"# Use \"h\" to pack horizontally # Use \"v\" to pack vertically class",
"if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26)",
"import partial from datetime import datetime import os import sqlite3 from sqlite3 import",
"self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame,",
"self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons",
"you want to quit both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1)",
"input and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1]",
"= summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\"",
"message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return False",
"10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT',",
"queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() !=",
"################################# Above are UI design, below are database access code ######################## ## #",
"if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self):",
"handler): self.errHandler = handler # The validator. It will call validator class and",
"self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\",",
"return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and one input",
"self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input",
"self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar()",
"self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"},",
"6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0]",
"def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"],",
"self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest",
"return isSuccess # Run sql, support batch # return 1: True/False for update/delete/insert",
"return errMsg # Return error message if the input is not in a",
"display error message. # The handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler",
"super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self,",
"!= \"\": return None else: return errMsg # Return error message if the",
"None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() #",
"valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules + \"('\" + self.inputValue.get()",
"transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql(",
"12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER",
"columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item in columnsAttr)",
"queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means",
"= tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) #",
"from sqlite3 import Error ## # Validate the input class Validator: # Return",
"ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide,",
"record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export",
"1', 'select * from stocks order by price desc limit 1', 'select count(id)",
"self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput =",
"= LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton,",
"Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2))",
"+ validationErrors) self.input.delete(0,\"end\") return False return True # When focus, focus the input",
"margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame,",
"def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not",
"One label and one input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\",",
"project is a assignment of College. # Purpose: Practice TK and database connection",
"all information in one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct",
"Create input and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue,",
"layouts: # Use \"h\" to pack horizontally # Use \"v\" to pack vertically",
"self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\",",
"of College. # Purpose: Practice TK and database connection # Usage: The user",
"'select * from stocks order by transaction_date asc limit 1', 'select * from",
"self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"]",
"tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All",
"pack horizontally # Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent,",
"state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When",
"is not a number (float) # Return None if the input is valid",
"import tkinter as tk from tkinter import ttk, messagebox, filedialog from functools import",
"= None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult",
"margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame,",
"tkinter as tk from tkinter import ttk, messagebox, filedialog from functools import partial",
"sqlite3 from sqlite3 import Error ## # Validate the input class Validator: #",
"focus(self): self.input.focus() # Return the input value def getDDValue(self): return self.inputValue.get() def setValue(self,",
"topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\"))",
"# Return error message if the input is not in a \"yyyy-MM-dd\" format",
"Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\",",
"+ \"('\" + self.inputValue.get() + \"')\") if validationErrors != None: # Output the",
"+ value + \"'\") else: queryParam.append(item + \"=\" + str(value)) where = \"\"",
"valid def isDate(self, input): errMsg = \"Please input a date in yyyy-MM-dd format.\"",
"valueIndex): self.input.current(valueIndex) ## # One label and one input box class LabelInputCombo(tk.Frame): def",
"\"=\" + str(value)) where = \"\" if len(queryParam) > 0: where = \"where",
"input box def focus(self): self.input.focus() # Return the input value def getInputValue(self): return",
"for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules + \"('\" +",
"searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes",
"except Error as e: # TODO: Log the error print(e) return False, []",
"anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\")",
"self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if",
"## # A layout to group some elements. # Support two layouts: #",
"this handler will display error message. # The handler should be .config(text=XXX) def",
"not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0]",
"Purpose: Practice TK and database connection # Usage: The user can add a",
"labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2))",
"1', 'select * from stocks order by transaction_date desc limit 1', 'select *",
"class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout,",
"errMsg float(input) except ValueError: return errMsg else: return None # Return error message",
"if conn: conn.close() # Create Table and initialize Data # Transaction Data: yyyy-MM-dd",
"textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]),",
"self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"]",
"Error\") # get all information in one connection def getSummaryInfo(self): isSuccess, dataResult =",
"*items): if items != None: for item in items: if layout == \"v\":",
"self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols =",
"= tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\",",
"80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return False if __name__",
"Table and initialize Data # Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT #",
"validator class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules",
"is valid def isEmpty(self, input): errMsg = \"Value required\" if input != \"\":",
"5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please",
"tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1])",
"in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0]",
"labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\",",
"price)] ) return isSuccess # Run sql, support batch # return 1: True/False",
"margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most",
"padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self,",
"the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors)",
"the input is blank # Return None if the input is valid def",
"except ValueError: return errMsg else: return None # Return error message if the",
"class ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor dbName = \"stocks_test.db\" def",
"updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if",
"# return 2: fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn =",
"fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input",
"def isNumber(self,input): errMsg = \"Please input a number.\" try: if input=='NaN': return errMsg",
"isSuccess, dataResult = self.runSql([ 'select distinct symbol from stocks', 'select * from stocks",
"Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName = \"stocks.db\" def",
"newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s",
"self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below are database access code ########################",
"parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig()",
"width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray):",
"item.pack(side='left', padx=5) return self ############################# Above are the widgets; Below are the UI",
"for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade",
"return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all items are",
"labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\",",
") return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick)",
"top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName",
"number (float) # Return None if the input is valid def isNumber(self,input): errMsg",
"layout, *items): if items != None: for item in items: if layout ==",
"[] try: conn = sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)): if",
"= tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide,",
"self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\")",
"text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if",
"labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2))",
"\"yyyy-MM-dd\" format # Return None if the input is valid def isDate(self, input):",
"self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount())",
"Return error message if the input is not in a \"yyyy-MM-dd\" format #",
"None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## #",
"anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0)",
"conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True",
"as trade_times, symbol from stocks group by symbol order by trade_times desc limit",
"order by price asc limit 1', 'select * from stocks order by price",
"input is valid def isNumber(self,input): errMsg = \"Please input a number.\" try: if",
"yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return None ##",
"__init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if items",
"*args, **kw) # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\",",
"elements. # Support two layouts: # Use \"h\" to pack horizontally # Use",
"self.runSql([ 'select * from stocks ' + where + ' order by transaction_date",
"\"where \" + \" and \".join(queryParam) # TODO: put it in debug log",
"'select distinct symbol from stocks', 'select * from stocks order by transaction_date asc",
"else: queryParam.append(item + \"=\" + str(value)) where = \"\" if len(queryParam) > 0:",
"self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def",
"%s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if",
"anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"),",
"= tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton,",
"if type(value) is str: queryParam.append(item + \"='\" + value + \"'\") else: queryParam.append(item",
"\"='\" + value + \"'\") else: queryParam.append(item + \"=\" + str(value)) where =",
"in debug log #print('select * from stocks ' + where + ' order",
"Return error message if the input is blank # Return None if the",
"It will call validator class and loop def validator(self): validator = Validator() for",
"%s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design,",
"means all items are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo()",
"horizontally # Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args,",
"# The validator. It will call validator class and loop def validator(self): validator",
"def isDate(self, input): errMsg = \"Please input a date in yyyy-MM-dd format.\" try:",
"\"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"]",
"box def focus(self): self.input.focus() # Return the input value def getInputValue(self): return self.inputValue.get()",
"not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]:",
"Return None if the input is valid def isEmpty(self, input): errMsg = \"Value",
"= ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1])",
"not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is",
"input a number.\" try: if input=='NaN': return errMsg float(input) except ValueError: return errMsg",
"\"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self ############################# Above are the widgets;",
"return None ## # One label and one combobox class LabelDDCombo(tk.Frame): def __init__(self,",
"# When focus, focus the input box def focus(self): self.input.focus() # Return the",
"padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self,",
"tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions())",
"{} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() !=",
"LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"),",
"*args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item in columnsAttr) self.treeview =",
"self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self,",
"\"Please input a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return",
"size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay)",
"*args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the value needs two validation",
"ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self,",
"searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton,",
"buttons on the top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten",
"'select * from stocks order by transaction_date desc limit 1', 'select * from",
"# One label and one input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label",
"'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3),",
"= tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def",
"the UI design ########################### ## # \"Activity Display\" contains two buttons on the",
"+ \" - \" + validationErrors) self.input.delete(0,\"end\") return False return True # When",
"items != None: for item in items: if layout == \"v\": item.pack(side='top', pady=5)",
"if the input is valid def isDate(self, input): errMsg = \"Please input a",
"design, below are database access code ######################## ## # Controller: Manipulate the data",
"is blank # Return None if the input is valid def isEmpty(self, input):",
"sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit() except Error as e:",
"16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL',",
"transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price)",
"self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"])",
"None if the input is valid def isNumber(self,input): errMsg = \"Please input a",
"Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"],",
"partial from datetime import datetime import os import sqlite3 from sqlite3 import Error",
"Create Table and initialize Data # Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT",
"self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and",
"def focus(self): self.input.focus() # Return the input value def getInputValue(self): return self.inputValue.get() def",
"self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide,",
"########################### ## # \"Activity Display\" contains two buttons on the top: Summary and",
"self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\"",
"be overwritten in class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent =",
"self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and one input box",
"is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame",
"The validator. It will call validator class and loop def validator(self): self.errHandler.config(text=\"No Error\")",
"# Return error message if the input is blank # Return None if",
"'select * from stocks order by price asc limit 1', 'select * from",
"validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors",
"def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False,",
"is str: queryParam.append(item + \"='\" + value + \"'\") else: queryParam.append(item + \"=\"",
"queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if",
"0: where = \"where \" + \" and \".join(queryParam) # TODO: put it",
"self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr,",
"# validateArray = [\"isNumber\", \"isEmpty\"], means the value needs two validation self.validatorArray =",
"None activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False,",
"symbol from stocks', 'select * from stocks order by transaction_date asc limit 1',",
"= self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all",
"input a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg",
"def setValues(self, tupleArray): if tupleArray is not None: self.clearAll() for row in tupleArray[0]:",
"for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0:",
"None: # Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" -",
"self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"]",
"self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window",
"error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return",
"input value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One",
"isNumber(self,input): errMsg = \"Please input a number.\" try: if input=='NaN': return errMsg float(input)",
"count(id) as trade_times, symbol from stocks group by symbol order by trade_times desc",
"('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy',",
"LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput,",
"items: if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self #############################",
"pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame,",
"if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator():",
"self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons on the top: Summary",
"desc limit 1' ]) if isSuccess: return dataResult return None def listTransactions(self, paramDict={}):",
"\"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if",
"entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and pack self.label",
"Return None if the input is valid def isDate(self, input): errMsg = \"Please",
"# Return None if the input is valid def isEmpty(self, input): errMsg =",
"from stocks ' + where + ' order by transaction_date asc') isSuccess, dataResult",
"by transaction_date asc' ]) if isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price):",
"return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() !=",
"\"h\" to pack horizontally # Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def",
"ValueError: return errMsg else: return None # Return error message if the input",
"self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2]))",
"font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14),",
"!= \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator():",
"data from DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not None:",
"addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate,",
"' order by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select * from stocks",
"return errMsg else: return None # Return error message if the input is",
"!= None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue =",
"if items != None: for item in items: if layout == \"v\": item.pack(side='top',",
"self.updateInfo() # Update the data from DB def updateInfo(self): dataController = DataController(self.dbName) if",
"# Create input and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable =",
"False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE,",
"= LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput,",
"margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self):",
"= LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\",",
"def __init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile): # Create Data if",
"font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary",
"def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile =",
"* from stocks ' + where + ' order by transaction_date asc' ])",
"order by transaction_date asc' ]) if isSuccess: return dataResult return None def addTransaction(self,",
"dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton =",
"import datetime import os import sqlite3 from sqlite3 import Error ## # Validate",
"tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]),",
"\"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return False return True",
"if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert",
"packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput",
"('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return",
"{\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB def updateInfo(self): dataController",
"'*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile is not None: exportResult =",
"size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue",
"to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw)",
"if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn = sqlite3.connect(self.db)",
"as e: # TODO: Log the error print(e) return False, [] else: return",
"stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text,",
"i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults",
"and one input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\",",
"select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0: if",
"handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler # The validator.",
"self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame,",
"Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE",
"the value needs two validation self.validatorArray = validateArray # Create label and pack",
"parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if items !=",
"self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\",",
"margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14),",
"{\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput",
"= tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent,",
"def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\" and",
"by symbol order by trade_times desc limit 1' ]) if isSuccess: return dataResult",
"When focus, focus the input box def focus(self): self.input.focus() # Return the input",
"functools import partial from datetime import datetime import os import sqlite3 from sqlite3",
"is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo()",
"self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate, this handler will display",
"font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\",",
"limit 1', 'select count(id) as trade_times, symbol from stocks group by symbol order",
"9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL',",
"limit 1', 'select * from stocks order by price desc limit 1', 'select",
"> 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn",
"DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s,",
"asc') isSuccess, dataResult = self.runSql([ 'select * from stocks ' + where +",
"\"Please input a number.\" try: if input=='NaN': return errMsg float(input) except ValueError: return",
"parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\")",
"= list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for",
"def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo()",
"self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all items",
"self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ##",
"destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if",
"initialize Data # Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell",
"and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None:",
"!= \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] =",
"clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame,",
"valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output",
"it in debug log #print('select * from stocks ' + where + '",
"validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay)",
"Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile is not None: exportResult",
"TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions()",
"font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self):",
"command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self):",
"None: summaryResults = dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0]",
"LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary",
"self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage()",
"# Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100 # Transation Price:",
"exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") #################################",
"True/False for update/delete/insert # return 2: fetch data for select def runSql(self, sqlStatementArray,",
"\"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue()",
"Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\")",
"self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to",
"None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d,",
"self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\",",
"[\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return",
"text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols),",
"tupleArray is not None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return",
"symbol, trans, quantity, price)] ) return isSuccess # Run sql, support batch #",
"+ \"'\") else: queryParam.append(item + \"=\" + str(value)) where = \"\" if len(queryParam)",
"label and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\",",
"date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return",
"Return error message if the input is not a number (float) # Return",
"def validator(self): validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue())",
"!= \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] =",
"limit 1', 'select * from stocks order by transaction_date desc limit 1', 'select",
"Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both",
"in items: if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self",
"treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children())",
"else: return None # Return error message if the input is blank #",
"\"%Y-%m-%d\") except ValueError: return errMsg else: return None ## # One label and",
"stocks order by transaction_date desc limit 1', 'select * from stocks order by",
"handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\") return False return True",
"\"Activity Display\" contains two buttons on the top: Summary and Activities class ActivityEntryWindow(tk.Frame):",
"{\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB def updateInfo(self):",
"self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"),",
"UI design ########################### ## # \"Activity Display\" contains two buttons on the top:",
"if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame",
"the error print(e) return False, [] else: return True, fetchResult finally: if conn:",
"messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay",
"conn: conn.close() # Create Table and initialize Data # Transaction Data: yyyy-MM-dd #",
"(mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() ==",
"destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below are database access code",
"ValueError: return errMsg else: return None ## # One label and one combobox",
"focus, focus the input box def focus(self): self.input.focus() # Return the input value",
"return False, [] else: return True, fetchResult finally: if conn: conn.close() # Create",
"returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension",
"queryParam.append(item + \"=\" + str(value)) where = \"\" if len(queryParam) > 0: where",
"datetime import datetime import os import sqlite3 from sqlite3 import Error ## #",
"self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive",
"is not None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children())",
"data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) >",
"state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value",
"self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\",",
"class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in",
"labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6),",
"= LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton",
"self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input",
")[0] return False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow)",
"[ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL',",
"ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent): self.parent",
"Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0]",
"self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value",
"buttons on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame",
"searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if",
"Transaction: Buy/Sell # Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self, withData =",
"self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate, this handler will",
"LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\",",
"# TODO: Log the error print(e) return False, [] else: return True, fetchResult",
"the records # # Author: <NAME> # Date: 2021-03-17 import tkinter as tk",
"2021-03-17 import tkinter as tk from tkinter import ttk, messagebox, filedialog from functools",
"errMsg # Return error message if the input is not in a \"yyyy-MM-dd\"",
"filedialog from functools import partial from datetime import datetime import os import sqlite3",
"= Validator() for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules +",
"class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args,",
"Sqllite database, and one can search and list the records # # Author:",
"not in a \"yyyy-MM-dd\" format # Return None if the input is valid",
"the input is not in a \"yyyy-MM-dd\" format # Return None if the",
"self.validatorArray = validateArray # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9),",
"if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self):",
"%s, %s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are",
"where + ' order by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select *",
"+ ' order by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select * from",
"text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def",
"dataResult return None def listTransactions(self, paramDict={}): queryParam = [] for item, value in",
"TK and database connection # Usage: The user can add a stock record",
"will call validator class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator()",
"record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below are database access",
"two buttons on the top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will be",
"runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) !=",
"size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame,",
"are UI design, below are database access code ######################## ## # Controller: Manipulate",
"self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent,",
"None # Return error message if the input is blank # Return None",
"One label and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\",",
"setInputErrorHandler(self, handler): self.errHandler = handler # The validator. It will call validator class",
"14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary )",
"sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray):",
"is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade =",
"in self.validatorArray: #eval() validationErrors = eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() +",
"#eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the error message",
"want to quit both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea",
"tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self):",
"entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary =",
"items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def",
"exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')])",
"transaction_date asc' ]) if isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess,",
"'select count(id) as trade_times, symbol from stocks group by symbol order by trade_times",
"value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label",
"inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else:",
"The user can add a stock record to Sqllite database, and one can",
"* from stocks order by price asc limit 1', 'select * from stocks",
"!= \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator():",
"layout to group some elements. # Support two layouts: # Use \"h\" to",
"show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll =",
"KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]:",
"self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2]))",
"self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two",
"text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"},",
"AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER, price REAL )'''])[0]: return",
"try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return None ## # One",
"] )[0] return False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass =",
"overwritten in class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent",
"Controller: Manipulate the data and return to View class DataController: def __init__(self, dataFile):",
"will call validator class and loop def validator(self): validator = Validator() for valRules",
"DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not None: summaryResults =",
"None dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets()",
"labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"],",
"recordOnClick(self): inputDict = self.generateParametersDict() # 5 means all items are inputted if len(inputDict)",
"{\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the data from DB def updateInfo(self): dataController =",
"self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All",
"stocks order by transaction_date asc limit 1', 'select * from stocks order by",
"self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame =",
"transaction_date desc limit 1', 'select * from stocks order by price asc limit",
"os import sqlite3 from sqlite3 import Error ## # Validate the input class",
"windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want",
"None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult =",
"('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy',",
"\" + validationErrors) self.input.delete(0,\"end\") return False return True # When focus, focus the",
"self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols",
"packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and pack self.label =",
"in one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol from",
"+ \"')\") if validationErrors != None: # Output the error message to \"error",
"fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\",",
"command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame",
"columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self,",
"def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray)",
"self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1])",
"\"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow = tk.Toplevel(activityDisplayWindow) ActivityEntryWindow(activityEntryWindow, displayWindowClass) activityDisplayWindow.mainloop()",
"Document', '*.txt')]) if destFile is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User",
"'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80,",
"connection # Usage: The user can add a stock record to Sqllite database,",
"\"Value required\" if input != \"\": return None else: return errMsg # Return",
"LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw)",
"if validationErrors != None: # Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"]",
"is a assignment of College. # Purpose: Practice TK and database connection #",
"labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2))",
"size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame,",
"exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def",
"= filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile",
"validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the error message to",
"- \" + validationErrors) self.input.delete(0,\"end\") return False return True # When focus, focus",
"'*.txt')]) if destFile is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\")",
"for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy',",
"Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you",
"= False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date",
"anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and",
"= self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\"",
"self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"},",
"widgets; Below are the UI design ########################### ## # \"Activity Display\" contains two",
"queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return",
"DataController: def __init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile): # Create Data",
"Update the data from DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is",
"add a stock record to Sqllite database, and one can search and list",
"Date: 2021-03-17 import tkinter as tk from tkinter import ttk, messagebox, filedialog from",
"' + where + ' order by transaction_date asc' ]) if isSuccess: return",
"padx=5) return self ############################# Above are the widgets; Below are the UI design",
"LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton =",
"where = \"\" if len(queryParam) > 0: where = \"where \" + \"",
"self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def",
"self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class",
"on the top: Summary and Activities class ActivityDisplayWindow(tk.Frame): summaryFrame = None activitiesDataTableFrame =",
".config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler # The validator. It will call",
"self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20))",
"tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo()",
"asc limit 1', 'select * from stocks order by transaction_date desc limit 1',",
"+ \" and \".join(queryParam) # TODO: put it in debug log #print('select *",
"validateArray # Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\")",
"(?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return isSuccess # Run sql, support",
"as tk from tkinter import ttk, messagebox, filedialog from functools import partial from",
"and database connection # Usage: The user can add a stock record to",
"self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] )",
"text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) #",
"self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) #",
"Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame,",
"if not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData = True): raise Exception(\"Database",
"validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput )",
"+ where + ' order by transaction_date asc' ]) if isSuccess: return dataResult",
"2: fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn = None if",
"if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol",
"None if the input is valid def isDate(self, input): errMsg = \"Please input",
"if destFile is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for",
"MSFT # Transaction: Buy/Sell # Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self,",
"return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [",
"padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate, this handler will display error",
"return dataResult return None def listTransactions(self, paramDict={}): queryParam = [] for item, value",
"to quit both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea =",
"two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton =",
"__init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray",
"messagebox, filedialog from functools import partial from datetime import datetime import os import",
"Error\") validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\" +",
"x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80,",
"self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue()",
"not a number (float) # Return None if the input is valid def",
"input and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState,",
"\"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains",
"= \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self):",
"TODO: Log the error print(e) return False, [] else: return True, fetchResult finally:",
"in paramDict.items(): if type(value) is str: queryParam.append(item + \"='\" + value + \"'\")",
"def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10))",
"if the input is not in a \"yyyy-MM-dd\" format # Return None if",
"self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons on the top: Summary and",
"self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() !=",
"Error ## # Validate the input class Validator: # Return error message if",
"def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parentClass.parent.destroy()",
"fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit() except Error as e: #",
"80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01',",
"sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults",
"database access code ######################## ## # Controller: Manipulate the data and return to",
"Symbol: MSFT # Transaction: Buy/Sell # Quantity: 100 # Transation Price: 12.34 def",
"UI design, below are database access code ######################## ## # Controller: Manipulate the",
"stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100,",
"parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def",
"from stocks order by transaction_date asc limit 1', 'select * from stocks order",
"asc' ]) if isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult",
"margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\",",
"conn = sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) >",
"self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if",
"%s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade",
"filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile is",
"__init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile): # Create Data if not",
"1: True/False for update/delete/insert # return 2: fetch data for select def runSql(self,",
"def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol from stocks', 'select *",
"def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary",
"*args, **kw) def layout(self, layout, *items): if items != None: for item in",
"# Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self, withData = False): if",
"isEmpty(self, input): errMsg = \"Value required\" if input != \"\": return None else:",
"# The validator. It will call validator class and loop def validator(self): self.errHandler.config(text=\"No",
"dataFile): self.db = dataFile if not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData",
"errMsg else: return None ## # One label and one combobox class LabelDDCombo(tk.Frame):",
"<NAME> # Date: 2021-03-17 import tkinter as tk from tkinter import ttk, messagebox,",
"self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and",
"+ self.inputValue.get() + \"')\") if validationErrors != None: # Output the error message",
"needCommit = False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults =",
"self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame,",
"College. # Purpose: Practice TK and database connection # Usage: The user can",
"('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell',",
"Practice TK and database connection # Usage: The user can add a stock",
"100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01',",
"10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return False if __name__ ==",
"entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary =",
"sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if",
"switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage()",
"= tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self):",
"destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above",
"def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension = [('Text Document',",
"batch # return 1: True/False for update/delete/insert # return 2: fetch data for",
"to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\") return False",
"parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item in",
"import Error ## # Validate the input class Validator: # Return error message",
"tkinter import ttk, messagebox, filedialog from functools import partial from datetime import datetime",
"records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')],",
"isSuccess, dataResult = self.runSql([ 'select * from stocks ' + where + '",
"to group some elements. # Support two layouts: # Use \"h\" to pack",
"can add a stock record to Sqllite database, and one can search and",
"== \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\"",
"number.\" try: if input=='NaN': return errMsg float(input) except ValueError: return errMsg else: return",
"self.input.focus() # Return the input value def getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex):",
"validation self.validatorArray = validateArray # Create label and pack self.label = tk.Label(self, text=labelName,",
"100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ]",
"layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self ############################# Above are",
"# Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args,",
"!= None: # Output the error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \"",
"list the records # # Author: <NAME> # Date: 2021-03-17 import tkinter as",
"def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self):",
"sqlStatementParamArray=[]): conn = None if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return",
"if tupleArray is not None: self.clearAll() for row in tupleArray[0]: self.addValues(row) def getRecordsCount(self):",
"handler will display error message. # The handler should be .config(text=XXX) def setInputErrorHandler(self,",
"defaultextension = [('Text Document', '*.txt')]) if destFile is not None: exportResult = DataController(self.dbName).listTransactions()",
"# Date: 2021-03-17 import tkinter as tk from tkinter import ttk, messagebox, filedialog",
"Summary and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor dbName",
"tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick)",
"paramDict.items(): if type(value) is str: queryParam.append(item + \"='\" + value + \"'\") else:",
"activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif",
"input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw):",
"self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame,",
"if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") # get all information",
"= [('Text Document', '*.txt')]) if destFile is not None: exportResult = DataController(self.dbName).listTransactions() if",
"initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks ( id INTEGER PRIMARY KEY",
"is not in a \"yyyy-MM-dd\" format # Return None if the input is",
"command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent)",
"self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\",",
"if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\":",
"in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults =",
"12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT',",
"Usage: The user can add a stock record to Sqllite database, and one",
"contains two buttons on the top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will",
"LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10)",
"'select * from stocks order by price desc limit 1', 'select count(id) as",
"windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\")",
"on the top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in",
"(?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT',",
"= {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if self.symbolInput.getInputValue()",
"else: return True, fetchResult finally: if conn: conn.close() # Create Table and initialize",
"'AAPL', 'sell', 80, 11.3) ] )[0] return False if __name__ == \"__main__\": activityDisplayWindow",
"% self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes = [('Text Document', '*.txt')], defaultextension =",
"label and one input box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\",",
"two layouts: # Use \"h\" to pack horizontally # Use \"v\" to pack",
"fetchResult finally: if conn: conn.close() # Create Table and initialize Data # Transaction",
"print(e) return False, [] else: return True, fetchResult finally: if conn: conn.close() #",
"a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else:",
"self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do",
"margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput",
"the input is valid def isNumber(self,input): errMsg = \"Please input a number.\" try:",
"parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two",
"'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80,",
"'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3),",
"self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Oldest Transaction:\", entryState=\"disabled\", size=(22,22),",
"= LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"],",
"from datetime import datetime import os import sqlite3 from sqlite3 import Error ##",
"exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue()",
"input is not a number (float) # Return None if the input is",
"where = \"where \" + \" and \".join(queryParam) # TODO: put it in",
"# Run sql, support batch # return 1: True/False for update/delete/insert # return",
"%s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade",
"############################# Above are the widgets; Below are the UI design ########################### ## #",
"conn.close() # Create Table and initialize Data # Transaction Data: yyyy-MM-dd # Stock",
"None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s",
"summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" %",
"createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton",
"size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary =",
"self.addValues(row) def getRecordsCount(self): return len(self.treeview.get_children()) ## # A layout to group some elements.",
"**kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the value needs two validation self.validatorArray",
"conn.commit() except Error as e: # TODO: Log the error print(e) return False,",
"size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate,",
"if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self ############################# Above",
"size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame",
"= summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions())",
"are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self):",
"value + \"'\") else: queryParam.append(item + \"=\" + str(value)) where = \"\" if",
"put it in debug log #print('select * from stocks ' + where +",
"Successfully\") ################################# Above are UI design, below are database access code ######################## ##",
"Display\" contains two buttons on the top: Summary and Activities class ActivityEntryWindow(tk.Frame): #",
"values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return isSuccess # Run sql,",
"for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview)",
"if the input is not a number (float) # Return None if the",
"in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the",
"listTransactions(self, paramDict={}): queryParam = [] for item, value in paramDict.items(): if type(value) is",
"user can add a stock record to Sqllite database, and one can search",
"Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and pack",
"dataController = DataController(self.dbName) if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if summaryResults",
"inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def",
"Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if",
"needs two validation self.validatorArray = validateArray # Create label and pack self.label =",
"# 5 means all items are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]):",
"('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell',",
"self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0]))",
"connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol from stocks', 'select",
"return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price)",
"the top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in class",
"Buy/Sell # Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self, withData = False):",
"LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw)",
"## # Validate the input class Validator: # Return error message if the",
"Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary = LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary",
"' order by transaction_date asc' ]) if isSuccess: return dataResult return None def",
"by transaction_date desc limit 1', 'select * from stocks order by price asc",
"('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell',",
"__init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns = list(item[\"colName\"] for item",
"view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns",
"\"\": return None else: return errMsg # Return error message if the input",
"A layout to group some elements. # Support two layouts: # Use \"h\"",
"not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons on the",
"def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if",
"datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return None ## # One label",
"and return to View class DataController: def __init__(self, dataFile): self.db = dataFile if",
"for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None: #",
"\".join(queryParam) # TODO: put it in debug log #print('select * from stocks '",
"## # One label and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label",
"isSuccess: return dataResult return None def listTransactions(self, paramDict={}): queryParam = [] for item,",
"value in paramDict.items(): if type(value) is str: queryParam.append(item + \"='\" + value +",
"self.errHandler = handler # The validator. It will call validator class and loop",
"# Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction: Buy/Sell # Quantity:",
"call validator class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for",
"expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d",
"anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\",",
"* from stocks order by price desc limit 1', 'select count(id) as trade_times,",
"in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"],",
"Data if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") # get all",
"text=\"No Error\", font=(\"Arial\", 10), fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\",",
"#print('select * from stocks ' + where + ' order by transaction_date asc')",
"if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view",
"and list the records # # Author: <NAME> # Date: 2021-03-17 import tkinter",
"parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self):",
"all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are",
"self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\",",
"addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not None:",
"buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\"",
"try: if input=='NaN': return errMsg float(input) except ValueError: return errMsg else: return None",
"mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None:",
"is invalidate, this handler will display error message. # The handler should be",
"None ## # One label and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent,",
"self.input.current(valueIndex) ## # One label and one input box class LabelInputCombo(tk.Frame): def __init__(self,",
"the data and return to View class DataController: def __init__(self, dataFile): self.db =",
"# When the value is invalidate, this handler will display error message. #",
"1', 'select * from stocks order by price asc limit 1', 'select *",
"handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return False return True #",
"in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return None",
"(newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f",
"self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw):",
"!= None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate, this",
"access code ######################## ## # Controller: Manipulate the data and return to View",
"are the widgets; Below are the UI design ########################### ## # \"Activity Display\"",
"tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton)",
"# Transation Price: 12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks",
"stocks group by symbol order by trade_times desc limit 1' ]) if isSuccess:",
"1', 'select count(id) as trade_times, symbol from stocks group by symbol order by",
"topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols",
"elif activity.lower() == \"activities\": if self.summaryFrame is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## #",
"= self.runSql([ 'select distinct symbol from stocks', 'select * from stocks order by",
"## # One label and one input box class LabelInputCombo(tk.Frame): def __init__(self, parent,",
"import sqlite3 from sqlite3 import Error ## # Validate the input class Validator:",
"'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100,",
"# Return error message if the input is not a number (float) #",
"pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input = ttk.Combobox(self, textvariable",
"generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue()",
"\" - \" + validationErrors) return False return True # When focus, focus",
"def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\"))",
"valid def isNumber(self,input): errMsg = \"Please input a number.\" try: if input=='NaN': return",
"self.onClose) # Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to",
"update/delete/insert # return 2: fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]): conn",
"= \"Please input a date in yyyy-MM-dd format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError:",
"self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\",",
"into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return isSuccess",
"= parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def",
"INTEGER PRIMARY KEY AUTOINCREMENT, transaction_date DATE, symbol text, transaction_direction text, Quantity INTEGER, price",
"trade_times desc limit 1' ]) if isSuccess: return dataResult return None def listTransactions(self,",
"self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2]))",
"code ######################## ## # Controller: Manipulate the data and return to View class",
"error message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\")",
"self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None:",
"if isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql(",
"self.parent = parent self.parentClass = parentWindowClass self.dbName = parentWindowClass.dbName self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets()",
"self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"):",
"stocks ' + where + ' order by transaction_date asc') isSuccess, dataResult =",
"False, [] else: return True, fetchResult finally: if conn: conn.close() # Create Table",
"* from stocks order by transaction_date desc limit 1', 'select * from stocks",
"self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in self.validatorArray: #eval() validationErrors = eval(\"validator.\"",
"self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is",
"entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\",",
"order by transaction_date asc') isSuccess, dataResult = self.runSql([ 'select * from stocks '",
"'MSFT', 'sell', 80, 10.3), ('2020-10-01', 'AAPL', 'sell', 80, 11.3) ] )[0] return False",
"validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput = LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\",",
"exportResult: destFile.write(\"User Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\"",
"eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() + \"')\") if validationErrors != None:",
"self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01',",
"if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is",
"class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass =",
"return errMsg float(input) except ValueError: return errMsg else: return None # Return error",
"Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22),",
"dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks",
"class and loop def validator(self): validator = Validator() for valRules in self.validatorArray: #eval()",
"activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() ==",
"if size[0] != None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack",
"assignment of College. # Purpose: Practice TK and database connection # Usage: The",
"updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator():",
"validator.isEmpty(self.getDDValue()) if validationErrors != None: # Output the error message to \"error handler\"",
"Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw)",
"validator. It will call validator class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator",
"needCommit: conn.commit() except Error as e: # TODO: Log the error print(e) return",
"if the input is valid def isEmpty(self, input): errMsg = \"Value required\" if",
"size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame,",
"into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL', 'buy',",
"buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict",
"is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\": if self.summaryFrame is not",
"# Update the data from DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame",
"can search and list the records # # Author: <NAME> # Date: 2021-03-17",
"0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else:",
"View class DataController: def __init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile): #",
"# Transaction: Buy/Sell # Quantity: 100 # Transation Price: 12.34 def initializeDatabase(self, withData",
"finally: if conn: conn.close() # Create Table and initialize Data # Transaction Data:",
"Transation Price: 12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks (",
"the widgets; Below are the UI design ########################### ## # \"Activity Display\" contains",
"anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions =",
"tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When",
"asc limit 1', 'select * from stocks order by price desc limit 1',",
"self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower() == \"summary\": if self.activitiesDataTableFrame is not None:",
"message. # The handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler",
"if len(sqlStatementParamArray) > 0: if len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = []",
"\"isEmpty\"], means the value needs two validation self.validatorArray = validateArray # Create label",
"message to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\") return",
"= \"Value required\" if input != \"\": return None else: return errMsg #",
"error message if the input is not a number (float) # Return None",
"self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[",
"summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade",
") return isSuccess # Run sql, support batch # return 1: True/False for",
"(cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\" % (expensiveTrade[5],expensiveTrade[3],expensiveTrade[2])) mostTrade = summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s",
"= eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() + \"')\") if validationErrors !=",
"Return the input value def getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower()",
"{\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame",
"tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1] !=",
"self.input.delete(0,\"end\") return False return True # When focus, focus the input box def",
"where + ' order by transaction_date asc' ]) if isSuccess: return dataResult return",
"focus(self): self.input.focus() # Return the input value def getInputValue(self): return self.inputValue.get() def setValue(self,",
"self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\") return False return True #",
"\"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\",",
"self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not None: self.clearAll() for row in",
"Validator: # Return error message if the input is not a number (float)",
"# get all information in one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([",
"{\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame =",
"# Author: <NAME> # Date: 2021-03-17 import tkinter as tk from tkinter import",
"else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self): self.dateInput.setValue(\"\") self.symbolInput.setValue(\"\")",
"# Purpose: Practice TK and database connection # Usage: The user can add",
"columns = list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns)",
"entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means",
"if self.summaryFrame is None: self.summaryFrame = LayoutFrame(self.parent) self.uniqueStockSymbols = tk.StringVar() self.oldestTransactionSummary = LabelInputCombo(self.summaryFrame,",
"the input is valid def isEmpty(self, input): errMsg = \"Value required\" if input",
"== \"summary\": if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.grid_forget() self.buildSummaryPage() elif activity.lower() == \"activities\":",
"if needCommit: conn.commit() except Error as e: # TODO: Log the error print(e)",
"are the UI design ########################### ## # \"Activity Display\" contains two buttons on",
"item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr:",
"# Create Data if not self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") #",
"in a \"yyyy-MM-dd\" format # Return None if the input is valid def",
"= tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\",",
"and one can search and list the records # # Author: <NAME> #",
"from tkinter import ttk, messagebox, filedialog from functools import partial from datetime import",
"from DB def updateInfo(self): dataController = DataController(self.dbName) if self.summaryFrame is not None: summaryResults",
"[('Text Document', '*.txt')], defaultextension = [('Text Document', '*.txt')]) if destFile is not None:",
"('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3), ('2020-03-01', 'AAPL', 'sell',",
"clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict = {}",
"if len(queryParam) > 0: where = \"where \" + \" and \".join(queryParam) #",
"def windowSelfConfig(self): self.parent.geometry('400x600+450+20') self.parent.title(\"Activity Entry\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self):",
"list(item[\"colName\"] for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn",
"messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parent.destroy() def createWidgets(self): #",
"= tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is None:",
"blank # Return None if the input is valid def isEmpty(self, input): errMsg",
"It will call validator class and loop def validator(self): self.errHandler.config(text=\"No Error\") validator =",
"get all information in one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select",
"\"')\") if validationErrors != None: # Output the error message to \"error handler\"",
"tk.Label(self.summaryFrame, text=\"Unique Stock Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14),",
"None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the value is invalidate, this handler",
"self.symbolInput.setValue(\"\") self.transationInput.setValue(0) self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d",
"columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set)",
"self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) # Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want",
"labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\",",
"self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame",
"len(sqlStatementArray) != len(sqlStatementParamArray): return False,[] fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit",
"LabelInputCombo(self.summaryFrame, labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\",",
"= summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0] self.mostExpensivePriceSummary.setValue(\"$%0.2f %s %s\"",
"for item in columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in",
"recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame,",
"by transaction_date asc limit 1', 'select * from stocks order by transaction_date desc",
"'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100,",
"validateArray = [\"isNumber\", \"isEmpty\"], means the value needs two validation self.validatorArray = validateArray",
"clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not None: self.clearAll() for row",
"recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def generateParametersDict(self): queryDict =",
"class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args,",
"else: return errMsg # Return error message if the input is not in",
"= True): raise Exception(\"Database Initialize Error\") # get all information in one connection",
"size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput",
"ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8), packSide=\"top\", margin=(2,2))",
"input is valid def isDate(self, input): errMsg = \"Please input a date in",
"activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent): self.parent = parent self.parent.resizable(False, False)",
"range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i])",
"def isEmpty(self, input): errMsg = \"Value required\" if input != \"\": return None",
"str: queryParam.append(item + \"='\" + value + \"'\") else: queryParam.append(item + \"=\" +",
"def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton = tk.Button(buttonsFrame,",
"treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray",
"len(sqlStatementParamArray) > 0: queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"):",
"and initialize Data # Transaction Data: yyyy-MM-dd # Stock Symbol: MSFT # Transaction:",
"100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01',",
"self.activitiesButton = tk.Button(topButtonsArea, text=\"Activities\", command=partial(self.switchButtonOnClick,\"Activities\")) topButtonsArea.layout(\"h\",self.summaryButton, self.activitiesButton).grid(row=0,column=0,pady=10) self.buildSummaryPage() def buildSummaryPage(self): if self.summaryFrame is",
"pady=margin[1]) # When the value is invalidate, this handler will display error message.",
"desc limit 1', 'select count(id) as trade_times, symbol from stocks group by symbol",
"is not None: summaryResults = dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols =",
"class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5, *args,**kw): super().__init__(master=parent, *args, **kw) columns =",
"to pack horizontally # Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self,",
"text=\"search\", command=self.searchOnClick) exportButton = tk.Button(buttonsFrame, text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return",
"Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.newestTransactionSummary = LabelInputCombo(self.summaryFrame, labelName=\"Newest Transaction:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.cheapestPriceSymmary",
"= \"Please input a number.\" try: if input=='NaN': return errMsg float(input) except ValueError:",
"will be overwritten in class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent",
"from stocks ' + where + ' order by transaction_date asc' ]) if",
"Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19)",
"in range(10)], [ ('2020-01-01', 'AAPL', 'buy', 100, 12.3), ('2020-02-01', 'MSFT', 'buy', 80, 8.3),",
"\"('\" + self.inputValue.get() + \"')\") if validationErrors != None: # Output the error",
"None: for item in items: if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left',",
"= dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x",
"self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self, parent, columnsAttr, tableRows=5,",
"size=(8,8), packSide=\"top\", margin=(2,2)) self.quantityInput.setInputErrorHandler(self.errorMessageDisplay) self.priceInput = LabelInputCombo(dataInputFrame, labelName=\"Price\", validateArray=[\"isNumber\", \"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2))",
"price desc limit 1', 'select count(id) as trade_times, symbol from stocks group by",
"\"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args,",
"**kw) def layout(self, layout, *items): if items != None: for item in items:",
"aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0)",
"]) if isSuccess: return dataResult return None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult =",
"# One label and one combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\",",
"some elements. # Support two layouts: # Use \"h\" to pack horizontally #",
"DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all",
"be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler # The validator. It will",
"True # When focus, focus the input box def focus(self): self.input.focus() # Return",
"getDDValue(self): return self.inputValue.get() def setValue(self, valueIndex): self.input.current(valueIndex) ## # One label and one",
"are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions() self.parentClass.updateInfo() self.clearOnClick() self.errorMessageDisplay.config(text=\"Insert Successfully\")",
"!= None: for item in items: if layout == \"v\": item.pack(side='top', pady=5) else:",
"% (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0] self.cheapestPriceSymmary.setValue(\"$%0.2f %s %s\" % (cheapestTrade[5],cheapestTrade[3],cheapestTrade[2])) expensiveTrade = summaryResults[4][0]",
"# \"Activity Display\" contains two buttons on the top: Summary and Activities class",
"dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay)",
"Symbols\", font=(\"Arial\", 14), anchor=\"w\"), tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\",",
"validator. It will call validator class and loop def validator(self): validator = Validator()",
"= \"\" if len(queryParam) > 0: where = \"where \" + \" and",
"price asc limit 1', 'select * from stocks order by price desc limit",
"self.dateInput.getInputValue() if self.symbolInput.getInputValue() != \"\" and self.symbolInput.validator(): queryDict[\"symbol\"] = self.symbolInput.getInputValue() if self.transationInput.getDDValue() !=",
"% (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade = summaryResults[3][0]",
"def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you",
"to \"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return False return",
"summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" %",
"fetchResult = [] try: conn = sqlite3.connect(self.db) needCommit = False for i in",
"call validator class and loop def validator(self): validator = Validator() for valRules in",
"self.input.focus() # Return the input value def getInputValue(self): return self.inputValue.get() def setValue(self, value):",
"\" + \" and \".join(queryParam) # TODO: put it in debug log #print('select",
"pady=5) else: item.pack(side='left', padx=5) return self ############################# Above are the widgets; Below are",
"This project is a assignment of College. # Purpose: Practice TK and database",
"search and list the records # # Author: <NAME> # Date: 2021-03-17 import",
"The handler should be .config(text=XXX) def setInputErrorHandler(self, handler): self.errHandler = handler # The",
"from stocks', 'select * from stocks order by transaction_date asc limit 1', 'select",
"\"'\") else: queryParam.append(item + \"=\" + str(value)) where = \"\" if len(queryParam) >",
"self.errorMessageDisplay.config(text=\"Insert Successfully\") else: self.errorMessageDisplay.config(text=\"Insert Fail.\") else: self.errorMessageDisplay.config(text=\"Please complete all input items\") def clearOnClick(self):",
"('2020-06-01', 'AAPL', 'buy', 100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy',",
"validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in self.validatorArray: #eval() validationErrors =",
"= ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def addValues(self,valueArray): self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def",
"self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent)",
"pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"},",
"input is valid def isEmpty(self, input): errMsg = \"Value required\" if input !=",
"validationErrors = eval(\"validator.\" + valRules + \"('\" + self.inputValue.get() + \"')\") if validationErrors",
"\"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def",
"self ############################# Above are the widgets; Below are the UI design ########################### ##",
"input box def focus(self): self.input.focus() # Return the input value def getDDValue(self): return",
"cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile",
"self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) return False return True # When",
"= dataFile if not os.path.exists(dataFile): # Create Data if not self.initializeDatabase(withData = True):",
"= LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\", margin=(1,1)) self.dateInput.setInputErrorHandler(self.errorMessageDisplay) self.symbolInput",
"*args, **kw): super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if items != None:",
"'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL', 'sell', 100, 9.3), ('2020-06-01', 'AAPL', 'buy', 100,",
"dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity,",
"error print(e) return False, [] else: return True, fetchResult finally: if conn: conn.close()",
"is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record in",
"[\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in range(10)], [ ('2020-01-01', 'AAPL',",
"ttk, messagebox, filedialog from functools import partial from datetime import datetime import os",
"\"isEmpty\"], size=(5,6), packSide=\"top\", margin=(2,2)) self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return",
"the input box def focus(self): self.input.focus() # Return the input value def getInputValue(self):",
"'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01', 'MSFT', 'sell', 80, 10.3),",
"by price asc limit 1', 'select * from stocks order by price desc",
"== \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return self ############################# Above are the",
"onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit both two windows?\"): self.parentClass.parent.destroy() def",
"Use \"h\" to pack horizontally # Use \"v\" to pack vertically class LayoutFrame(tk.Frame):",
"None: self.label.config(width=size[0]) self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar()",
"for item in items: if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5)",
"isDate(self, input): errMsg = \"Please input a date in yyyy-MM-dd format.\" try: datetime.strptime(input,",
"\"\" if len(queryParam) > 0: where = \"where \" + \" and \".join(queryParam)",
"# TODO: put it in debug log #print('select * from stocks ' +",
"= sqlite3.connect(self.db) needCommit = False for i in range(len(sqlStatementArray)): if len(sqlStatementParamArray) > 0:",
"self.initializeDatabase(withData = True): raise Exception(\"Database Initialize Error\") # get all information in one",
"is not None: self.summaryFrame.grid_forget() self.buildActivitiesPage() ## # \"Activity Display\" contains two buttons on",
"labelName=\"Cheapest Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22),",
"isSuccess # Run sql, support batch # return 1: True/False for update/delete/insert #",
"REAL )'''])[0]: return self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\" for x in",
"def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"], size=(5,10), packSide=\"top\",",
"data and return to View class DataController: def __init__(self, dataFile): self.db = dataFile",
"+ \"='\" + value + \"'\") else: queryParam.append(item + \"=\" + str(value)) where",
"= LabelInputCombo(self.summaryFrame, labelName=\"Most Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14),",
"symbol order by trade_times desc limit 1' ]) if isSuccess: return dataResult return",
"False if __name__ == \"__main__\": activityDisplayWindow = tk.Tk() displayWindowClass = ActivityDisplayWindow(activityDisplayWindow) activityEntryWindow =",
"{\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self):",
"self.priceInput.setInputErrorHandler(self.errorMessageDisplay) dataInputFrame.layout('h', self.dateInput, self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame",
"self.symbolInput, self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton",
"OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s",
"return errMsg else: return None ## # One label and one combobox class",
"self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value) # Table view class TreeViewWithScrollBar(tk.Frame): def __init__(self,",
"\"error handler\" self.errHandler.config(text=self.label[\"text\"] + \" - \" + validationErrors) self.input.delete(0,\"end\") return False return",
"summaryResults[5][0] self.mostTradedStockSummary.setValue(\"%s (%d Transactions)\" % (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def",
"(transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol, trans, quantity, price)] ) return isSuccess # Run",
"loop def validator(self): self.errHandler.config(text=\"No Error\") validator = Validator() for valRules in self.validatorArray: #eval()",
"# A layout to group some elements. # Support two layouts: # Use",
"self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"},",
"if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit: conn.commit() except Error as",
"Activity\") for record in exportResult[0]: destFile.write(\"\\n%d, %s, %s, %s, %d, %.2f\" % record)",
"= self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict",
"return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\")",
"a number.\" try: if input=='NaN': return errMsg float(input) except ValueError: return errMsg else:",
"> 0: where = \"where \" + \" and \".join(queryParam) # TODO: put",
"errMsg = \"Value required\" if input != \"\": return None else: return errMsg",
"text=\"Export\", command=self.exportOnClick) buttonsFrame.layout('h', recordButton, clearButton, searchButton, exportButton) return buttonsFrame def updateTransactions(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions()) def",
"are database access code ######################## ## # Controller: Manipulate the data and return",
"fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent) self.dateInput = LabelInputCombo(dataInputFrame, labelName=\"Date\", validateArray=[\"isDate\", \"isEmpty\"],",
"summaryFrame = None activitiesDataTableFrame = None dbName = \"stocks.db\" def __init__(self,parent): self.parent =",
"# Create label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if",
"item in items: if layout == \"v\": item.pack(side='top', pady=5) else: item.pack(side='left', padx=5) return",
"quit both two windows?\"): self.parent.destroy() def createWidgets(self): # self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent)",
"columnsAttr) self.treeview = ttk.Treeview(self, height=tableRows, show=\"headings\", columns=columns) for aColumn in columnsAttr: self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"],",
"from stocks group by symbol order by trade_times desc limit 1' ]) if",
"records # # Author: <NAME> # Date: 2021-03-17 import tkinter as tk from",
"= self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and self.quantityInput.validator(): queryDict[\"Quantity\"] = self.quantityInput.getInputValue() if self.priceInput.getInputValue()",
"parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray =",
"= [] for item, value in paramDict.items(): if type(value) is str: queryParam.append(item +",
"the input value def getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() ==",
"top: Summary and Activities class ActivityEntryWindow(tk.Frame): # will be overwritten in class constructor",
"for update/delete/insert # return 2: fetch data for select def runSql(self, sqlStatementArray, sqlStatementParamArray=[]):",
"summaryResults = dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for",
"the input is not a number (float) # Return None if the input",
"## # Controller: Manipulate the data and return to View class DataController: def",
"entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostExpensivePriceSummary = LabelInputCombo(self.summaryFrame, labelName=\"Most Expensive Price:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.mostTradedStockSummary",
"LabelInputCombo(dataInputFrame, labelName=\"Symbol\", validateArray=[\"isEmpty\"], size=(6,6), packSide=\"top\", margin=(2,2)) self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\",",
"not None: summaryResults = dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols = summaryResults[0]",
"labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and",
"buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"},",
"self.transationInput, self.quantityInput, self.priceInput ) return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton =",
"## # \"Activity Display\" contains two buttons on the top: Summary and Activities",
"def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) #",
"you want to quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent,",
"8.3), ('2020-03-01', 'AAPL', 'sell', 80, 10.3), ('2020-04-01', 'MSFT', 'sell', 80, 10.4), ('2020-05-01', 'AAPL',",
"self.symbolInput.getInputValue() if self.transationInput.getDDValue() != \"\": queryDict[\"transaction_direction\"] = self.transationInput.getDDValue() if self.quantityInput.getInputValue() != \"\" and",
"a assignment of College. # Purpose: Practice TK and database connection # Usage:",
"{\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price\",\"width\":60,\"anchor\":\"center\"}],tableRows=19) self.allTransactions.pack(side=\"top\", pady=(10,0), fill=\"both\") self.errorMessageDisplay.pack(side=\"bottom\", fill=\"x\") self.updateTransactions() def dataInputForm(self): dataInputFrame = LayoutFrame(self.parent)",
"class DataController: def __init__(self, dataFile): self.db = dataFile if not os.path.exists(dataFile): # Create",
"True, fetchResult finally: if conn: conn.close() # Create Table and initialize Data #",
"queryParam = [] for item, value in paramDict.items(): if type(value) is str: queryParam.append(item",
"by price desc limit 1', 'select count(id) as trade_times, symbol from stocks group",
"Traded Stock:\", entryState=\"disabled\", size=(22,22), margin=(2,2)) self.summaryFrame.layout(\"v\", tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Unique",
"below are database access code ######################## ## # Controller: Manipulate the data and",
"self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities Display\") self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose) def onClose(self): if messagebox.askokcancel(\"Quit\",",
"= self.generateParametersDict() # 5 means all items are inputted if len(inputDict) == 5:",
"5 means all items are inputted if len(inputDict) == 5: if DataController(self.dbName).addTransaction(inputDict[\"transaction_date\"],inputDict[\"symbol\"],inputDict[\"transaction_direction\"],inputDict[\"Quantity\"],inputDict[\"price\"]): self.updateTransactions()",
"margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create label and pack self.label = tk.Label(self, text=labelName,",
"format # Return None if the input is valid def isDate(self, input): errMsg",
"self.treeview.column(aColumn[\"colName\"], width=aColumn[\"width\"], anchor=aColumn[\"anchor\"]) self.treeview.heading(aColumn[\"colName\"], text=aColumn[\"colName\"]) treeScroll = ttk.Scrollbar(self, orient=\"vertical\",command=self.treeview.yview) self.treeview.grid(row=0,column=0) treeScroll.grid(row=0,column=1,sticky=\"NSEW\") self.treeview.configure(yscrollcommand=treeScroll.set) def",
"= TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"}, {\"colName\":\"Date\",\"width\":100,\"anchor\":\"center\"}, {\"colName\":\"Symbol\",\"width\":80,\"anchor\":\"center\"}, {\"colName\":\"Transation\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Quantity\",\"width\":70,\"anchor\":\"center\"}, {\"colName\":\"Price$\",\"width\":60,\"anchor\":\"center\"}],tableRows=26) self.activitiesDataTableFrame.grid(row=1,column=0) self.updateInfo() # Update the",
"item, value in paramDict.items(): if type(value) is str: queryParam.append(item + \"='\" + value",
"super().__init__(master=parent, *args, **kw) def layout(self, layout, *items): if items != None: for item",
"14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if",
"None def addTransaction(self, transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values",
"queryDict = {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] = self.dateInput.getInputValue() if",
"tk.Listbox(self.summaryFrame, listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary,",
"values=ddItems) self.input.current(0) if size[1] != None: self.input.config(width=size[1]) self.input.pack(side=packSide, padx=(0,margin[0]), pady=margin[1]) # When the",
"= tk.StringVar() self.input = ttk.Combobox(self, textvariable = self.inputValue, state=entryState, values=ddItems) self.input.current(0) if size[1]",
"quit both two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\",",
"def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not None: self.clearAll() for",
"listvariable=self.uniqueStockSymbols), tk.Label(self.summaryFrame, text=\"\", font=(\"Arial\", 14), anchor=\"w\"), tk.Label(self.summaryFrame, text=\"Summary\", font=(\"Arial\", 14), anchor=\"w\"), self.oldestTransactionSummary, self.newestTransactionSummary,",
"box class LabelInputCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent,",
"self.oldestTransactionSummary, self.newestTransactionSummary, self.cheapestPriceSymmary, self.mostExpensivePriceSummary, self.mostTradedStockSummary ) self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is",
"handler # The validator. It will call validator class and loop def validator(self):",
"= summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\"",
"self.symbolInput.setInputErrorHandler(self.errorMessageDisplay) self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\",",
"input value def getInputValue(self): return self.inputValue.get() def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\":",
"% record) destFile.close() self.errorMessageDisplay.config(text=\"Export Successfully\") ################################# Above are UI design, below are database",
"self.uniqueStockSymbols.set([x[0] for x in tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2]))",
"information in one connection def getSummaryInfo(self): isSuccess, dataResult = self.runSql([ 'select distinct symbol",
"if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if summaryResults is not None:",
"invalidate, this handler will display error message. # The handler should be .config(text=XXX)",
"format.\" try: datetime.strptime(input, \"%Y-%m-%d\") except ValueError: return errMsg else: return None ## #",
"self.parent.rowconfigure(0,weight=1) self.parent.columnconfigure(0,weight=1) topButtonsArea = LayoutFrame(self.parent) self.summaryButton = tk.Button(topButtonsArea, text=\"Summary\", command=partial(self.switchButtonOnClick,\"summary\")) self.activitiesButton = tk.Button(topButtonsArea,",
"and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] !=",
"]) if isSuccess: return dataResult return None def listTransactions(self, paramDict={}): queryParam = []",
"self.quantityInput.setValue(\"\") self.priceInput.setValue(\"\") self.errorMessageDisplay.config(text=\"All inputs are cleared\") def searchOnClick(self): self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\"",
"else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit = True if needCommit:",
"if the input is valid def isNumber(self,input): errMsg = \"Please input a number.\"",
"__init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent, *args, **kw) # Create",
"1' ]) if isSuccess: return dataResult return None def listTransactions(self, paramDict={}): queryParam =",
"return dataInputFrame def buttons(self): buttonsFrame = LayoutFrame(self.parent) recordButton = tk.Button(buttonsFrame, text=\"Record\", command=self.recordOnClick) clearButton",
"# Return None if the input is valid def isDate(self, input): errMsg =",
"% (mostTrade[1],mostTrade[0])) if self.activitiesDataTableFrame is not None: self.activitiesDataTableFrame.setValues(dataController.listTransactions()) def switchButtonOnClick(self, activity): if activity.lower()",
") self.summaryFrame.grid(row=1,column=0) self.updateInfo() def buildActivitiesPage(self): if self.activitiesDataTableFrame is None: self.activitiesDataTableFrame = TreeViewWithScrollBar(self.parent,[ {\"colName\":\"ID\",\"width\":10,\"anchor\":\"center\"},",
"stock record to Sqllite database, and one can search and list the records",
"transDate,symbol,trans,quantity,price): isSuccess, dataResult = self.runSql( [\"insert into stocks (transaction_date,symbol,transaction_direction,Quantity,price) values (?,?,?,?,?)\"], [(transDate, symbol,",
"will display error message. # The handler should be .config(text=XXX) def setInputErrorHandler(self, handler):",
"dataController.getSummaryInfo() if summaryResults is not None: tradeSymbols = summaryResults[0] self.uniqueStockSymbols.set([x[0] for x in",
"# Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw):",
"Use \"v\" to pack vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent,",
"= handler # The validator. It will call validator class and loop def",
"def __init__(self,parent): self.parent = parent self.parent.resizable(False, False) self.windowSelfConfig() self.createWidgets() def windowSelfConfig(self): self.parent.geometry('400x600+20+20') self.parent.title(\"Activities",
"input=='NaN': return errMsg float(input) except ValueError: return errMsg else: return None # Return",
"is valid def isDate(self, input): errMsg = \"Please input a date in yyyy-MM-dd",
"self.transationInput = LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\",",
"DataController(self.dbName) if self.summaryFrame is not None: summaryResults = dataController.getSummaryInfo() if summaryResults is not",
"command=self.recordOnClick) clearButton = tk.Button(buttonsFrame, text=\"Clear\", command=self.clearOnClick) searchButton = tk.Button(buttonsFrame, text=\"search\", command=self.searchOnClick) exportButton =",
"# Destroy parent window def onClose(self): if messagebox.askokcancel(\"Quit\", \"Do you want to quit",
"def generateParametersDict(self): queryDict = {} if self.dateInput.getInputValue() != \"\" and self.dateInput.validator(): queryDict[\"transaction_date\"] =",
"queryResults = conn.execute(sqlStatementArray[i], sqlStatementParamArray[i]) else: queryResults = conn.execute(sqlStatementArray[i]) if sqlStatementArray[i].strip().lower().startswith(\"select\"): fetchResult.append(queryResults.fetchall()) else: needCommit",
"100, 14.3), ('2020-07-01', 'MSFT', 'buy', 100, 16.3), ('2020-08-01', 'AAPL', 'buy', 100, 6.3), ('2020-09-01',",
"vertically class LayoutFrame(tk.Frame): def __init__(self, parent, *args, **kw): super().__init__(master=parent, *args, **kw) def layout(self,",
"Create input and pack self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if",
"constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass): self.parent = parent self.parentClass = parentWindowClass",
"if input != \"\": return None else: return errMsg # Return error message",
"%s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s %s %s\" % (newestTrade[1],newestTrade[3],newestTrade[2])) cheapestTrade =",
"def setValue(self, value): if self.input[\"state\"].lower() == \"disabled\": self.input.config(state=\"normal\") self.input.delete(0,\"end\") self.input.insert(0,value) self.input.config(state=\"disabled\") self.input.delete(0,\"end\") self.input.insert(0,value)",
"transaction_date asc limit 1', 'select * from stocks order by transaction_date desc limit",
"self.treeview.insert('','end',values=valueArray) def clearAll(self): self.treeview.delete(*self.treeview.get_children()) def setValues(self, tupleArray): if tupleArray is not None: self.clearAll()",
"label and pack self.label = tk.Label(self, text=labelName, font=(\"Courier\",9), fg=\"#333\", anchor=\"e\") if size[0] !=",
"order by trade_times desc limit 1' ]) if isSuccess: return dataResult return None",
"fg=\"red\", anchor=\"w\") self.dataInputForm().pack(side=\"top\", pady=(20,10)) self.buttons().pack(side=\"top\", pady=(0,20)) tk.Label(self.parent, text=\"All Transactions\", font=(\"Arial\", 14), anchor=\"w\").pack(side=\"top\") self.allTransactions",
"Validator() for valRules in self.validatorArray: #eval() validationErrors = validator.isEmpty(self.getDDValue()) if validationErrors != None:",
"tradeSymbols]) OldestTrade = summaryResults[1][0] self.oldestTransactionSummary.setValue(\"%s %s %s\" % (OldestTrade[1],OldestTrade[3],OldestTrade[2])) newestTrade = summaryResults[2][0] self.newestTransactionSummary.setValue(\"%s",
"self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def recordOnClick(self): inputDict",
"destFile is not None: exportResult = DataController(self.dbName).listTransactions() if exportResult: destFile.write(\"User Activity\") for record",
"the value is invalidate, this handler will display error message. # The handler",
"self.inputValue = tk.StringVar() self.input = tk.Entry(self, textvariable=self.inputValue, state=entryState) if size[1] != None: self.input.config(width=size[1])",
"from stocks order by price asc limit 1', 'select * from stocks order",
"combobox class LabelDDCombo(tk.Frame): def __init__(self, parent, labelName=\"Label Name\", entryState=\"normal\", packSide=\"left\", size=(0,0), margin=(0,0),ddItems=[],*args,**kw): super().__init__(master=parent,",
"Log the error print(e) return False, [] else: return True, fetchResult finally: if",
"Price: 12.34 def initializeDatabase(self, withData = False): if self.runSql(['''CREATE TABLE stocks ( id",
"two windows?\"): self.parentClass.parent.destroy() def createWidgets(self): self.errorMessageDisplay = tk.Label(self.parent, text=\"No Error\", font=(\"Arial\", 10), fg=\"red\",",
"design ########################### ## # \"Activity Display\" contains two buttons on the top: Summary",
"return None # Return error message if the input is blank # Return",
"LabelDDCombo(dataInputFrame, labelName=\"Transation\", ddItems=[\"\",\"buy\",\"sell\"], size=(10,5),entryState=\"readonly\",packSide=\"top\", margin=(2,2)) self.transationInput.setInputErrorHandler(self.errorMessageDisplay) self.quantityInput = LabelInputCombo(dataInputFrame, labelName=\"Quantity\", validateArray=[\"isNumber\", \"isEmpty\"], size=(8,8),",
"size=(0,0), margin=(0,0),validateArray=[],*args,**kw): super().__init__(master=parent, *args, **kw) # validateArray = [\"isNumber\", \"isEmpty\"], means the value",
"self.quantityInput.getInputValue() if self.priceInput.getInputValue() != \"\" and self.priceInput.validator(): queryDict[\"price\"] = self.priceInput.getInputValue() return queryDict def",
"self.label.pack(side=packSide, padx=(margin[0],0), pady=margin[1]) # Create input and pack self.inputValue = tk.StringVar() self.input =",
"+ ' order by transaction_date asc' ]) if isSuccess: return dataResult return None",
"self.allTransactions.setValues(DataController(self.dbName).listTransactions(self.generateParametersDict())) self.errorMessageDisplay.config(text=\" %d records returned\" % self.allTransactions.getRecordsCount()) def exportOnClick(self): destFile = filedialog.asksaveasfile(filetypes =",
"# will be overwritten in class constructor dbName = \"stocks_test.db\" def __init__(self,parent, parentWindowClass):",
"True if needCommit: conn.commit() except Error as e: # TODO: Log the error",
"= self.runSql([ 'select * from stocks ' + where + ' order by"
] |
[
"== old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat",
"self.read() while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now",
"= datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream =",
"modified data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals",
"\"\"\" print(out) def run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream = self.read()",
"block :param stream: stream to read :type stream: six.BytesIO :param dict block: start",
"be refreshed \"\"\" print(out) def run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream",
":param stream: stream to read :type stream: six.BytesIO :param dict block: start offset,",
"raw data \"\"\" start = int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return",
"what to' ' diff check inside of block with given offsets'), required=True) arguments",
"word_size, *old) processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new)",
") return nodes class Spy(object): \"\"\" Changes spy :param str filename: path inspected",
"os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path)",
"do as this is leaf :param element: :return: None \"\"\" @staticmethod def unpack(value,",
"return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\"",
"stream withing given block :param stream: stream to read :type stream: six.BytesIO :param",
"return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source to list of equal",
"sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls save",
"modifications .. module:: watcher :platform: Linux, Windows, MacOS X :synopsis: watches for dark",
"'use data inside of json file for choosing what to' ' diff check",
"= size self.old = old self.new = new def add(self, element): \"\"\" nothing",
"offset, size to read :rtype: str :return: raw data \"\"\" start = int(block['start'],",
"%(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value':",
"def add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start,",
"idx * word_size if old == new: continue #: todo decide what's version",
"datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read()",
"to read :rtype: str :return: raw data \"\"\" start = int(block['start'], 16) size",
"= stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in",
"size = int(block['size'], 16) + idx * word_size start = int(block['start'], 16) +",
"x.is_dir()).path else: for root, directory, files in os.walk(prefix): for filename in files: if",
"bytestring and iterate through it coverts chars back to #: int there's only",
"file for choosing what to' ' diff check inside of block with given",
"nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes class Spy(object): \"\"\" Changes spy",
"import unicode_literals import os import sys import six import struct import json import",
"cli :keyword int start_offset: start inspections with given offset :keyword int start_offset: end",
"in diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\" running on windows it",
"os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime ==",
"new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers = watchers def",
":type stream: six.BytesIO :param dict block: start offset, size to read :rtype: str",
"and prints any modified data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from",
"os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object):",
"ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting",
"drop downs. processed_old = old processed_new = new if isinstance(old, list) and isinstance(new,",
"'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old': old, 'old_hex': old, 'follow':",
">= (3, 5): path = next(x for x in os.scandir(prefix) if x.is_dir()).path else:",
"self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate( zip(text_wrap(old_data,",
"unicode_literals import os import sys import six import struct import json import argparse",
"watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally:",
"self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start, size, old, new):",
"self.start = start self.size = size self.old = old self.new = new def",
"\"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source to list of",
"darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w',",
"_wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream =",
"\"\"\" wrap source to list of equal parts :param str source: source to",
"nothing to do as this is leaf :param element: :return: None \"\"\" @staticmethod",
"): size = int(block['size'], 16) + idx * word_size start = int(block['start'], 16)",
"nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json file for choosing what to'",
"import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks",
"dict skip_table: skip some data which is represented in table stored in dict",
"location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file =",
"size to read :rtype: str :return: raw data \"\"\" start = int(block['start'], 16)",
"= pack('B' * word_size, *old) processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start,",
"word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes class Spy(object): \"\"\"",
"-* \"\"\" DSFP modifications spy, looks for save file modifications .. module:: watcher",
"from time import sleep from datetime import datetime from textwrap import wrap from",
"KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ == '__main__': parser =",
"spy, looks for save file modifications .. module:: watcher :platform: Linux, Windows, MacOS",
"ns.filename or get_default_file_name() watchers = [] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read()))",
"text_wrap(new_data, word_size)) ): size = int(block['size'], 16) + idx * word_size start =",
"for node in diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\" running on",
"new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\"",
"python would be #: more prioritized as textwrap.wrap does not work with #:",
"log into the main window :keyword bool refresh: True if should be refreshed",
"block) for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size",
":keyword int slot: character slot :keyword dict skip_table: skip some data which is",
"read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into",
"self.old_stream = old_stream self.watchers = watchers def read_stream(self, stream, block): \"\"\" read stream",
"sleep from datetime import datetime from textwrap import wrap from struct import pack,",
"= self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" %",
"process_diff(self, word_size=4): \"\"\" processes diff :param int word_size: word size for diff processing",
"for filename in files: if filename == default_file: path = os.path.join(prefix, root) break",
"metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json file for choosing what",
"looks for save file modifications .. module:: watcher :platform: Linux, Windows, MacOS X",
"'--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'),",
"def __init__(self): self.children = [] def add(self, element): self.children.append(element) class Leaf(Node): __slots__ =",
"if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls save file.'",
"file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of",
"'value': new, 'hex': new, 'old': old, 'old_hex': old, 'follow': '<-' } ) return",
"def __init__(self, start, size, old, new): super(Leaf, self).__init__() self.start = start self.size =",
"old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers = watchers def read_stream(self,",
"Changes spy :param str filename: path inspected filename :keyword int slot: character slot",
"= os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns): filename = ns.filename or",
"only :param str source: source to wrap :param int parts: N equal parts",
"idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'],",
"== new: continue #: todo decide what's version of python would be #:",
"return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param int word_size: word size",
"list): processed_old = pack('B' * word_size, *old) processed_new = pack('B' * word_size, *new)",
":rtype: list[str] :return: list of str with N or equal length \"\"\" return",
"def log(out): \"\"\" log into the main window :keyword bool refresh: True if",
"wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream,",
"%s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff =",
"if x.is_dir()).path else: for root, directory, files in os.walk(prefix): for filename in files:",
"in files: if filename == default_file: path = os.path.join(prefix, root) break return os.path.join(path,",
"['start', 'size'] def __init__(self, start, size, old, new): super(Leaf, self).__init__() self.start = start",
"%(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old':",
"Windows, MacOS X :synopsis: watches for dark souls save file modifications and prints",
"element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start, size, old,",
"path = next(x for x in os.scandir(prefix) if x.is_dir()).path else: for root, directory,",
"files in os.walk(prefix): for filename in files: if filename == default_file: path =",
"self.new_stream = new_stream self.old_stream = old_stream self.watchers = watchers def read_stream(self, stream, block):",
"self.watchers: for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream,",
"them back in #: python 3+ which could give performance drop downs. processed_old",
"new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node)",
"add(self, element): \"\"\" nothing to do as this is leaf :param element: :return:",
"convert/pack them back in #: python 3+ which could give performance drop downs.",
"old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat =",
"dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data",
":rtype: list[Leaf] :return: diffs \"\"\" nodes = [] for table in self.watchers: for",
"for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size =",
"= int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4):",
"json file for choosing what to' ' diff check inside of block with",
"length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source to list",
"to wrap :param int parts: N equal parts :rtype: list[str] :return: list of",
"= NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified += 1 def",
"in os.walk(prefix): for filename in files: if filename == default_file: path = os.path.join(prefix,",
"new_stream self.old_stream = old_stream self.watchers = watchers def read_stream(self, stream, block): \"\"\" read",
"run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream = self.read() while 1: sleep(1)",
"Leaf(start, size, processed_old, processed_new) ) return nodes class Spy(object): \"\"\" Changes spy :param",
"= self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate(",
"and isinstance(new, list): processed_old = pack('B' * word_size, *old) processed_new = pack('B' *",
"list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source to list of equal parts",
"parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers):",
"= int(block['size'], 16) + idx * word_size start = int(block['start'], 16) + idx",
"modified = 0 old_stat = os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat",
"would get default draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file location \"\"\"",
"stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param int word_size: word size for",
"x in os.scandir(prefix) if x.is_dir()).path else: for root, directory, files in os.walk(prefix): for",
"print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff",
"equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source to",
"equal parts :param str source: source to wrap :param int parts: N equal",
"character slot :keyword dict skip_table: skip some data which is represented in table",
"parser = argparse.ArgumentParser( description='Prints changes for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2',",
"\"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start,",
"struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import",
"for diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes = [] for table",
"as textwrap.wrap does not work with #: bytestring and iterate through it coverts",
"processed_new = new if isinstance(old, list) and isinstance(new, list): processed_old = pack('B' *",
"return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the main window :keyword bool",
"(3, 5): path = next(x for x in os.scandir(prefix) if x.is_dir()).path else: for",
"inside of json file for choosing what to' ' diff check inside of",
"offset \"\"\" def __init__(self, filename, watchers=None): self.filename = filename self.watchers = watchers def",
"while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now =",
"= 0 old_stat = os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat =",
":return: list of str with N or equal length \"\"\" if six.PY2: return",
"new, 'hex': new, 'old': old, 'old_hex': old, 'follow': '<-' } ) return fmt",
"with given offset \"\"\" def __init__(self, filename, watchers=None): self.filename = filename self.watchers =",
"root, directory, files in os.walk(prefix): for filename in files: if filename == default_file:",
"PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path): return",
"argparse from time import sleep from datetime import datetime from textwrap import wrap",
"stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param int word_size: word",
"os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\" %",
"def text_wrap(source, parts): \"\"\" wrap source to list of equal parts :param str",
"self.start def _wrap(source, parts): \"\"\" wrap source to list of equal parts python",
"new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16) +",
":param dict block: start offset, size to read :rtype: str :return: raw data",
"'--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json file for",
"use_curses: use curses interface instead of standard cli :keyword int start_offset: start inspections",
"@staticmethod def log(out): \"\"\" log into the main window :keyword bool refresh: True",
"filename == default_file: path = os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns):",
"or equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap source",
"moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import os import sys import",
"str :return: draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path",
"<<EMAIL>> \"\"\" from __future__ import unicode_literals import os import sys import six import",
"parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream",
"element): \"\"\" nothing to do as this is leaf :param element: :return: None",
":return: diffs \"\"\" nodes = [] for table in self.watchers: for block in",
"'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5):",
"in os.scandir(prefix) if x.is_dir()).path else: for root, directory, files in os.walk(prefix): for filename",
"word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16) + idx * word_size start",
"os.walk(prefix): for filename in files: if filename == default_file: path = os.path.join(prefix, root)",
"if isinstance(old, list) and isinstance(new, list): processed_old = pack('B' * word_size, *old) processed_new",
"prioritized as textwrap.wrap does not work with #: bytestring and iterate through it",
"stream: stream to read :type stream: six.BytesIO :param dict block: start offset, size",
"type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use",
"data inside of json file for choosing what to' ' diff check inside",
"None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new =",
":platform: Linux, Windows, MacOS X :synopsis: watches for dark souls save file modifications",
"offset :keyword int start_offset: end inspections with given offset \"\"\" def __init__(self, filename,",
"wrap source to list of equal parts python 3+ only :param str source:",
"module:: watcher :platform: Linux, Windows, MacOS X :synopsis: watches for dark souls save",
"[] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try:",
"not work with #: bytestring and iterate through it coverts chars back to",
"inspections with given offset \"\"\" def __init__(self, filename, watchers=None): self.filename = filename self.watchers",
"fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt",
"for x in os.scandir(prefix) if x.is_dir()).path else: for root, directory, files in os.walk(prefix):",
"import sleep from datetime import datetime from textwrap import wrap from struct import",
"wrap from struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from",
"NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified += 1 def get_default_file_name():",
"list of str with N or equal length \"\"\" if six.PY2: return wrap(source,",
"default draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file location \"\"\" prefix =",
"* word_size, *old) processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old,",
"required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json",
"block) new_data = self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size),",
"Linux, Windows, MacOS X :synopsis: watches for dark souls save file modifications and",
"souls save file modifications and prints any modified data in console .. moduleauthor::",
"json import argparse from time import sleep from datetime import datetime from textwrap",
"processes diff :param int word_size: word size for diff processing :rtype: list[Leaf] :return:",
"word_size if old == new: continue #: todo decide what's version of python",
"from __future__ import unicode_literals import os import sys import six import struct import",
"[] for table in self.watchers: for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream,",
"isinstance(old, list) and isinstance(new, list): processed_old = pack('B' * word_size, *old) processed_new =",
"\"\"\" start = int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return stream.read(size) def",
"old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx, (old, new) in",
"'follow': '<-' } ) return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start",
"for table in self.watchers: for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block)",
"would be #: more prioritized as textwrap.wrap does not work with #: bytestring",
"int(block['start'], 16) + idx * word_size if old == new: continue #: todo",
"os import sys import six import struct import json import argparse from time",
"0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old': old,",
"stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S')))",
"old processed_new = new if isinstance(old, list) and isinstance(new, list): processed_old = pack('B'",
"in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16) + idx",
"\"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap source to list of",
"watcher :platform: Linux, Windows, MacOS X :synopsis: watches for dark souls save file",
"N or equal length \"\"\" if six.PY2: return wrap(source, parts) return _wrap(source, parts)",
"os.scandir(prefix) if x.is_dir()).path else: for root, directory, files in os.walk(prefix): for filename in",
"diff check inside of block with given offsets'), required=True) arguments = parser.parse_args(sys.argv[1:]) main(arguments)",
"get_default_file_name(): \"\"\" running on windows it would get default draks0005.sl2 file location :rtype:",
".. module:: watcher :platform: Linux, Windows, MacOS X :synopsis: watches for dark souls",
"word_size start = int(block['start'], 16) + idx * word_size if old == new:",
"0 old_stat = os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat = os.lstat(self.filename)",
"old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\"",
"3+ only :param str source: source to wrap :param int parts: N equal",
"spy :param str filename: path inspected filename :keyword int slot: character slot :keyword",
"def run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream = self.read() while 1:",
"draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = ''",
"'saddr': self.start, 'value': new, 'hex': new, 'old': old, 'old_hex': old, 'follow': '<-' }",
"there's only one option convert/pack them back in #: python 3+ which could",
"try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ ==",
"processed_old = pack('B' * word_size, *old) processed_new = pack('B' * word_size, *new) nodes.append(",
"given offset :keyword int start_offset: end inspections with given offset \"\"\" def __init__(self,",
":synopsis: watches for dark souls save file modifications and prints any modified data",
"instead of standard cli :keyword int start_offset: start inspections with given offset :keyword",
") return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts):",
"def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children = [] def",
"idx * word_size start = int(block['start'], 16) + idx * word_size if old",
"windows it would get default draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file",
"save file modifications .. module:: watcher :platform: Linux, Windows, MacOS X :synopsis: watches",
"save file modifications and prints any modified data in console .. moduleauthor:: Tarvitz",
"print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser(",
"* word_size start = int(block['start'], 16) + idx * word_size if old ==",
":return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new",
"watchers = [] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename,",
"self).__init__() self.start = start self.size = size self.old = old self.new = new",
"parts python 3+ only :param str source: source to wrap :param int parts:",
"wrap source to list of equal parts :param str source: source to wrap",
"class Node(object): def __init__(self): self.children = [] def add(self, element): self.children.append(element) class Leaf(Node):",
"import os import sys import six import struct import json import argparse from",
"_wrap(source, parts): \"\"\" wrap source to list of equal parts python 3+ only",
"to read :type stream: six.BytesIO :param dict block: start offset, size to read",
"\"\"\" nothing to do as this is leaf :param element: :return: None \"\"\"",
"processed_old = old processed_new = new if isinstance(old, list) and isinstance(new, list): processed_old",
"in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import os",
"__slots__ = ['start', 'size'] def __init__(self, start, size, old, new): super(Leaf, self).__init__() self.start",
"on windows it would get default draks0005.sl2 file location :rtype: str :return: draks0005.sl2",
"True if should be refreshed \"\"\" print(out) def run(self): modified = 0 old_stat",
"start, size, old, new): super(Leaf, self).__init__() self.start = start self.size = size self.old",
"for choosing what to' ' diff check inside of block with given offsets'),",
"struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt = (",
"0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value': new,",
"processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return",
"old self.new = new def add(self, element): \"\"\" nothing to do as this",
"filename in files: if filename == default_file: path = os.path.join(prefix, root) break return",
"utf-8 -* \"\"\" DSFP modifications spy, looks for save file modifications .. module::",
"return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt =",
"in dict :keyword bool use_curses: use curses interface instead of standard cli :keyword",
"the main window :keyword bool refresh: True if should be refreshed \"\"\" print(out)",
"six.BytesIO :param dict block: start offset, size to read :rtype: str :return: raw",
"equal parts python 3+ only :param str source: source to wrap :param int",
"= os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2' if sys.version_info[:2]",
"six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the main window :keyword bool refresh:",
"start = int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self,",
"parts): \"\"\" wrap source to list of equal parts :param str source: source",
"list) and isinstance(new, list): processed_old = pack('B' * word_size, *old) processed_new = pack('B'",
"is represented in table stored in dict :keyword bool use_curses: use curses interface",
"continue now = datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat",
"in #: python 3+ which could give performance drop downs. processed_old = old",
"table in self.watchers: for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data",
"'size'] def __init__(self, start, size, old, new): super(Leaf, self).__init__() self.start = start self.size",
"= pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes",
"could give performance drop downs. processed_old = old processed_new = new if isinstance(old,",
":keyword dict skip_table: skip some data which is represented in table stored in",
"stored in dict :keyword bool use_curses: use curses interface instead of standard cli",
"from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self):",
"stream to read :type stream: six.BytesIO :param dict block: start offset, size to",
"bool refresh: True if should be refreshed \"\"\" print(out) def run(self): modified =",
"parts): \"\"\" wrap source to list of equal parts python 3+ only :param",
"== '__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls save file.' ) parser.add_argument('-f',",
"size for diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes = [] for",
"watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers = watchers def read_stream(self, stream,",
"from datetime import datetime from textwrap import wrap from struct import pack, unpack",
"changes for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file',",
"modified += 1 def get_default_file_name(): \"\"\" running on windows it would get default",
"textwrap.wrap does not work with #: bytestring and iterate through it coverts chars",
"self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old': old, 'old_hex': old, 'follow': '<-'",
"__init__(self, filename, watchers=None): self.filename = filename self.watchers = watchers def read(self): fo =",
"which is represented in table stored in dict :keyword bool use_curses: use curses",
"} ) return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source,",
"read_stream(self, stream, block): \"\"\" read stream withing given block :param stream: stream to",
"word size for diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes = []",
"= new_stream self.old_stream = old_stream self.watchers = watchers def read_stream(self, stream, block): \"\"\"",
"= old_stream self.watchers = watchers def read_stream(self, stream, block): \"\"\" read stream withing",
"diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes = [] for table in",
"= [] def add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def",
"return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream",
"def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers =",
"in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C,",
"__init__(self): self.children = [] def add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start',",
"new def add(self, element): \"\"\" nothing to do as this is leaf :param",
"= ns.filename or get_default_file_name() watchers = [] if ns.watch_table: for stream in ns.watch_table:",
"next(x for x in os.scandir(prefix) if x.is_dir()).path else: for root, directory, files in",
"read :type stream: six.BytesIO :param dict block: start offset, size to read :rtype:",
"finally: sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls",
"dark souls save file modifications and prints any modified data in console ..",
"= '' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path = next(x",
"given block :param stream: stream to read :type stream: six.BytesIO :param dict block:",
"stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff():",
"stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch",
"to do as this is leaf :param element: :return: None \"\"\" @staticmethod def",
"or equal length \"\"\" if six.PY2: return wrap(source, parts) return _wrap(source, parts) class",
"# -*- coding: utf-8 -* \"\"\" DSFP modifications spy, looks for save file",
"chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children = []",
"does not work with #: bytestring and iterate through it coverts chars back",
"parts :param str source: source to wrap :param int parts: N equal parts",
"back to #: int there's only one option convert/pack them back in #:",
"16) + idx * word_size start = int(block['start'], 16) + idx * word_size",
"filename, watchers=None): self.filename = filename self.watchers = watchers def read(self): fo = open(self.filename,",
"sys.version_info[:2] >= (3, 5): path = next(x for x in os.scandir(prefix) if x.is_dir()).path",
"source to list of equal parts :param str source: source to wrap :param",
"withing given block :param stream: stream to read :type stream: six.BytesIO :param dict",
"interface instead of standard cli :keyword int start_offset: start inspections with given offset",
"exiting ..\") finally: sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes",
":keyword int start_offset: start inspections with given offset :keyword int start_offset: end inspections",
"skip_table: skip some data which is represented in table stored in dict :keyword",
"chars back to #: int there's only one option convert/pack them back in",
"16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param int word_size:",
"= int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param",
"give performance drop downs. processed_old = old processed_new = new if isinstance(old, list)",
"__init__(self, start, size, old, new): super(Leaf, self).__init__() self.start = start self.size = size",
"with N or equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\"",
"= next(x for x in os.scandir(prefix) if x.is_dir()).path else: for root, directory, files",
"block: start offset, size to read :rtype: str :return: raw data \"\"\" start",
"= Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0)",
"get_default_file_name() watchers = [] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher =",
":keyword bool refresh: True if should be refreshed \"\"\" print(out) def run(self): modified",
"16) + idx * word_size if old == new: continue #: todo decide",
"DSFP modifications spy, looks for save file modifications .. module:: watcher :platform: Linux,",
"os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns): filename = ns.filename or get_default_file_name()",
"to list of equal parts :param str source: source to wrap :param int",
"or get_default_file_name() watchers = [] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher",
"3+ which could give performance drop downs. processed_old = old processed_new = new",
"sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified:",
"= self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s",
"stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s",
"def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log",
"description='Prints changes for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save",
"python 3+ only :param str source: source to wrap :param int parts: N",
"\"\"\" Changes spy :param str filename: path inspected filename :keyword int slot: character",
"represented in table stored in dict :keyword bool use_curses: use curses interface instead",
"\"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new,",
"struct import json import argparse from time import sleep from datetime import datetime",
"start offset, size to read :rtype: str :return: raw data \"\"\" start =",
"processing :rtype: list[Leaf] :return: diffs \"\"\" nodes = [] for table in self.watchers:",
"= old self.new = new def add(self, element): \"\"\" nothing to do as",
"equal parts :rtype: list[str] :return: list of str with N or equal length",
"#: int there's only one option convert/pack them back in #: python 3+",
"self.filename = filename self.watchers = watchers def read(self): fo = open(self.filename, 'rb') return",
"for dark souls save file modifications and prints any modified data in console",
"self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ):",
"fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr':",
"only one option convert/pack them back in #: python 3+ which could give",
"unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old)",
"filename: path inspected filename :keyword int slot: character slot :keyword dict skip_table: skip",
"old_stat = os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat = os.lstat(self.filename) if",
"is leaf :param element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt,",
"refresh: True if should be refreshed \"\"\" print(out) def run(self): modified = 0",
"= new def add(self, element): \"\"\" nothing to do as this is leaf",
"= ['start', 'size'] def __init__(self, start, size, old, new): super(Leaf, self).__init__() self.start =",
"Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start, size, old, new): super(Leaf, self).__init__()",
"of str with N or equal length \"\"\" if six.PY2: return wrap(source, parts)",
"size, processed_old, processed_new) ) return nodes class Spy(object): \"\"\" Changes spy :param str",
"start inspections with given offset :keyword int start_offset: end inspections with given offset",
"import datetime from textwrap import wrap from struct import pack, unpack PROJECT_ROOT =",
"now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for",
"__repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap source to",
"self.new = new def add(self, element): \"\"\" nothing to do as this is",
"watchers def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\"",
"[] def add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self,",
"list of equal parts :param str source: source to wrap :param int parts:",
"what's version of python would be #: more prioritized as textwrap.wrap does not",
"sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class",
"add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start, size,",
"of str with N or equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source,",
"window :keyword bool refresh: True if should be refreshed \"\"\" print(out) def run(self):",
":keyword bool use_curses: use curses interface instead of standard cli :keyword int start_offset:",
"argparse.ArgumentParser( description='Prints changes for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename',",
"slot :keyword dict skip_table: skip some data which is represented in table stored",
"list[str] :return: list of str with N or equal length \"\"\" return list(chunks(source,",
"work with #: bytestring and iterate through it coverts chars back to #:",
"__future__ import unicode_literals import os import sys import six import struct import json",
"break return os.path.join(path, default_file) def main(ns): filename = ns.filename or get_default_file_name() watchers =",
"list[str] :return: list of str with N or equal length \"\"\" if six.PY2:",
"of python would be #: more prioritized as textwrap.wrap does not work with",
"@staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old",
"for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt:",
"= self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified",
"return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap source to list",
"= self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size))",
"to list of equal parts python 3+ only :param str source: source to",
"\" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr': self.start, 'value': new, 'hex':",
"import six import struct import json import argparse from time import sleep from",
"file location :rtype: str :return: draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'),",
"standard cli :keyword int start_offset: start inspections with given offset :keyword int start_offset:",
"5): path = next(x for x in os.scandir(prefix) if x.is_dir()).path else: for root,",
"self.old = old self.new = new def add(self, element): \"\"\" nothing to do",
"it coverts chars back to #: int there's only one option convert/pack them",
"1 def get_default_file_name(): \"\"\" running on windows it would get default draks0005.sl2 file",
"#: more prioritized as textwrap.wrap does not work with #: bytestring and iterate",
"self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % {",
":param int word_size: word size for diff processing :rtype: list[Leaf] :return: diffs \"\"\"",
"textwrap import wrap from struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT,",
"word_size: word size for diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes =",
"leaf :param element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0]",
"old_stream = self.read() while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime:",
"dict :keyword bool use_curses: use curses interface instead of standard cli :keyword int",
"if old == new: continue #: todo decide what's version of python would",
"\"\"\" def __init__(self, filename, watchers=None): self.filename = filename self.watchers = watchers def read(self):",
"0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap source to list of equal",
"curses interface instead of standard cli :keyword int start_offset: start inspections with given",
"one option convert/pack them back in #: python 3+ which could give performance",
"log(out): \"\"\" log into the main window :keyword bool refresh: True if should",
"from struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils",
"size, old, new): super(Leaf, self).__init__() self.start = start self.size = size self.old =",
"( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start, 'saddr':",
"metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=(",
"+ idx * word_size start = int(block['start'], 16) + idx * word_size if",
"word_size=4): \"\"\" processes diff :param int word_size: word size for diff processing :rtype:",
"path) class Node(object): def __init__(self): self.children = [] def add(self, element): self.children.append(element) class",
"super(Leaf, self).__init__() self.start = start self.size = size self.old = old self.new =",
"of equal parts :param str source: source to wrap :param int parts: N",
"size self.old = old self.new = new def add(self, element): \"\"\" nothing to",
"to #: int there's only one option convert/pack them back in #: python",
"should be refreshed \"\"\" print(out) def run(self): modified = 0 old_stat = os.lstat(self.filename)",
"self.start, 'value': new, 'hex': new, 'old': old, 'old_hex': old, 'follow': '<-' } )",
"if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run()",
"#: bytestring and iterate through it coverts chars back to #: int there's",
"choosing what to' ' diff check inside of block with given offsets'), required=True)",
":rtype: str :return: draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' )",
"= self.read() while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue",
"in table stored in dict :keyword bool use_curses: use curses interface instead of",
"inspections with given offset :keyword int start_offset: end inspections with given offset \"\"\"",
"refreshed \"\"\" print(out) def run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream =",
"'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the main window :keyword",
"skip some data which is represented in table stored in dict :keyword bool",
"new): super(Leaf, self).__init__() self.start = start self.size = size self.old = old self.new",
":return: raw data \"\"\" start = int(block['start'], 16) size = int(block['size'], 16) stream.seek(start)",
"start_offset: start inspections with given offset :keyword int start_offset: end inspections with given",
"str with N or equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts):",
"equal length \"\"\" if six.PY2: return wrap(source, parts) return _wrap(source, parts) class NewDiff(object):",
"int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff :param int",
"N equal parts :rtype: list[str] :return: list of str with N or equal",
"root) break return os.path.join(path, default_file) def main(ns): filename = ns.filename or get_default_file_name() watchers",
"= filename self.watchers = watchers def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read())",
"'old': old, 'old_hex': old, 'follow': '<-' } ) return fmt def __repr__(self): return",
"enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16) + idx *",
"dict block: start offset, size to read :rtype: str :return: raw data \"\"\"",
"(old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16)",
"get default draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file location \"\"\" prefix",
"slot: character slot :keyword dict skip_table: skip some data which is represented in",
"'hex': new, 'old': old, 'old_hex': old, 'follow': '<-' } ) return fmt def",
"wrap :param int parts: N equal parts :rtype: list[str] :return: list of str",
"any modified data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import",
"of json file for choosing what to' ' diff check inside of block",
"option convert/pack them back in #: python 3+ which could give performance drop",
"with N or equal length \"\"\" if six.PY2: return wrap(source, parts) return _wrap(source,",
"datetime import datetime from textwrap import wrap from struct import pack, unpack PROJECT_ROOT",
"% { 'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old': old, 'old_hex':",
"continue #: todo decide what's version of python would be #: more prioritized",
"inspected filename :keyword int slot: character slot :keyword dict skip_table: skip some data",
"block): \"\"\" read stream withing given block :param stream: stream to read :type",
"str filename: path inspected filename :keyword int slot: character slot :keyword dict skip_table:",
"[%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff = NewDiff(old_stream=old_stream,",
"Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import os import sys import six",
"list of str with N or equal length \"\"\" return list(chunks(source, parts)) def",
"old_stream self.watchers = watchers def read_stream(self, stream, block): \"\"\" read stream withing given",
"and iterate through it coverts chars back to #: int there's only one",
"old == new: continue #: todo decide what's version of python would be",
"path inspected filename :keyword int slot: character slot :keyword dict skip_table: skip some",
"= os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\"",
":rtype: str :return: raw data \"\"\" start = int(block['start'], 16) size = int(block['size'],",
"fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the",
"watchers=self.watchers) for node in diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\" running",
"for root, directory, files in os.walk(prefix): for filename in files: if filename ==",
"default_file) def main(ns): filename = ns.filename or get_default_file_name() watchers = [] if ns.watch_table:",
"for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False)",
"this is leaf :param element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return",
"= watchers def read_stream(self, stream, block): \"\"\" read stream withing given block :param",
"modifications and prints any modified data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\"",
"class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream",
"% (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream,",
"\"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2'",
"files: if filename == default_file: path = os.path.join(prefix, root) break return os.path.join(path, default_file)",
"six.PY2: return wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self,",
"new_data = self.read_stream(self.new_stream, block) for idx, (old, new) in enumerate( zip(text_wrap(old_data, word_size), text_wrap(new_data,",
":rtype: list[str] :return: list of str with N or equal length \"\"\" if",
"'<-' } ) return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def",
"performance drop downs. processed_old = old processed_new = new if isinstance(old, list) and",
"old, 'old_hex': old, 'follow': '<-' } ) return fmt def __repr__(self): return \"<Leaf:",
"self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified +=",
"prints any modified data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__",
"MacOS X :synopsis: watches for dark souls save file modifications and prints any",
"six import struct import json import argparse from time import sleep from datetime",
"* word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes class Spy(object):",
"int start_offset: end inspections with given offset \"\"\" def __init__(self, filename, watchers=None): self.filename",
"return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children = [] def add(self, element):",
"main window :keyword bool refresh: True if should be refreshed \"\"\" print(out) def",
"directory, files in os.walk(prefix): for filename in files: if filename == default_file: path",
"modifications spy, looks for save file modifications .. module:: watcher :platform: Linux, Windows,",
"N or equal length \"\"\" return list(chunks(source, parts)) def text_wrap(source, parts): \"\"\" wrap",
"import argparse from time import sleep from datetime import datetime from textwrap import",
"it would get default draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file location",
"else: for root, directory, files in os.walk(prefix): for filename in files: if filename",
"-*- coding: utf-8 -* \"\"\" DSFP modifications spy, looks for save file modifications",
"ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except",
"% self.start def _wrap(source, parts): \"\"\" wrap source to list of equal parts",
"return wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream,",
"\"\"\" running on windows it would get default draks0005.sl2 file location :rtype: str",
"watches for dark souls save file modifications and prints any modified data in",
"= os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT,",
"file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table',",
"sys import six import struct import json import argparse from time import sleep",
"[]): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx, (old, new)",
"= [] for table in self.watchers: for block in table.get('WATCH', []): old_data =",
"help=( 'use data inside of json file for choosing what to' ' diff",
"draks0005.sl2 file location :rtype: str :return: draks0005.sl2 file location \"\"\" prefix = os.path.join(",
"start_offset: end inspections with given offset \"\"\" def __init__(self, filename, watchers=None): self.filename =",
") path = '' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path",
"value)[0] def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s]",
"pack('B' * word_size, *old) processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start, size,",
"data in console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import",
"with #: bytestring and iterate through it coverts chars back to #: int",
"new = self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \"",
"def __str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s",
"print(out) def run(self): modified = 0 old_stat = os.lstat(self.filename) old_stream = self.read() while",
"parts :rtype: list[str] :return: list of str with N or equal length \"\"\"",
"more prioritized as textwrap.wrap does not work with #: bytestring and iterate through",
"filename :keyword int slot: character slot :keyword dict skip_table: skip some data which",
"word_size)) ): size = int(block['size'], 16) + idx * word_size start = int(block['start'],",
"path = '' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path =",
"stream: six.BytesIO :param dict block: start offset, size to read :rtype: str :return:",
":param element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def",
"os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2' if sys.version_info[:2] >=",
"'old_hex': old, 'follow': '<-' } ) return fmt def __repr__(self): return \"<Leaf: 0x%08x>\"",
"list of equal parts python 3+ only :param str source: source to wrap",
"unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def rel(path):",
"if six.PY2: return wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\" def",
"#: python 3+ which could give performance drop downs. processed_old = old processed_new",
"watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\")",
"class Spy(object): \"\"\" Changes spy :param str filename: path inspected filename :keyword int",
"for save file modifications .. module:: watcher :platform: Linux, Windows, MacOS X :synopsis:",
"read stream withing given block :param stream: stream to read :type stream: six.BytesIO",
"type=argparse.FileType('r'), help=( 'use data inside of json file for choosing what to' '",
"size = int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes diff",
"watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ == '__main__':",
"watchers=None): self.filename = filename self.watchers = watchers def read(self): fo = open(self.filename, 'rb')",
"path = os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns): filename = ns.filename",
"= os.lstat(self.filename) old_stream = self.read() while 1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime",
") parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json',",
"source: source to wrap :param int parts: N equal parts :rtype: list[str] :return:",
"str :return: raw data \"\"\" start = int(block['start'], 16) size = int(block['size'], 16)",
"int word_size: word size for diff processing :rtype: list[Leaf] :return: diffs \"\"\" nodes",
"version of python would be #: more prioritized as textwrap.wrap does not work",
"new if isinstance(old, list) and isinstance(new, list): processed_old = pack('B' * word_size, *old)",
"def add(self, element): \"\"\" nothing to do as this is leaf :param element:",
"..\") finally: sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes for",
"if should be refreshed \"\"\" print(out) def run(self): modified = 0 old_stat =",
"parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+',",
"class Leaf(Node): __slots__ = ['start', 'size'] def __init__(self, start, size, old, new): super(Leaf,",
"decide what's version of python would be #: more prioritized as textwrap.wrap does",
"console .. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import os import",
"def _wrap(source, parts): \"\"\" wrap source to list of equal parts python 3+",
"return os.path.join(path, default_file) def main(ns): filename = ns.filename or get_default_file_name() watchers = []",
"some data which is represented in table stored in dict :keyword bool use_curses:",
"16) size = int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\" processes",
"in self.watchers: for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data =",
"\"\"\" read stream withing given block :param stream: stream to read :type stream:",
"if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now() print(\"modified: %s [%s]\" % (modified,",
"__str__(self): new = self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x",
"open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the main window",
"os.path.join(path, default_file) def main(ns): filename = ns.filename or get_default_file_name() watchers = [] if",
"' diff check inside of block with given offsets'), required=True) arguments = parser.parse_args(sys.argv[1:])",
"watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__",
"bool use_curses: use curses interface instead of standard cli :keyword int start_offset: start",
":param str source: source to wrap :param int parts: N equal parts :rtype:",
"= start self.size = size self.old = old self.new = new def add(self,",
"self.children = [] def add(self, element): self.children.append(element) class Leaf(Node): __slots__ = ['start', 'size']",
"self.size = size self.old = old self.new = new def add(self, element): \"\"\"",
"\"\"\" nodes = [] for table in self.watchers: for block in table.get('WATCH', []):",
"*new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes class Spy(object): \"\"\" Changes",
"1: sleep(1) stat = os.lstat(self.filename) if stat.st_mtime == old_stat.st_mtime: continue now = datetime.now()",
"def process_diff(self, word_size=4): \"\"\" processes diff :param int word_size: word size for diff",
"'dsfp')) from dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def",
"import sys import six import struct import json import argparse from time import",
"int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return stream.read(size) def process_diff(self, word_size=4): \"\"\"",
"\"\"\" log into the main window :keyword bool refresh: True if should be",
"from textwrap import wrap from struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0,",
"'__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls save file.' ) parser.add_argument('-f', '--filename',",
"= new if isinstance(old, list) and isinstance(new, list): processed_old = pack('B' * word_size,",
"* word_size if old == new: continue #: todo decide what's version of",
"filename self.watchers = watchers def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod",
"old_stat = stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node",
"int there's only one option convert/pack them back in #: python 3+ which",
"str source: source to wrap :param int parts: N equal parts :rtype: list[str]",
"= 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path = next(x for x in",
"\"\"\" DSFP modifications spy, looks for save file modifications .. module:: watcher :platform:",
"self.watchers = watchers def read_stream(self, stream, block): \"\"\" read stream withing given block",
"prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2' if",
"\"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream",
"back in #: python 3+ which could give performance drop downs. processed_old =",
"default_file: path = os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns): filename =",
"Node(object): def __init__(self): self.children = [] def add(self, element): self.children.append(element) class Leaf(Node): __slots__",
"start self.size = size self.old = old self.new = new def add(self, element):",
"#: todo decide what's version of python would be #: more prioritized as",
"node in diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\" running on windows",
"diff.process_diff(): print(node) modified += 1 def get_default_file_name(): \"\"\" running on windows it would",
"if sys.version_info[:2] >= (3, 5): path = next(x for x in os.scandir(prefix) if",
"save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str, dest='filename', help='save file', required=False) parser.add_argument('-w', '--watch-table',",
"stream, block): \"\"\" read stream withing given block :param stream: stream to read",
"help='save file', required=False) parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside",
"\"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new)",
"'' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path = next(x for",
"source to wrap :param int parts: N equal parts :rtype: list[str] :return: list",
"self.watchers = watchers def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def",
"which could give performance drop downs. processed_old = old processed_new = new if",
"python 3+ which could give performance drop downs. processed_old = old processed_new =",
":param str filename: path inspected filename :keyword int slot: character slot :keyword dict",
"for block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block)",
"print(node) modified += 1 def get_default_file_name(): \"\"\" running on windows it would get",
"diffs \"\"\" nodes = [] for table in self.watchers: for block in table.get('WATCH',",
"running on windows it would get default draks0005.sl2 file location :rtype: str :return:",
":return: list of str with N or equal length \"\"\" return list(chunks(source, parts))",
":return: draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path =",
":param int parts: N equal parts :rtype: list[str] :return: list of str with",
"file modifications .. module:: watcher :platform: Linux, Windows, MacOS X :synopsis: watches for",
"watchers def read_stream(self, stream, block): \"\"\" read stream withing given block :param stream:",
"= [] if ns.watch_table: for stream in ns.watch_table: watchers.append(json.loads(stream.read())) watcher = Spy(filename=filename, watchers=watchers)",
".. moduleauthor:: Tarvitz <<EMAIL>> \"\"\" from __future__ import unicode_literals import os import sys",
"{ 'addr': self.start, 'saddr': self.start, 'value': new, 'hex': new, 'old': old, 'old_hex': old,",
":keyword int start_offset: end inspections with given offset \"\"\" def __init__(self, filename, watchers=None):",
"into the main window :keyword bool refresh: True if should be refreshed \"\"\"",
"Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Prints",
"if filename == default_file: path = os.path.join(prefix, root) break return os.path.join(path, default_file) def",
"list[Leaf] :return: diffs \"\"\" nodes = [] for table in self.watchers: for block",
"import json import argparse from time import sleep from datetime import datetime from",
"diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers) for node in diff.process_diff(): print(node) modified += 1",
"dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json file for choosing",
"parser.add_argument('-w', '--watch-table', dest='watch_table', metavar='table.json,table2.json', nargs='+', type=argparse.FileType('r'), help=( 'use data inside of json file",
"coverts chars back to #: int there's only one option convert/pack them back",
"X :synopsis: watches for dark souls save file modifications and prints any modified",
"time import sleep from datetime import datetime from textwrap import wrap from struct",
"old, new): super(Leaf, self).__init__() self.start = start self.size = size self.old = old",
"int(block['size'], 16) + idx * word_size start = int(block['start'], 16) + idx *",
"data which is represented in table stored in dict :keyword bool use_curses: use",
"self.unpack(self.new) old = self.unpack(self.old) fmt = ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s",
"*old) processed_new = pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) )",
"filename = ns.filename or get_default_file_name() watchers = [] if ns.watch_table: for stream in",
"import wrap from struct import pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp'))",
"\"\"\" processes diff :param int word_size: word size for diff processing :rtype: list[Leaf]",
"of standard cli :keyword int start_offset: start inspections with given offset :keyword int",
"int parts: N equal parts :rtype: list[str] :return: list of str with N",
"= ( \"0x%(addr)08x[%(saddr)10s] %(value)10s 0x%(hex)08x \" \"%(follow)5s %(old)10s 0x%(old_hex)08x\" % { 'addr': self.start,",
"os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children = [] def add(self, element): self.children.append(element)",
"source to list of equal parts python 3+ only :param str source: source",
"block in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for",
"== default_file: path = os.path.join(prefix, root) break return os.path.join(path, default_file) def main(ns): filename",
"def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap source",
"read :rtype: str :return: raw data \"\"\" start = int(block['start'], 16) size =",
"NewDiff(object): \"\"\" \"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream =",
"zip(text_wrap(old_data, word_size), text_wrap(new_data, word_size)) ): size = int(block['size'], 16) + idx * word_size",
"through it coverts chars back to #: int there's only one option convert/pack",
"Spy(filename=filename, watchers=watchers) try: watcher.run() except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if",
"import struct import json import argparse from time import sleep from datetime import",
"table stored in dict :keyword bool use_curses: use curses interface instead of standard",
"file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file",
"coding: utf-8 -* \"\"\" DSFP modifications spy, looks for save file modifications ..",
"new: continue #: todo decide what's version of python would be #: more",
"\"\"\" wrap source to list of equal parts python 3+ only :param str",
"= argparse.ArgumentParser( description='Prints changes for darksouls save file.' ) parser.add_argument('-f', '--filename', metavar='draks0005.sl2', type=str,",
"todo decide what's version of python would be #: more prioritized as textwrap.wrap",
"\"\"\" def __init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers",
"+= 1 def get_default_file_name(): \"\"\" running on windows it would get default draks0005.sl2",
"\"\"\" from __future__ import unicode_literals import os import sys import six import struct",
"to' ' diff check inside of block with given offsets'), required=True) arguments =",
"rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children = [] def add(self,",
"location :rtype: str :return: draks0005.sl2 file location \"\"\" prefix = os.path.join( os.getenv('HOME'), 'Documents/NBGI/DarkSouls/'",
"processed_new) ) return nodes class Spy(object): \"\"\" Changes spy :param str filename: path",
"import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children =",
"now = datetime.now() print(\"modified: %s [%s]\" % (modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream",
"new, 'old': old, 'old_hex': old, 'follow': '<-' } ) return fmt def __repr__(self):",
"in table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx,",
"datetime from textwrap import wrap from struct import pack, unpack PROJECT_ROOT = os.path.pardir",
"start = int(block['start'], 16) + idx * word_size if old == new: continue",
"default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path = next(x for x",
"text_wrap(source, parts): \"\"\" wrap source to list of equal parts :param str source:",
"parts: N equal parts :rtype: list[str] :return: list of str with N or",
"int start_offset: start inspections with given offset :keyword int start_offset: end inspections with",
"pack, unpack PROJECT_ROOT = os.path.pardir sys.path.insert(0, os.path.join(PROJECT_ROOT, 'dsfp')) from dsfp.utils import chunks def",
"file modifications and prints any modified data in console .. moduleauthor:: Tarvitz <<EMAIL>>",
"(modified, now.strftime('%H:%M:%S'))) old_stat = stat new_stream = self.read() diff = NewDiff(old_stream=old_stream, new_stream=new_stream, watchers=self.watchers)",
"given offset \"\"\" def __init__(self, filename, watchers=None): self.filename = filename self.watchers = watchers",
"downs. processed_old = old processed_new = new if isinstance(old, list) and isinstance(new, list):",
"as this is leaf :param element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'):",
"length \"\"\" if six.PY2: return wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\"",
"= old processed_new = new if isinstance(old, list) and isinstance(new, list): processed_old =",
"def __init__(self, filename, watchers=None): self.filename = filename self.watchers = watchers def read(self): fo",
"__name__ == '__main__': parser = argparse.ArgumentParser( description='Prints changes for darksouls save file.' )",
"int slot: character slot :keyword dict skip_table: skip some data which is represented",
"end inspections with given offset \"\"\" def __init__(self, filename, watchers=None): self.filename = filename",
"+ idx * word_size if old == new: continue #: todo decide what's",
"table.get('WATCH', []): old_data = self.read_stream(self.old_stream, block) new_data = self.read_stream(self.new_stream, block) for idx, (old,",
"'draks0005.sl2' if sys.version_info[:2] >= (3, 5): path = next(x for x in os.scandir(prefix)",
"= int(block['start'], 16) + idx * word_size if old == new: continue #:",
"iterate through it coverts chars back to #: int there's only one option",
"def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self): new = self.unpack(self.new) old =",
"of equal parts python 3+ only :param str source: source to wrap :param",
"with given offset :keyword int start_offset: end inspections with given offset \"\"\" def",
"os.getenv('HOME'), 'Documents/NBGI/DarkSouls/' ) path = '' default_file = 'draks0005.sl2' if sys.version_info[:2] >= (3,",
"def read_stream(self, stream, block): \"\"\" read stream withing given block :param stream: stream",
"be #: more prioritized as textwrap.wrap does not work with #: bytestring and",
"fmt def __repr__(self): return \"<Leaf: 0x%08x>\" % self.start def _wrap(source, parts): \"\"\" wrap",
"Spy(object): \"\"\" Changes spy :param str filename: path inspected filename :keyword int slot:",
"parts)) def text_wrap(source, parts): \"\"\" wrap source to list of equal parts :param",
"isinstance(new, list): processed_old = pack('B' * word_size, *old) processed_new = pack('B' * word_size,",
"pack('B' * word_size, *new) nodes.append( Leaf(start, size, processed_old, processed_new) ) return nodes class",
"nodes class Spy(object): \"\"\" Changes spy :param str filename: path inspected filename :keyword",
"element: :return: None \"\"\" @staticmethod def unpack(value, fmt='I'): return struct.unpack(fmt, value)[0] def __str__(self):",
"diff :param int word_size: word size for diff processing :rtype: list[Leaf] :return: diffs",
"= open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out): \"\"\" log into the main",
"\"\"\" if six.PY2: return wrap(source, parts) return _wrap(source, parts) class NewDiff(object): \"\"\" \"\"\"",
"data \"\"\" start = int(block['start'], 16) size = int(block['size'], 16) stream.seek(start) return stream.read(size)",
"except KeyboardInterrupt: print(\"\\nCatch Ctrl+C, exiting ..\") finally: sys.exit(0) if __name__ == '__main__': parser",
"def get_default_file_name(): \"\"\" running on windows it would get default draks0005.sl2 file location",
"__init__(self, new_stream, old_stream, watchers): self.new_stream = new_stream self.old_stream = old_stream self.watchers = watchers",
"dsfp.utils import chunks def rel(path): return os.path.join(PROJECT_ROOT, path) class Node(object): def __init__(self): self.children",
"use curses interface instead of standard cli :keyword int start_offset: start inspections with",
"old, 'follow': '<-' } ) return fmt def __repr__(self): return \"<Leaf: 0x%08x>\" %",
"processed_old, processed_new) ) return nodes class Spy(object): \"\"\" Changes spy :param str filename:",
"def main(ns): filename = ns.filename or get_default_file_name() watchers = [] if ns.watch_table: for",
"main(ns): filename = ns.filename or get_default_file_name() watchers = [] if ns.watch_table: for stream",
"str with N or equal length \"\"\" if six.PY2: return wrap(source, parts) return",
"nodes = [] for table in self.watchers: for block in table.get('WATCH', []): old_data",
"= watchers def read(self): fo = open(self.filename, 'rb') return six.BytesIO(fo.read()) @staticmethod def log(out):",
"return nodes class Spy(object): \"\"\" Changes spy :param str filename: path inspected filename"
] |
[
"< 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno)",
"= 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado'",
"else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo",
"{} aluno['nome'] = str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual a sua",
"print('-=' * 30) print(aluno) for k, v in aluno.items(): print(f'{k} é igual a",
"'''aluno = {} aluno['nome'] = str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual",
"= dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if",
"aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for k,",
"de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <=",
"= 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')'''",
"= 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for k, v",
"aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a",
"dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media']",
"aluno['nome'] = str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual a sua media:",
"'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno =",
"print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict()",
"= 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação']",
"{aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] =",
"5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-='",
"'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] =",
"aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara')",
"7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação'",
"é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media']",
"<= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' *",
"aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for k, v in aluno.items(): print(f'{k}",
"'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido",
">= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else:",
">= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno",
"= float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif",
"if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7:",
"pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de",
"aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado'",
"igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado'",
"')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] =",
"situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome']",
"{aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação']",
"print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media",
"float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5",
"= {} aluno['nome'] = str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual a",
"')) aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual",
"nome: ')) aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia",
"{aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome: '))",
"'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A",
"aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else:",
"')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação']",
"'Reprovado' print('-=' * 30) print(aluno) for k, v in aluno.items(): print(f'{k} é igual",
"<gh_stars>0 '''aluno = {} aluno['nome'] = str(input('Qual o Seu nome: ')) aluno['media'] =",
"elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação",
"o Seu nome: ')) aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome igual",
"aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação'",
"str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação']",
"= 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno",
"Seu nome: ')) aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome igual a",
"sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >=",
"a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif",
"aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] =",
"7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for",
"media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7:",
"')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] <",
"if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] =",
"7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação']",
"do aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] =",
"= str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual a sua media: '))",
"float(input('Qual a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if",
"igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >=",
"{aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media']",
"= str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >= 7:",
"str(input('Qual o Seu nome: ')) aluno['media'] = float(input('Qual a sua media: ')) print(f'Nome",
"a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media']",
"aluno {aluno[\"nome\"]} é {aluno[\"situação\"]}')''' print('Resolvido pelo guanabara') aluno = dict() aluno['nome'] = str(input('Nome:",
">= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação'] =",
"= float(input('Qual a sua media: ')) print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}')",
"aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]} é",
"print(f'Nome igual a {aluno[\"nome\"]}\\nMedia igual a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] =",
"guanabara') aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}:",
"else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for k, v in aluno.items():",
"* 30) print(aluno) for k, v in aluno.items(): print(f'{k} é igual a {v}')",
"aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30)",
"a {aluno[\"media\"]:.2f}') if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >= 5:",
"'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 30) print(aluno) for k, v in",
"aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: ')) if aluno['media'] >=",
"aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media'] < 7: aluno['situação']",
"5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do aluno {aluno[\"nome\"]}",
"aluno['media'] >= 5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print(f'A situação do",
"= 'Reprovado' print('-=' * 30) print(aluno) for k, v in aluno.items(): print(f'{k} é",
"aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Media de {aluno[\"nome\"]}: '))",
"elif 5 <= aluno['media'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado'",
"{aluno[\"nome\"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif 5 <= aluno['media']"
] |
[
"float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated file with",
"7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for line in",
"len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) #",
"filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ',",
"pass if __name__ == '__main__': import sys if len(sys.argv) != 4: print 'usage:",
"/path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module file path to path sys.path.insert(0,",
"fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated file with the",
"#! /usr/bin/env python def main(filename_raw_in, filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51,",
"False) with open(filename_raw_in) as f: for line in f: try: raw = float(line.strip())",
"# Compare the generated file with the golden filtered file import filecmp if",
"os.remove(fdout.name) except OSError: pass if __name__ == '__main__': import sys if len(sys.argv) !=",
"sys if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0]",
"the file on success try: import os os.remove(fdout.name) except OSError: pass if __name__",
"open(filename_raw_in) as f: for line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' %",
"except OSError: pass if __name__ == '__main__': import sys if len(sys.argv) != 4:",
"for line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass",
"equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the file on success try: import",
"golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal:",
"fdout.flush() # Compare the generated file with the golden filtered file import filecmp",
"= fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f:",
"as f: for line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw))",
"fir import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False)",
"main(filename_raw_in, filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout =",
"fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the file",
"filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as",
"/usr/bin/env python def main(filename_raw_in, filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51, 1000,",
"= tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for line in f: try:",
"', filename_filtered_out, fdout.name exit(-1) # Delete the file on success try: import os",
"4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the",
"except: pass fdout.flush() # Compare the generated file with the golden filtered file",
"# Delete the file on success try: import os os.remove(fdout.name) except OSError: pass",
"/path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module file path to",
"success try: import os os.remove(fdout.name) except OSError: pass if __name__ == '__main__': import",
"with open(filename_raw_in) as f: for line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n'",
"def main(filename_raw_in, filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout",
"filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1)",
"pass fdout.flush() # Compare the generated file with the golden filtered file import",
"fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for line in f:",
"import os os.remove(fdout.name) except OSError: pass if __name__ == '__main__': import sys if",
"in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() #",
"print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the file on",
"Delete the file on success try: import os os.remove(fdout.name) except OSError: pass if",
"fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for",
"try: import os os.remove(fdout.name) except OSError: pass if __name__ == '__main__': import sys",
"'__main__': import sys if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden'",
"/path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module file path to path",
"'Files not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the file on success",
"import fir import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete =",
"generated file with the golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name):",
"sys.argv[0] exit(-1) # Add the module file path to path sys.path.insert(0, sys.argv[1]) main(sys.argv[2],",
"tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for line in f: try: raw",
"filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete",
"if __name__ == '__main__': import sys if len(sys.argv) != 4: print 'usage: %s",
"not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the file on success try:",
"import sys if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' %",
"__name__ == '__main__': import sys if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module",
"'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module file",
"filename_filtered_out, fdout.name exit(-1) # Delete the file on success try: import os os.remove(fdout.name)",
"Compare the generated file with the golden filtered file import filecmp if not",
"filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete the",
"% filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated file with the golden",
"file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out,",
"1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in) as f: for line",
"filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated file with the golden filtered",
"print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module",
"import tempfile filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with",
"= False) with open(filename_raw_in) as f: for line in f: try: raw =",
"exit(-1) # Delete the file on success try: import os os.remove(fdout.name) except OSError:",
"!= 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add",
"import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name",
"= float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated file",
"raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare the generated",
"if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1)",
"with the golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files",
"fdout.name exit(-1) # Delete the file on success try: import os os.remove(fdout.name) except",
"f: for line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except:",
"try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare the",
"%s /path/to/fir_module /path/to/filter_in_file /path/to/filter_out_golden' % sys.argv[0] exit(-1) # Add the module file path",
"os os.remove(fdout.name) except OSError: pass if __name__ == '__main__': import sys if len(sys.argv)",
"if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1) #",
"not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not equal: ', filename_filtered_out, fdout.name exit(-1) # Delete",
"f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush() # Compare",
"exit(-1) # Add the module file path to path sys.path.insert(0, sys.argv[1]) main(sys.argv[2], sys.argv[3])",
"tempfile filt = fir.Filter_LP(51, 1000, 7) fdout = tempfile.NamedTemporaryFile(delete = False) with open(filename_raw_in)",
"== '__main__': import sys if len(sys.argv) != 4: print 'usage: %s /path/to/fir_module /path/to/filter_in_file",
"% sys.argv[0] exit(-1) # Add the module file path to path sys.path.insert(0, sys.argv[1])",
"the generated file with the golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out,",
"line in f: try: raw = float(line.strip()) fdout.write('%0.08f\\n' % filt.do_sample(raw)) except: pass fdout.flush()",
"the golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print 'Files not",
"OSError: pass if __name__ == '__main__': import sys if len(sys.argv) != 4: print",
"file with the golden filtered file import filecmp if not filecmp.cmp(filename_filtered_out, fdout.name): print",
"python def main(filename_raw_in, filename_filtered_out): import fir import tempfile filt = fir.Filter_LP(51, 1000, 7)",
"file on success try: import os os.remove(fdout.name) except OSError: pass if __name__ ==",
"on success try: import os os.remove(fdout.name) except OSError: pass if __name__ == '__main__':"
] |
[
"Approved :: Apache Software License\"), \"Programming Language :: Python\", \"Programming Language :: Python",
"# for Swig extension from builtins import open, dict PROJECT = 'intro_py.foreignc' HERE",
"= [os.path.join(root, file1) for path in paths for root, dirs, files in os.walk(path)",
"#os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension",
"# setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc))",
"-types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd in",
"raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ #",
"\"Programming Language :: Python :: 3\", \"Programming Language :: Python :: Implementation ::",
"\"MIT\": \"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved",
"can not be used with Jython.') ## for jna #if 'java' not in",
"assert os.getcwd() == self.cwd, 'Must be in pkg root: {0}'.format( self.cwd) ## use",
"'-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')],",
"if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools",
"json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else",
"'-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig",
"description #description = 'run nose2 [DEBUG=1] (* addon *)' description = 'run unittest",
"sys, pkgutil, json, glob from distutils.command.clean import clean as CleanCommand from setuptools import",
"cmd in blacklist for arg in sys.argv if cmd in arg] if []",
"os.getcwd() def run(self): import subprocess assert os.getcwd() == self.cwd, 'Must be in pkg",
"'), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon = {}",
"-m coverage run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError",
"for cffi, swig #if 'java' in sys.platform.lower(): # raise Exception('This package can not",
"clean as CleanCommand from setuptools import setup, find_packages, Command #from setuptools import Extension",
"OSI Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU General",
"filepats for file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist): import",
"def disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist for arg in sys.argv",
"open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi,",
"for path in paths for root, dirs, files in os.walk(path) for filepat in",
"sys.platform.lower(): # raise Exception('This package can only be used with Jython.') ## jip",
"Language :: English\", \"Development Status :: 3 - Alpha\", \"Intended Audience :: Developers\",",
"discover [DEBUG=1] (* addon *)' user_options = [('opts=', 'o', 'Test options (default: -s",
"_matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1) for path in paths for",
"f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo",
"addon *)' description = 'run unittest discover [DEBUG=1] (* addon *)' user_options =",
"sys.argv if cmd in arg] if [] != bad_cmds: print('Command(s) {0} have been",
"nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell = True)",
"# PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ##",
"PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if",
"dirs, files in os.walk(path) for filepat in filepats for file1 in fnmatch.filter(dirs +",
"= None, '' def finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess assert",
"#packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])],",
"USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( #",
"os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def run(self): import shutil",
"- Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache",
":: OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" }",
"swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable",
":: OSI Approved :: Apache Software License\"), \"Programming Language :: Python\", \"Programming Language",
"# py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'':",
"Language :: Python :: 3\", \"Programming Language :: Python :: Implementation :: Jython\",",
"#test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod],",
"'java' not in sys.platform.lower(): # raise Exception('This package can only be used with",
"with Jython.') ## for jna #if 'java' not in sys.platform.lower(): # raise Exception('This",
"'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1) for path in",
"-m nose2 {1}'.format( # sys.executable, self.opts), shell = True) errno = subprocess.call('{0} -m",
"sys.executable, self.opts), shell = True) errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable,",
"for jna #if 'java' not in sys.platform.lower(): # raise Exception('This package can only",
"'-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if '1' ==",
"have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch",
"unittest discover [DEBUG=1] (* addon *)' user_options = [('opts=', 'o', 'Test options (default:",
"os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] =",
"from __future__ import absolute_import, print_function import os, sys, pkgutil, json, glob from distutils.command.clean",
":: Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(),",
"cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read()",
"as exc: print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst') as",
"options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, '' def",
"#sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist for arg in",
"path in paths for root, dirs, files in os.walk(path) for filepat in filepats",
"#data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT),",
":: 3\", \"Programming Language :: Python :: Implementation :: Jython\", \"Topic :: Software",
"#cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items()",
"licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved :: Apache Software License\", \"MIT\":",
"not be used with Jython.') ## for jna #if 'java' not in sys.platform.lower():",
"\"License :: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved ::",
":: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\", \"ISC\":",
"glob from distutils.command.clean import clean as CleanCommand from setuptools import setup, find_packages, Command",
"files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for path in pathlist: if",
"\"License :: Public Domain\" } setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural",
"1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so',",
"Approved :: ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme",
"#description = 'run nose2 [DEBUG=1] (* addon *)' description = 'run unittest discover",
"# os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), #",
"#package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('',",
"unittest discover {1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno) ## for ffi_lib",
"def _remove_pathlist(pathlist): import shutil for path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path)",
"with open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst') as f_in: history =",
"\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming",
"absolute_import, print_function import os, sys, pkgutil, json, glob from distutils.command.clean import clean as",
"Python :: 3\", \"Programming Language :: Python :: Implementation :: Jython\", \"Topic ::",
"f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None",
"matches_pats def _remove_pathlist(pathlist): import shutil for path in pathlist: if os.path.exists(path) and os.path.isdir(path):",
":: Apache Software License\", \"MIT\": \"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\":",
"(GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License ::",
"import subprocess assert os.getcwd() == self.cwd, 'Must be in pkg root: {0}'.format( self.cwd)",
"== self.cwd, 'Must be in pkg root: {0}'.format( self.cwd) ## use nose2 #errno",
"extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon",
":: English\", \"Development Status :: 3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0',",
"':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)])",
"## for jna #if 'java' not in sys.platform.lower(): # raise Exception('This package can",
"{} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved :: Apache Software License\",",
"\"Natural Language :: English\", \"Development Status :: 3 - Alpha\", \"Intended Audience ::",
"License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme + '\\n\\n' +",
"py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.',",
"cffi, swig #if 'java' in sys.platform.lower(): # raise Exception('This package can not be",
"arg in sys.argv if cmd in arg] if [] != bad_cmds: print('Command(s) {0}",
"'*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd description #description = 'run nose2",
"Apache Software License\"), \"Programming Language :: Python\", \"Programming Language :: Python :: 2.7\",",
"finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess assert os.getcwd() == self.cwd, 'Must",
"# raise Exception('This package can not be used with Jython.') ## for jna",
"description = CleanCommand.description + ' (modified)' def run(self): import shutil CleanCommand.run(self) if 1",
"!= self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc',",
"['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))],",
"Language :: Python\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python",
"#ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds | cmds_addon.items() ), **pkginfo",
"'*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd description",
"-dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds =",
"pkg root: {0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format(",
"## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'),",
"pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {} licenseclassifiers = {",
"[DEBUG=1] (* addon *)' user_options = [('opts=', 'o', 'Test options (default: -s {0})'.format(",
"in fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for path",
"history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is",
"setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with",
"in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T",
":: Public Domain\" } setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language",
":: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for",
"self.cwd, self.opts = None, '' def finalize_options(self): self.cwd = os.getcwd() def run(self): import",
":: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License",
"# os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)])",
"disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1) for path",
"Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software",
"'-I.'] # ) cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable =",
"#extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'),",
"Status :: 3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI",
"disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist for arg in sys.argv if",
"json, glob from distutils.command.clean import clean as CleanCommand from setuptools import setup, find_packages,",
"'.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.']))",
"for arg in sys.argv if cmd in arg] if [] != bad_cmds: print('Command(s)",
"packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE",
"{0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import",
"'run unittest discover [DEBUG=1] (* addon *)' user_options = [('opts=', 'o', 'Test options",
"], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))],",
"# os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS']",
"## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId>",
"Jython.') ## for jna #if 'java' not in sys.platform.lower(): # raise Exception('This package",
"None else {} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved :: Apache",
"CleanCommand from setuptools import setup, find_packages, Command #from setuptools import Extension # for",
"OSI Approved :: GNU General Public License v3 or later (GPLv3+)\", \"ISC\": \"License",
"Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language",
"Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), #",
"Approved :: GNU General Public License v3 or later (GPLv3+)\", \"ISC\": \"License ::",
"v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC License (ISCL)\",",
"from builtins import open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')])",
"in sys.argv if cmd in arg] if [] != bad_cmds: print('Command(s) {0} have",
":: Python :: Implementation :: Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'},",
"'/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for",
"f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes",
"json_bytes is not None else {} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI",
"path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand):",
"(modified)' def run(self): import shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist',",
"(* addon *)' user_options = [('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))]",
"if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description",
"#if 'java' not in sys.platform.lower(): # raise Exception('This package can only be used",
"= json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {} licenseclassifiers = { \"Apache-2.0\":",
"3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved ::",
"# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os, sys,",
"addon *)' user_options = [('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def",
"import absolute_import, print_function import os, sys, pkgutil, json, glob from distutils.command.clean import clean",
"raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1)",
"in pkg root: {0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0} -m nose2",
"used with Jython.') ## for jna #if 'java' not in sys.platform.lower(): # raise",
"for path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class",
"#if 'java' in sys.platform.lower(): # raise Exception('This package can not be used with",
"= ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod",
"with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo =",
"'*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd description #description",
"\"Apache-2.0\": \"License :: OSI Approved :: Apache Software License\", \"MIT\": \"License :: OSI",
"exc: print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst') as f_in:",
"*)' user_options = [('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self):",
"= pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {}",
"License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU General Public License v3 or",
"\"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme + '\\n\\n' + history, classifiers=[",
"DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format(",
"run(self): import subprocess assert os.getcwd() == self.cwd, 'Must be in pkg root: {0}'.format(",
"cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage",
"os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)'",
"raise Exception('This package can only be used with Jython.') ## jip install <groupId>:<artifactId>:<version>",
"-jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist):",
"if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox',",
"'java' in sys.platform.lower(): # raise Exception('This package can not be used with Jython.')",
"for filepat in filepats for file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats",
"= os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java' in sys.platform.lower(): #",
"__future__ import absolute_import, print_function import os, sys, pkgutil, json, glob from distutils.command.clean import",
":: OSI Approved :: Apache Software License\", \"MIT\": \"License :: OSI Approved ::",
"## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds",
"Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software License\"), \"Programming Language ::",
"fnmatch matches_pats = [os.path.join(root, file1) for path in paths for root, dirs, files",
"'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java' in",
"*)' description = 'run unittest discover [DEBUG=1] (* addon *)' user_options = [('opts=',",
"Extension # for Swig extension from builtins import open, dict PROJECT = 'intro_py.foreignc'",
"os, sys, pkgutil, json, glob from distutils.command.clean import clean as CleanCommand from setuptools",
"extension from builtins import open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE,",
"'.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), #",
"import os, sys, pkgutil, json, glob from distutils.command.clean import clean as CleanCommand from",
"paths for root, dirs, files in os.walk(path) for filepat in filepats for file1",
"in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description",
"Software License\"), \"Programming Language :: Python\", \"Programming Language :: Python :: 2.7\", \"Programming",
"filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for path in pathlist: if os.path.exists(path)",
"setuptools import setup, find_packages, Command #from setuptools import Extension # for Swig extension",
"cmd description #description = 'run nose2 [DEBUG=1] (* addon *)' description = 'run",
"= 'run unittest discover [DEBUG=1] (* addon *)' user_options = [('opts=', 'o', 'Test",
"MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License ::",
"'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist for arg",
"self.cwd, 'Must be in pkg root: {0}'.format( self.cwd) ## use nose2 #errno =",
"find_packages, Command #from setuptools import Extension # for Swig extension from builtins import",
"Public Domain\" } setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language ::",
"Approved :: Apache Software License\", \"MIT\": \"License :: OSI Approved :: MIT License\",",
"paths): import fnmatch matches_pats = [os.path.join(root, file1) for path in paths for root,",
"Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU General Public",
"'{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], #",
"runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.']",
"'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None,",
"= CleanCommand.description + ' (modified)' def run(self): import shutil CleanCommand.run(self) if 1 !=",
"'run nose2 [DEBUG=1] (* addon *)' description = 'run unittest discover [DEBUG=1] (*",
"# runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern',",
"# extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if",
"subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno) ##",
"install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types",
"readme = f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT,",
"nose2 [DEBUG=1] (* addon *)' description = 'run unittest discover [DEBUG=1] (* addon",
"} setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language :: English\", \"Development",
"except ImportError as exc: print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read() with",
"= Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)],",
"Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds | cmds_addon.items()",
"'\\n\\n' + history, classifiers=[ \"Natural Language :: English\", \"Development Status :: 3 -",
"def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1) for path in paths",
"coding: utf-8 -*- from __future__ import absolute_import, print_function import os, sys, pkgutil, json,",
":: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD",
"\"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved",
"= os.getcwd() def run(self): import subprocess assert os.getcwd() == self.cwd, 'Must be in",
"-m unittest discover {1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno) ## for",
"be used with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar",
"sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], #",
"PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools",
"3\", \"Programming Language :: Python :: Implementation :: Jython\", \"Topic :: Software Development\"",
"#PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] =",
"file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for",
"subprocess assert os.getcwd() == self.cwd, 'Must be in pkg root: {0}'.format( self.cwd) ##",
"{1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno) ## for ffi_lib #PREFIX =",
"+ files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for path in pathlist:",
"os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description +",
"## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar'))",
"OSI Approved :: Apache Software License\"), \"Programming Language :: Python\", \"Programming Language ::",
"for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)])",
"jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)'",
"#package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.',",
"for Swig extension from builtins import open, dict PROJECT = 'intro_py.foreignc' HERE =",
"exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root,",
"for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], #",
"os.walk(path) for filepat in filepats for file1 in fnmatch.filter(dirs + files, filepat)] return",
"'*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd description #description =",
"in paths for root, dirs, files in os.walk(path) for filepat in filepats for",
"= os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = '",
"# # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH',",
"sys.executable, self.opts), shell = True) raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX',",
"in arg] if [] != bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise",
"-*- coding: utf-8 -*- from __future__ import absolute_import, print_function import os, sys, pkgutil,",
"= subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno)",
"open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read()",
"or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC License (ISCL)\", \"Unlicense\":",
"_remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*',",
"= { \"Apache-2.0\": \"License :: OSI Approved :: Apache Software License\", \"MIT\": \"License",
"= [arg for cmd in blacklist for arg in sys.argv if cmd in",
"cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds | cmds_addon.items() ), **pkginfo )",
"'*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd",
"'-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.',",
"and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + '",
"'-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon =",
"for file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil",
"= subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell = True) errno =",
"been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats",
"as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if",
"os.getcwd() == self.cwd, 'Must be in pkg root: {0}'.format( self.cwd) ## use nose2",
"'), # swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if '1' == os.environ.get('DEBUG',",
"os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java' in sys.platform.lower(): # raise",
"= f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json')",
"cmd in arg] if [] != bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds))",
"'0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds try: import",
"'Must be in pkg root: {0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0}",
"'{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] #",
"for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0,",
"package can not be used with Jython.') ## for jna #if 'java' not",
"in os.walk(path) for filepat in filepats for file1 in fnmatch.filter(dirs + files, filepat)]",
":: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU",
"use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell =",
"(default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self):",
"Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path",
"java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def",
"# DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for",
"print_function import os, sys, pkgutil, json, glob from distutils.command.clean import clean as CleanCommand",
"-s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self): self.cwd",
"can only be used with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ##",
"ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds",
"## nose2 cmd description #description = 'run nose2 [DEBUG=1] (* addon *)' description",
"self.cwd = os.getcwd() def run(self): import subprocess assert os.getcwd() == self.cwd, 'Must be",
"def initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self): self.cwd = os.getcwd() def",
"SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats = [os.path.join(root, file1) for",
"'.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.',",
":: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language ::",
"'/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self): self.cwd = os.getcwd()",
"OSI Approved :: Apache Software License\", \"MIT\": \"License :: OSI Approved :: MIT",
"import setup, find_packages, Command #from setuptools import Extension # for Swig extension from",
"arg] if [] != bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2)",
":: Python :: 3\", \"Programming Language :: Python :: Implementation :: Jython\", \"Topic",
"= ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'),",
":: BSD License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU General Public License",
"--> javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve",
"# sys.executable, self.opts), shell = True) errno = subprocess.call('{0} -m unittest discover {1}'.format(",
"= 'run nose2 [DEBUG=1] (* addon *)' description = 'run unittest discover [DEBUG=1]",
"'*.class'], ['.'])) class Test0(Command): ## nose2 cmd description #description = 'run nose2 [DEBUG=1]",
"os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([",
"javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]'",
"= True) raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] =",
"distutils.command.clean import clean as CleanCommand from setuptools import setup, find_packages, Command #from setuptools",
":: Python\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python ::",
"self.opts), shell = True) raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local')",
"'{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '),",
"'__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class",
"print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst') as f_in: history",
"'-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for",
"used with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar",
"open('HISTORY.rst') as f_in: history = f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8'))",
"= 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java'",
"\"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved ::",
"-*- from __future__ import absolute_import, print_function import os, sys, pkgutil, json, glob from",
"Exception('This package can not be used with Jython.') ## for jna #if 'java'",
"shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def",
"'..')]) ## for cffi, swig #if 'java' in sys.platform.lower(): # raise Exception('This package",
"elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def run(self):",
"True) raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([",
"OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\",",
"for cmd in blacklist for arg in sys.argv if cmd in arg] if",
"in blacklist for arg in sys.argv if cmd in arg] if [] !=",
"blacklist for arg in sys.argv if cmd in arg] if [] != bad_cmds:",
"Exception('This package can only be used with Jython.') ## jip install <groupId>:<artifactId>:<version> -->",
"2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python :: Implementation",
"only be used with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java",
"'.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = '",
"in sys.platform.lower(): # raise Exception('This package can only be used with Jython.') ##",
"else {} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved :: Apache Software",
"_remove_pathlist(pathlist): import shutil for path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif",
"Swig extension from builtins import open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__))",
"setup, find_packages, Command #from setuptools import Extension # for Swig extension from builtins",
"'.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command):",
"be in pkg root: {0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0} -m",
"from setuptools import setup, find_packages, Command #from setuptools import Extension # for Swig",
"Command #from setuptools import Extension # for Swig extension from builtins import open,",
"as f_in: readme = f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes",
"{0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self): self.cwd =",
"is not None else {} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved",
"package can only be used with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar",
"libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), #",
"jna #if 'java' not in sys.platform.lower(): # raise Exception('This package can only be",
"sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java' in sys.platform.lower(): # raise Exception('This",
"jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist",
"\"Programming Language :: Python\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::",
"def finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess assert os.getcwd() == self.cwd,",
"# swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower():",
"BSD License\", \"GPL-3.0+\": \"License :: OSI Approved :: GNU General Public License v3",
"= ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS',",
"HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig #if 'java' in sys.platform.lower():",
"shell = True) raise SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH']",
"'*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'],",
"Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], #",
"'/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split('",
"root: {0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( #",
"swig #if 'java' in sys.platform.lower(): # raise Exception('This package can not be used",
"import Extension # for Swig extension from builtins import open, dict PROJECT =",
":: Apache Software License\"), \"Programming Language :: Python\", \"Programming Language :: Python ::",
"# library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), #",
"+ '\\n\\n' + history, classifiers=[ \"Natural Language :: English\", \"Development Status :: 3",
"Python\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\",",
"f_in: readme = f_in.read() with open('HISTORY.rst') as f_in: history = f_in.read() json_bytes =",
"coverage run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as",
"class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def run(self): import shutil CleanCommand.run(self)",
"os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds try:",
"= '{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass)",
"builtins import open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ##",
"raise Exception('This package can not be used with Jython.') ## for jna #if",
"<groupId> <artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg",
"return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~',",
"include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], #",
"'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts = None, ''",
"-retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd in blacklist for",
"files in os.walk(path) for filepat in filepats for file1 in fnmatch.filter(dirs + files,",
"extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # ) cmds_addon = {} if '1'",
"= {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable)",
"run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc:",
":: ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme +",
"# sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'),",
"os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def run(self): import",
"' (modified)' def run(self): import shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build',",
"class Test0(Command): ## nose2 cmd description #description = 'run nose2 [DEBUG=1] (* addon",
"'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ##",
"\"Programming Language :: Python :: Implementation :: Jython\", \"Topic :: Software Development\" ],",
"if json_bytes is not None else {} licenseclassifiers = { \"Apache-2.0\": \"License ::",
"None, '' def finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess assert os.getcwd()",
"for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]},",
"(* addon *)' description = 'run unittest discover [DEBUG=1] (* addon *)' user_options",
"Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\", \"GPL-3.0+\":",
"'.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT),",
"glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE",
"## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))],",
"CleanCommand.description + ' (modified)' def run(self): import shutil CleanCommand.run(self) if 1 != self.all:",
"# DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi",
"initialize_options(self): self.cwd, self.opts = None, '' def finalize_options(self): self.cwd = os.getcwd() def run(self):",
":: Implementation :: Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.',",
"+ ' (modified)' def run(self): import shutil CleanCommand.run(self) if 1 != self.all: return",
"extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.',",
"filepat in filepats for file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats def",
"try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst') as f_in:",
"'{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except",
"Implementation :: Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]),",
"True) errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell = True)",
"'/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T",
"description = 'run unittest discover [DEBUG=1] (* addon *)' user_options = [('opts=', 'o',",
"\"ISC\": \"License :: OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License :: Public",
"def run(self): import shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*',",
"from distutils.command.clean import clean as CleanCommand from setuptools import setup, find_packages, Command #from",
"# '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], #",
"CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov',",
"## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean':",
"setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst') as f_in: readme =",
"library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS',",
"= [('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts",
"if [] != bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register',",
"\"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0]",
"#os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS',",
"License\", \"MIT\": \"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License :: OSI",
"English\", \"Development Status :: 3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License",
"add-on cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst')",
"bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats,",
"print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths):",
"import clean as CleanCommand from setuptools import setup, find_packages, Command #from setuptools import",
"[arg for cmd in blacklist for arg in sys.argv if cmd in arg]",
"'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log',",
"\"License :: OSI Approved :: Apache Software License\"), \"Programming Language :: Python\", \"Programming",
"\"License :: OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\"",
"pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {} licenseclassifiers",
"{1}'.format( # sys.executable, self.opts), shell = True) errno = subprocess.call('{0} -m unittest discover",
"sys.platform.lower(): # raise Exception('This package can not be used with Jython.') ## for",
"subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell = True) errno = subprocess.call('{0}",
"{ \"Apache-2.0\": \"License :: OSI Approved :: Apache Software License\", \"MIT\": \"License ::",
"(ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme + '\\n\\n' + history,",
"dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for cffi, swig",
"def run(self): import subprocess assert os.getcwd() == self.cwd, 'Must be in pkg root:",
"return matches_pats def _remove_pathlist(pathlist): import shutil for path in pathlist: if os.path.exists(path) and",
"Clean0(CleanCommand): description = CleanCommand.description + ' (modified)' def run(self): import shutil CleanCommand.run(self) if",
"self.opts = None, '' def finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess",
"'/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ #",
"<artifactId> '[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for",
"[os.path.join(root, file1) for path in paths for root, dirs, files in os.walk(path) for",
"Test0(Command): ## nose2 cmd description #description = 'run nose2 [DEBUG=1] (* addon *)'",
"import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst') as f_in: readme",
"#from setuptools import Extension # for Swig extension from builtins import open, dict",
"user_options = [('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd,",
"setuptools import Extension # for Swig extension from builtins import open, dict PROJECT",
"License v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC License",
"bad_cmds = [arg for cmd in blacklist for arg in sys.argv if cmd",
"<groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency <groupId> <artifactId> '[<version>,)' -types jar",
"matches_pats = [os.path.join(root, file1) for path in paths for root, dirs, files in",
"self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis', 'htmlcov', '.tox', '*.so', '*.pyc', '*.pyo',",
"'.tox', '*.so', '*.pyc', '*.pyo', '*~', '.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2",
"# extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '), # swig_opts=['-modern', '-I.'] # )",
"not in sys.platform.lower(): # raise Exception('This package can only be used with Jython.')",
"nose2 cmd description #description = 'run nose2 [DEBUG=1] (* addon *)' description =",
":: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software License\"), \"Programming Language",
"'' def finalize_options(self): self.cwd = os.getcwd() def run(self): import subprocess assert os.getcwd() ==",
"## for cffi, swig #if 'java' in sys.platform.lower(): # raise Exception('This package can",
"'/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on",
"disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def _matches_filepatterns(filepats, paths): import fnmatch matches_pats =",
"sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), #",
"'/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/',",
"## use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell",
"discover {1}'.format( sys.executable, self.opts), shell = True) raise SystemExit(errno) ## for ffi_lib #PREFIX",
":: GNU General Public License v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI",
"USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension",
"for root, dirs, files in os.walk(path) for filepat in filepats for file1 in",
"#errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts), shell = True) errno",
"shell = True) errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell",
"run(self): import shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache',",
"= f_in.read() json_bytes = pkgutil.get_data(PROJECT, 'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not",
"# raise Exception('This package can only be used with Jython.') ## jip install",
"SystemExit(errno) ## for ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH',",
"OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup(",
"in sys.platform.lower(): # raise Exception('This package can not be used with Jython.') ##",
"ffi_lib #PREFIX = os.environ.get('PREFIX', '/usr/local') #os.environ['LD_LIBRARY_PATH'] = ':'.join([ # os.environ.get('LD_LIBRARY_PATH', '.'), '{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS']",
"Python :: Implementation :: Jython\", \"Topic :: Software Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT,",
"!= bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload') def",
"history, classifiers=[ \"Natural Language :: English\", \"Development Status :: 3 - Alpha\", \"Intended",
"'[<version>,)' -types jar -retrieve 'javalib/[artifact]-[revision](-[classifier]).[ext]' #sys.path.extend(glob.glob('javalib/*.jar')) def disable_commands(*blacklist): bad_cmds = [arg for cmd",
"['.'])) class Test0(Command): ## nose2 cmd description #description = 'run nose2 [DEBUG=1] (*",
"as CleanCommand from setuptools import setup, find_packages, Command #from setuptools import Extension #",
"in filepats for file1 in fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist):",
"self.cwd) ## use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable, self.opts),",
"Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency <groupId>",
"ISC License (ISCL)\", \"Unlicense\": \"License :: Public Domain\" } setup( long_description=readme + '\\n\\n'",
"\"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software License\"),",
"with Jython.') ## jip install <groupId>:<artifactId>:<version> --> javalib/*.jar ## java -jar ivy.jar -dependency",
"long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language :: English\", \"Development Status ::",
"ImportError as exc: print(repr(exc)) with open('README.rst') as f_in: readme = f_in.read() with open('HISTORY.rst')",
"DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig",
"# include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)],",
"errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell = True) raise",
"import shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__',",
"import fnmatch matches_pats = [os.path.join(root, file1) for path in paths for root, dirs,",
"Apache Software License\", \"MIT\": \"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License",
"GNU General Public License v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved",
"+ history, classifiers=[ \"Natural Language :: English\", \"Development Status :: 3 - Alpha\",",
"[] != bad_cmds: print('Command(s) {0} have been disabled; exiting'.format(bad_cmds)) raise SystemExit(2) disable_commands('register', 'upload')",
"self.opts), shell = True) errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts),",
"'1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools add-on",
"'/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ## for cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ##",
"json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {} licenseclassifiers = { \"Apache-2.0\": \"License",
"# sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.', PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT],",
"\"Development Status :: 3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License ::",
"be used with Jython.') ## for jna #if 'java' not in sys.platform.lower(): #",
"= True) errno = subprocess.call('{0} -m unittest discover {1}'.format( sys.executable, self.opts), shell =",
"\"GPL-3.0+\": \"License :: OSI Approved :: GNU General Public License v3 or later",
"import shutil for path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path):",
"'{}/lib'.format(PREFIX)]) #os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([",
"'resources/pkginfo.json') pkginfo = json.loads(json_bytes.decode(encoding='utf-8')) if json_bytes is not None else {} licenseclassifiers =",
"for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds |",
"shutil for path in pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path)",
"cmds try: import setup_addcmds cmds_addon.update(setup_addcmds.cmdclass) except ImportError as exc: print(repr(exc)) with open('README.rst') as",
"Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python",
"['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, # DON'T USE #test_suite='{0}.tests'.format(PROJECT), ##",
"nose2 {1}'.format( # sys.executable, self.opts), shell = True) errno = subprocess.call('{0} -m unittest",
"os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ##",
"later (GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC License (ISCL)\", \"Unlicense\": \"License",
"Public License v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved :: ISC",
"import open, dict PROJECT = 'intro_py.foreignc' HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.extend([os.path.join(HERE, '..')]) ## for",
"if cmd in arg] if [] != bad_cmds: print('Command(s) {0} have been disabled;",
"General Public License v3 or later (GPLv3+)\", \"ISC\": \"License :: OSI Approved ::",
"Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # # sources=['{0}/classic_c_wrap.c'.format('build')], # sources=['{0}/classic_c.i'.format(PROJECT.replace('.', '/'))], # include_dirs=['.',",
"utf-8 -*- from __future__ import absolute_import, print_function import os, sys, pkgutil, json, glob",
"Software License\", \"MIT\": \"License :: OSI Approved :: MIT License\", \"BSD-3-Clause\": \"License ::",
"{} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) #",
"\"License :: OSI Approved :: Apache Software License\", \"MIT\": \"License :: OSI Approved",
"' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod =",
"#os.environ['LDFLAGS'] = ' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ #",
"extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test': Test0}).items() ## setuptools add-on cmds | cmds_addon.items() ),",
"Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software License\"), \"Programming",
"Language :: Python :: Implementation :: Jython\", \"Topic :: Software Development\" ], #package_dir={'':",
"== os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds",
"setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language :: English\", \"Development Status",
"classifiers=[ \"Natural Language :: English\", \"Development Status :: 3 - Alpha\", \"Intended Audience",
"# libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split(' '),",
"Domain\" } setup( long_description=readme + '\\n\\n' + history, classifiers=[ \"Natural Language :: English\",",
"cffi #cffi_modules=['{0}/classic_build.py:ffibuilder'.format( # PROJECT.replace('.', '/'))], ## for Swig extension #ext_modules=[extension_mod], cmdclass=dict(dict({'clean': Clean0, 'test':",
"pathlist: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) class Clean0(CleanCommand): description =",
":: 3 - Alpha\", \"Intended Audience :: Developers\", licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved",
"os.environ.get('CPPFLAGS', '-Ibuild/include'), # '-I{}/include'.format(PREFIX)]) ## for Swig extension #extension_mod = Extension(name='{0}._classic_c'.format(PROJECT), # #",
"root, dirs, files in os.walk(path) for filepat in filepats for file1 in fnmatch.filter(dirs",
"licenseclassifiers.get('Apache-2.0', \"License :: OSI Approved :: Apache Software License\"), \"Programming Language :: Python\",",
"[('opts=', 'o', 'Test options (default: -s {0})'.format( '/'.join(PROJECT.split('.')[:-1])))] def initialize_options(self): self.cwd, self.opts =",
"shutil CleanCommand.run(self) if 1 != self.all: return _remove_pathlist(_matches_filepatterns(['build', 'dist', '*.egg*', '.cache', '__pycache__', '.hypothesis',",
"[DEBUG=1] (* addon *)' description = 'run unittest discover [DEBUG=1] (* addon *)'",
"{0}'.format( self.cwd) ## use nose2 #errno = subprocess.call('{0} -m nose2 {1}'.format( # sys.executable,",
"path in glob.glob('{0}/*.py'.format('/'.join(PROJECT.split('.')[:-1])))], #data_files=[('', ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))])], # DON'T USE #package_data={'': ['{0}/tests/__main__.py'.format(PROJECT.replace('.', '/'))]}, #",
"'.coverage*', '*.log', '*.class'], ['.'])) class Test0(Command): ## nose2 cmd description #description = 'run",
"# ) cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0}",
"'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS', '-Ibuild/include').split(' '), # extra_link_args=os.environ.get('LDFLAGS', '-Lbuild/lib').split('",
"License\"), \"Programming Language :: Python\", \"Programming Language :: Python :: 2.7\", \"Programming Language",
"PROJECT.replace('.', '/'), '{}/include'.format(PREFIX)], # library_dirs=os.environ.get('LD_LIBRARY_PATH', 'build/lib').split(':'), # libraries=[PROJECT], # runtime_library_dirs=['$ORIGIN/', '{}/lib'.format(PREFIX)], # extra_compile_args=os.environ.get('CPPFLAGS',",
"fnmatch.filter(dirs + files, filepat)] return matches_pats def _remove_pathlist(pathlist): import shutil for path in",
"not None else {} licenseclassifiers = { \"Apache-2.0\": \"License :: OSI Approved ::",
"' '.join([ # os.environ.get('LDFLAGS', '-Lbuild/lib'), '-L{}/lib'.format(PREFIX)]) #os.environ['CPPFLAGS'] = ' '.join([ # os.environ.get('CPPFLAGS', '-Ibuild/include'),",
"pkgutil, json, glob from distutils.command.clean import clean as CleanCommand from setuptools import setup,",
":: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python ::",
"sys.executable = '{0} -m coverage run'.format(sys.executable) # setuptools add-on cmds try: import setup_addcmds",
"\"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",",
") cmds_addon = {} if '1' == os.environ.get('DEBUG', '0').lower(): sys.executable = '{0} -m",
"file1) for path in paths for root, dirs, files in os.walk(path) for filepat",
"License\", \"BSD-3-Clause\": \"License :: OSI Approved :: BSD License\", \"GPL-3.0+\": \"License :: OSI",
"Development\" ], #package_dir={'': '.'}, #packages=find_packages(include=[PROJECT, '{0}.tests'.format(PROJECT.replace('.', '/'))]), packages=find_packages(), # py_modules=[splitext(basename(path))[0] for path in"
] |
[
"webbrowser from tempfile import gettempdir import pytest from pprof import cpu from pprof.cpu",
"@pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda",
"assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda",
"test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report =",
"inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__, 16, \"f\"): test_input}) assert",
"path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1, 1)",
"mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path",
"import webbrowser from tempfile import gettempdir import pytest from pprof import cpu from",
"\"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f",
"from tempfile import gettempdir import pytest from pprof import cpu from pprof.cpu import",
"report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report()",
"def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report",
"cpu from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): #",
"wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18,",
"def f(a, b): # fake func res = a + b return res",
"cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is",
"1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001),",
"(19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], )",
"fake func res = a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report",
"<gh_stars>1-10 import atexit import inspect import os.path import webbrowser from tempfile import gettempdir",
"0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker,",
"tempfile import gettempdir import pytest from pprof import cpu from pprof.cpu import show_html",
"import inspect import os.path import webbrowser from tempfile import gettempdir import pytest from",
"f(a, b): # fake func res = a + b return res @pytest.mark.run(order=-1)",
"b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report == empty_report",
"1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)],",
"(19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\")",
"source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__, 16, \"f\"):",
"x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f) assert",
"([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected):",
"inspect import os.path import webbrowser from tempfile import gettempdir import pytest from pprof",
"assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19,",
"@pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0),",
"import cpu from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b):",
"300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19,",
"atexit import inspect import os.path import webbrowser from tempfile import gettempdir import pytest",
"0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\",",
"lambda x: source) report = show_html({(__file__, 16, \"f\"): test_input}) assert report.__contains__(expected) is True",
"\"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path =",
"x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path)",
"= inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__, 16, \"f\"): test_input})",
"True wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [",
"\".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input,",
"import pytest from pprof import cpu from pprof.cpu import show_html empty_report = '<html><head><meta",
"1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect,",
"x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f)",
"charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res = a + b return",
"from pprof import cpu from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def",
"1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source =",
"(19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"), ([(18, 1,",
"\"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda",
"test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__,",
"1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"),",
"empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res = a",
"assert os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0)",
"pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func",
"res = a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report()",
"0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ],",
"== 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"),",
"\"getblock\", lambda x: source) report = show_html({(__file__, 16, \"f\"): test_input}) assert report.__contains__(expected) is",
"0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"), ([(18,",
"cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1,",
"return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit,",
"1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def",
"wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1,",
"\"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19,",
"= cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1,",
"= '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res = a +",
"import os.path import webbrowser from tempfile import gettempdir import pytest from pprof import",
"= cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser,",
"== empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x)",
"lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\"",
"from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake",
"2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18,",
"test_cpu(mocker): report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x)",
"import gettempdir import pytest from pprof import cpu from pprof.cpu import show_html empty_report",
"+ b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report ==",
"@pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1,",
"cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\",",
"os.path import webbrowser from tempfile import gettempdir import pytest from pprof import cpu",
"\"300.0ms\"), ([(18, 1, 0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1,",
"func res = a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report =",
"report == empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x:",
"1, 1_000_001), (19, 1, 0)], \"1.00s\"), ], ) def test_show_html(mocker, test_input, expected): source",
"expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__, 16,",
"([(18, 1, 0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)],",
"], ) def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x:",
"b): # fake func res = a + b return res @pytest.mark.run(order=-1) def",
"gettempdir import pytest from pprof import cpu from pprof.cpu import show_html empty_report =",
"import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res",
"empty_report mocker.patch.object(atexit, \"register\", lambda x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report()",
"# fake func res = a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker):",
"mocker.patch.object(inspect, \"getblock\", lambda x: source) report = show_html({(__file__, 16, \"f\"): test_input}) assert report.__contains__(expected)",
"res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\",",
"lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f =",
"os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize(",
"is True wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\",",
"cpu(f) assert wrapper_f(1, 1) == 2 @pytest.mark.run(order=0) @pytest.mark.parametrize( \"test_input,expected\", [ ([(18, 1, 0),",
"import atexit import inspect import os.path import webbrowser from tempfile import gettempdir import",
"def test_cpu(mocker): report = cpu.get_report() assert report == empty_report mocker.patch.object(atexit, \"register\", lambda x:",
"1, 0), (19, 1, 0)], \".\"), ([(18, 1, 1_000_001), (19, 1, 0)], \"1.00s\"),",
") def test_show_html(mocker, test_input, expected): source = inspect.getsource(f).split(\"\\n\") mocker.patch.object(inspect, \"getblock\", lambda x: source)",
"x: x) cpu.auto_report() mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert",
"[ ([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1,",
"mocker.patch.object(webbrowser, \"open\", lambda x: x) cpu.open_report() path = f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True",
"a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert report",
"f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1, 1) == 2",
"([(18, 1, 0), (19, 1, 300_000)], \"300.0ms\"), ([(18, 1, 0), (19, 1, 0)],",
"= f\"{gettempdir()}/cpu_profile.html\" assert os.path.exists(path) is True wrapper_f = cpu(f) assert wrapper_f(1, 1) ==",
"pytest from pprof import cpu from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>'",
"pprof import cpu from pprof.cpu import show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a,",
"'<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res = a + b",
"show_html empty_report = '<html><head><meta charset=\"UTF-8\"/></head></html>' def f(a, b): # fake func res =",
"= a + b return res @pytest.mark.run(order=-1) def test_cpu(mocker): report = cpu.get_report() assert"
] |
[
"test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test: %s\" % self.name class YamlException(Exception):",
"= api_test self.api_config = api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def",
"file is loaded by py.test to discover API tests import pytest from apitest",
"APITest from loader import yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\" and",
"reportinfo(self): return self.fspath, 0, \"API Test: %s\" % self.name class YamlException(Exception): \"\"\" custom",
"test, config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent)",
"config = doc.get('config', {}) for test in doc.get('tests', []): yield APITestItem(test['name'], self, test,",
"and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if",
"This file is loaded by py.test to discover API tests import pytest from",
"tests import pytest from apitest import APITest from loader import yaml_load def pytest_collect_file(parent,",
"def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config",
"parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config = api_config def",
"if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self):",
"self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test: %s\" % self.name class",
"return self.fspath, 0, \"API Test: %s\" % self.name class YamlException(Exception): \"\"\" custom exception",
"\"API Test: %s\" % self.name class YamlException(Exception): \"\"\" custom exception for error reporting.",
"loader import yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return",
"api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0,",
"super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config = api_config def runtest(self): test =",
"pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File):",
"class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test =",
"parent) self.api_test = api_test self.api_config = api_config def runtest(self): test = APITest(self.api_test, self.api_config)",
"APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test: %s\" % self.name",
"doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self, name, parent,",
"is loaded by py.test to discover API tests import pytest from apitest import",
"apitest import APITest from loader import yaml_load def pytest_collect_file(parent, path): if path.ext ==",
"yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for test in doc.get('tests', []): yield",
"# This file is loaded by py.test to discover API tests import pytest",
"api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config = api_config def runtest(self):",
"self.api_test = api_test self.api_config = api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest()",
"path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def",
"doc: config = doc.get('config', {}) for test in doc.get('tests', []): yield APITestItem(test['name'], self,",
"yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config):",
"0, \"API Test: %s\" % self.name class YamlException(Exception): \"\"\" custom exception for error",
"collect(self): doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for test in",
"in doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self, name,",
"py.test to discover API tests import pytest from apitest import APITest from loader",
"discover API tests import pytest from apitest import APITest from loader import yaml_load",
"api_test self.api_config = api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self):",
"test in doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self,",
"{}) for test in doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item):",
"if doc: config = doc.get('config', {}) for test in doc.get('tests', []): yield APITestItem(test['name'],",
"APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem,",
"import yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path,",
"= doc.get('config', {}) for test in doc.get('tests', []): yield APITestItem(test['name'], self, test, config)",
"class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config', {})",
"__init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config =",
"APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test",
"return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc: config",
"api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config = api_config def runtest(self): test",
"for test in doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def",
"config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test",
"API tests import pytest from apitest import APITest from loader import yaml_load def",
"to discover API tests import pytest from apitest import APITest from loader import",
"== \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc =",
"path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc:",
"def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API",
"\".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open())",
"= yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for test in doc.get('tests', []):",
"def collect(self): doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for test",
"self.api_config = api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return",
"self).__init__(name, parent) self.api_test = api_test self.api_config = api_config def runtest(self): test = APITest(self.api_test,",
"Test: %s\" % self.name class YamlException(Exception): \"\"\" custom exception for error reporting. \"\"\"",
"self, test, config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test, api_config): super(APITestItem, self).__init__(name,",
"path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc",
"APITestFile(path, parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc: config =",
"APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for",
"= APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test: %s\" %",
"loaded by py.test to discover API tests import pytest from apitest import APITest",
"pytest from apitest import APITest from loader import yaml_load def pytest_collect_file(parent, path): if",
"test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test: %s\"",
"[]): yield APITestItem(test['name'], self, test, config) class APITestItem(pytest.Item): def __init__(self, name, parent, api_test,",
"from loader import yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"):",
"runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath, 0, \"API Test:",
"import pytest from apitest import APITest from loader import yaml_load def pytest_collect_file(parent, path):",
"self.fspath, 0, \"API Test: %s\" % self.name class YamlException(Exception): \"\"\" custom exception for",
"by py.test to discover API tests import pytest from apitest import APITest from",
"from apitest import APITest from loader import yaml_load def pytest_collect_file(parent, path): if path.ext",
"doc.get('config', {}) for test in doc.get('tests', []): yield APITestItem(test['name'], self, test, config) class",
"doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config', {}) for test in doc.get('tests',",
"def reportinfo(self): return self.fspath, 0, \"API Test: %s\" % self.name class YamlException(Exception): \"\"\"",
"yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent)",
"name, parent, api_test, api_config): super(APITestItem, self).__init__(name, parent) self.api_test = api_test self.api_config = api_config",
"import APITest from loader import yaml_load def pytest_collect_file(parent, path): if path.ext == \".yaml\"",
"parent) class APITestFile(pytest.File): def collect(self): doc = yaml_load(self.fspath.open()) if doc: config = doc.get('config',",
"def pytest_collect_file(parent, path): if path.ext == \".yaml\" and path.basename.startswith(\"test\"): return APITestFile(path, parent) class",
"= api_config def runtest(self): test = APITest(self.api_test, self.api_config) test.runtest() def reportinfo(self): return self.fspath,"
] |
[
"= self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( { \"after\": after, \"before\": before,",
"attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\"",
"Dict, Type, TypeVar import attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\")",
") return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d",
"from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\"))",
"def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() after =",
"-> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts =",
"= src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls( after=after, before=before,",
"after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls( after=after, before=before, ) return",
"before: SegmentContext def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict()",
"return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d =",
"d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls( after=after,",
"field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy()",
"Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update(",
"Dict[str, Any] = {} field_dict.update( { \"after\": after, \"before\": before, } ) return",
"src_dict: Dict[str, Any]) -> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before =",
"Any] = {} field_dict.update( { \"after\": after, \"before\": before, } ) return field_dict",
"Any, Dict, Type, TypeVar import attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\",",
"import Any, Dict, Type, TypeVar import attr from ..models.segment_context import SegmentContext T =",
"} ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:",
"<reponame>kairntech/sherpa-client from typing import Any, Dict, Type, TypeVar import attr from ..models.segment_context import",
"after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before",
"before, } ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) ->",
"SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]: after",
"typing import Any, Dict, Type, TypeVar import attr from ..models.segment_context import SegmentContext T",
"from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\"",
"\"before\": before, } ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any])",
"Dict[str, Any]) -> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\"))",
"field_dict.update( { \"after\": after, \"before\": before, } ) return field_dict @classmethod def from_dict(cls:",
"TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self)",
"import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext",
"after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( {",
"T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls(",
"to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any]",
"@attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str,",
"bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self) ->",
"import attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts:",
"Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] = {}",
"class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]:",
"{ \"after\": after, \"before\": before, } ) return field_dict @classmethod def from_dict(cls: Type[T],",
"\"\"\" after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict()",
"= TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext def",
"= self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( { \"after\":",
"self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( { \"after\": after,",
"after, \"before\": before, } ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str,",
"@classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() after",
"from typing import Any, Dict, Type, TypeVar import attr from ..models.segment_context import SegmentContext",
"..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after:",
"Any]) -> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts",
"Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before",
"T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before: SegmentContext",
"SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class SegmentContexts: \"\"\" \"\"\" after: SegmentContext before:",
"field_dict: Dict[str, Any] = {} field_dict.update( { \"after\": after, \"before\": before, } )",
"= SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls( after=after, before=before, ) return segment_contexts",
"TypeVar import attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True) class",
"before = self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( { \"after\": after, \"before\":",
"src_dict.copy() after = SegmentContext.from_dict(d.pop(\"after\")) before = SegmentContext.from_dict(d.pop(\"before\")) segment_contexts = cls( after=after, before=before, )",
"Type, TypeVar import attr from ..models.segment_context import SegmentContext T = TypeVar(\"T\", bound=\"SegmentContexts\") @attr.s(auto_attribs=True)",
"def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str,",
"{} field_dict.update( { \"after\": after, \"before\": before, } ) return field_dict @classmethod def",
"\"\"\" \"\"\" after: SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]: after =",
"= {} field_dict.update( { \"after\": after, \"before\": before, } ) return field_dict @classmethod",
"\"after\": after, \"before\": before, } ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict:",
"self.before.to_dict() field_dict: Dict[str, Any] = {} field_dict.update( { \"after\": after, \"before\": before, }",
"-> Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict: Dict[str, Any] =",
"SegmentContext before: SegmentContext def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before =",
"SegmentContext def to_dict(self) -> Dict[str, Any]: after = self.after.to_dict() before = self.before.to_dict() field_dict:"
] |
[
"\" Hello there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World",
"my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\" => false",
"help them with our own Hashtag Generator! Here's the deal: It must start",
"=> false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()]) if",
"thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\"",
"trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\" =>",
"Hashtag Generator! Here's the deal: It must start with a hashtag (#). All",
"an empty string it must return false. Examples \" Hello there thanks for",
"\" => \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for",
"false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()]) if (len(s)",
"time typing in hashtags. Let's help them with our own Hashtag Generator! Here's",
"words must have their first letter capitalized. If the final result is longer",
"result is an empty string it must return false. Examples \" Hello there",
"marketing team is spending way too much time typing in hashtags. Let's help",
"All words must have their first letter capitalized. If the final result is",
"+''.join([i.capitalize() for i in s.split()]) if (len(s) < 140 and s) else False",
"Here's the deal: It must start with a hashtag (#). All words must",
"is an empty string it must return false. Examples \" Hello there thanks",
"is spending way too much time typing in hashtags. Let's help them with",
"Generator! Here's the deal: It must start with a hashtag (#). All words",
"have their first letter capitalized. If the final result is longer than 140",
"return false. If the input or the result is an empty string it",
"much time typing in hashtags. Let's help them with our own Hashtag Generator!",
"It must start with a hashtag (#). All words must have their first",
"them with our own Hashtag Generator! Here's the deal: It must start with",
"(#). All words must have their first letter capitalized. If the final result",
"must return false. If the input or the result is an empty string",
"with a hashtag (#). All words must have their first letter capitalized. If",
"\" Hello World \" => \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return",
"the input or the result is an empty string it must return false.",
"If the final result is longer than 140 chars it must return false.",
"false. If the input or the result is an empty string it must",
"team is spending way too much time typing in hashtags. Let's help them",
"for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\"",
"our own Hashtag Generator! Here's the deal: It must start with a hashtag",
"''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()]) if (len(s) <",
"spending way too much time typing in hashtags. Let's help them with our",
"or the result is an empty string it must return false. Examples \"",
"If the input or the result is an empty string it must return",
"input or the result is an empty string it must return false. Examples",
"first letter capitalized. If the final result is longer than 140 chars it",
"generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()]) if (len(s) < 140 and",
"the final result is longer than 140 chars it must return false. If",
"World \" => \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize()",
"=> \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\" => false ''' def",
"140 chars it must return false. If the input or the result is",
"way too much time typing in hashtags. Let's help them with our own",
"string it must return false. Examples \" Hello there thanks for trying my",
"letter capitalized. If the final result is longer than 140 chars it must",
"too much time typing in hashtags. Let's help them with our own Hashtag",
"hashtag (#). All words must have their first letter capitalized. If the final",
"Examples \" Hello there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello",
"empty string it must return false. Examples \" Hello there thanks for trying",
"there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" =>",
"must return false. Examples \" Hello there thanks for trying my Kata\" =>",
": The marketing team is spending way too much time typing in hashtags.",
"than 140 chars it must return false. If the input or the result",
"Hello World \" => \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return '#'",
"chars it must return false. If the input or the result is an",
"typing in hashtags. Let's help them with our own Hashtag Generator! Here's the",
"with our own Hashtag Generator! Here's the deal: It must start with a",
"return false. Examples \" Hello there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\"",
"\"\" => false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()])",
"capitalized. If the final result is longer than 140 chars it must return",
"Let's help them with our own Hashtag Generator! Here's the deal: It must",
"# https://www.codewars.com/kata/52449b062fb80683ec000024/ ''' Instructions : The marketing team is spending way too much",
"it must return false. If the input or the result is an empty",
"Hello there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \"",
"=> \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i",
"is longer than 140 chars it must return false. If the input or",
"Instructions : The marketing team is spending way too much time typing in",
"\"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\" => false ''' def generate_hashtag(s):",
"https://www.codewars.com/kata/52449b062fb80683ec000024/ ''' Instructions : The marketing team is spending way too much time",
"return '#' +''.join([i.capitalize() for i in s.split()]) if (len(s) < 140 and s)",
"it must return false. Examples \" Hello there thanks for trying my Kata\"",
"''' Instructions : The marketing team is spending way too much time typing",
"The marketing team is spending way too much time typing in hashtags. Let's",
"'#' +''.join([i.capitalize() for i in s.split()]) if (len(s) < 140 and s) else",
"deal: It must start with a hashtag (#). All words must have their",
"the deal: It must start with a hashtag (#). All words must have",
"their first letter capitalized. If the final result is longer than 140 chars",
"must have their first letter capitalized. If the final result is longer than",
"Kata\" => \"#HelloThereThanksForTryingMyKata\" \" Hello World \" => \"#HelloWorld\" \"\" => false '''",
"final result is longer than 140 chars it must return false. If the",
"own Hashtag Generator! Here's the deal: It must start with a hashtag (#).",
"a hashtag (#). All words must have their first letter capitalized. If the",
"\"#HelloWorld\" \"\" => false ''' def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in",
"start with a hashtag (#). All words must have their first letter capitalized.",
"result is longer than 140 chars it must return false. If the input",
"in hashtags. Let's help them with our own Hashtag Generator! Here's the deal:",
"hashtags. Let's help them with our own Hashtag Generator! Here's the deal: It",
"the result is an empty string it must return false. Examples \" Hello",
"must start with a hashtag (#). All words must have their first letter",
"def generate_hashtag(s): return '#' +''.join([i.capitalize() for i in s.split()]) if (len(s) < 140",
"longer than 140 chars it must return false. If the input or the",
"false. Examples \" Hello there thanks for trying my Kata\" => \"#HelloThereThanksForTryingMyKata\" \""
] |
[] |
[
"#Pygame import pygame pygame.init() #os to access files import os #Inits #import win",
"#Import the libraries #Pygame import pygame pygame.init() #os to access files import os",
"the libraries #Pygame import pygame pygame.init() #os to access files import os #Inits",
"libraries #Pygame import pygame pygame.init() #os to access files import os #Inits #import"
] |
[
"of the original source clip file used for thumbnail # {dstframe} - The",
"widthTextChanged(self): # Slot to handle change of thumbnail format combo change state value",
"self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] =",
"pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\") for index,",
"Trigger to make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout) layout.addRow(\"Size:\",thumbSizeLayout)",
"the frame from which to pick the thumbnail.\\nCustom allows you to specify a",
"self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"]))",
"use Hiero's internal thumbnail size or specify a box or width/height scaling in",
"be used via the Export dialog via Shot, Clip or Sequence Processor #",
"# {frametype} - Position where the thumbnail was taken from (first/middle/last/custom) # {srcframe}",
"height # Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115)",
"file used for thumbnail # {dstframe} - The destination frame (timeline time) number",
"if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value)",
"== str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset",
"self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit()",
"task which can be used via the Export dialog via Shot, Clip or",
"to handle change of thumbnail format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"]",
"from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item",
"frame number of the original source clip file used for thumbnail # {dstframe}",
"\"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask,",
"in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit()",
"item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit()",
"where the thumbnail was taken from (first/middle/last/custom) # {srcframe} - The frame number",
"0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox()",
"self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False)",
"self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in",
"9, 0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox =",
"layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout = QHBoxLayout()",
"unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout)",
"state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else:",
"elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value)",
"can be used via the Export dialog via Shot, Clip or Sequence Processor",
"Slot to handle change of thumbnail format combo change state value = self._heightBox.text()",
"self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value",
"self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0,",
"value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to handle change",
"in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft)",
"tokens exist for: # {frametype} - Position where the thumbnail was taken from",
"type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item",
"change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot",
"self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout =",
"Hiero's internal thumbnail size or specify a box or width/height scaling in pixels.\")",
"change of thumbnail format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value)",
"self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To",
"self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb",
"index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel",
"= QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave",
"taken from (first/middle/last/custom) # {srcframe} - The frame number of the original source",
"* import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\"",
"self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it",
"self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set the enabled state correctly",
"height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0)",
"thumbnail size or specify a box or width/height scaling in pixels.\") thumbSizeTypes =",
"original source clip file used for thumbnail # {dstframe} - The destination frame",
"of thumbnail format combo change state value = self._thumbSizeComboBox.currentText() if value == \"Default\":",
"to handle change of thumbnail format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"]",
"Slot to handle change of thumbnail format combo change state value = self._frameTypeComboBox.currentText()",
"unicode(value) def customOffsetTextChanged(self): # Slot to handle change of thumbnail format combo change",
"layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to",
"box or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\",",
"change of thumbnail format combo change state value = self._frameTypeComboBox.currentText() if str(value) ==",
"self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle change of thumbnail",
"relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index,",
"if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the",
"format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index,",
"\"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget,",
"= \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self,",
"PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame",
"to pick the thumbnail.\\nCustom allows you to specify a custom frame offset, relative",
"combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot",
"self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle change of",
"self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as Default",
"value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False)",
"index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) #",
"self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to handle change of thumbnail",
"self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set the",
"value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to handle change",
"Slot to handle change of thumbnail format combo change state value = self._customFrameLineEdit.text()",
"Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index)",
"\"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\":",
"combo change state value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False)",
"= unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle change of thumbnail format",
"thumbSizeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo change state",
"# QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\",",
"# Thumbnail Exporter Task UI # Thumbnail image export task which can be",
"= QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)),",
"= unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to",
"* from PySide2.QtGui import * from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask",
"# To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. #",
"ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: #",
"(self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item",
"thumbnail format combo change state value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False)",
"change of thumbnail format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value)",
"thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the",
"\"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]):",
"to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: # {frametype} - Position",
"and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: # {frametype}",
"kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\"",
"destination frame (timeline time) number used for the thumbnail # <NAME>, v1.0, 13/10/13",
"populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb",
"self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the",
"change of thumbnail format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value)",
"combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot",
"== self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self,",
"used for the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from",
"clip file used for thumbnail # {dstframe} - The destination frame (timeline time)",
"change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to",
"type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size",
"self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True)",
"for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged)",
"self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft)",
"to handle change of thumbnail format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"]",
"handle change of thumbnail format combo change state value = self._thumbSizeComboBox.currentText() if value",
"to specify a custom frame offset, relative from the first frame.\") thumbFrameTypes =",
"self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail",
"self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index)",
"* from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame =",
"= \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail",
"for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox)",
"QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\")",
"def customOffsetTextChanged(self): # Slot to handle change of thumbnail format combo change state",
"self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False)",
"= QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the thumbnail.\\nCustom allows you",
"determines the size of the thumbnail.\\nLeave as Default to use Hiero's internal thumbnail",
"to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate):",
"class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame =",
"{frametype} - Position where the thumbnail was taken from (first/middle/last/custom) # {srcframe} -",
"frame offset from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox,",
"= (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\") for index, item in",
"a box or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to",
"unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo",
"\"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): #",
"handle change of thumbnail format combo change state value = self._frameTypeComboBox.currentText() if str(value)",
"frame (timeline time) number used for the thumbnail # <NAME>, v1.0, 13/10/13 from",
"self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"]))",
"self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot",
"thumbnail format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self):",
"self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to handle change of thumbnail format",
"thumbnail format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self):",
"number used for the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import *",
"change state value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False)",
"unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle",
"first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch()",
"of the thumbnail.\\nLeave as Default to use Hiero's internal thumbnail size or specify",
"QImage save height # Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox =",
"the size of the thumbnail.\\nLeave as Default to use Hiero's internal thumbnail size",
"Slot to handle change of thumbnail format combo change state value = self._widthBox.text()",
"Slot to handle change of thumbnail format combo change state value = self._thumbSizeComboBox.currentText()",
"widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame",
"thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick",
"if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\":",
"self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif",
"QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the thumbnail.\\nCustom",
"from PySide2.QtGui import * from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class",
"you to specify a custom frame offset, relative from the first frame.\") thumbFrameTypes",
"def frameTypeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo change",
"= unicode(value) def customOffsetTextChanged(self): # Slot to handle change of thumbnail format combo",
"self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to handle change of thumbnail",
"= unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle change of thumbnail format",
"def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot",
"thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft)",
"the frame offset from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"]))",
"thumbnail was taken from (first/middle/last/custom) # {srcframe} - The frame number of the",
"str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def",
"= (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if",
"value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value",
"self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in",
"item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame",
"Thumbnail image export task which can be used via the Export dialog via",
"pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger",
"__init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to",
"width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12)",
"self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9,",
"frameTypeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo change state",
"== \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\":",
"to use Hiero's internal thumbnail size or specify a box or width/height scaling",
"save format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for",
"was taken from (first/middle/last/custom) # {srcframe} - The frame number of the original",
"kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def",
"(\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item",
"value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled",
"self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): #",
"zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12)",
"Processor # To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory.",
"self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height",
"ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame",
"# {srcframe} - The frame number of the original source clip file used",
"self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is",
"= QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first frame of",
"# QImage save height # Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox",
"self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame type layout thumbSizeLayout =",
"value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to",
"the thumbnail.\\nCustom allows you to specify a custom frame offset, relative from the",
"to handle change of thumbnail format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"]",
"widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify",
"== \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to",
"thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item)",
"from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\"",
"layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame type layout",
"as Default to use Hiero's internal thumbnail size or specify a box or",
"self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False)",
"handle change of thumbnail format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] =",
"a custom frame offset, relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame,",
"= \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self):",
"self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True)",
"= (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if",
"str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame type layout thumbSizeLayout",
"state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to handle",
"index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit",
"thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes =",
"hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame =",
"self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as Default to use Hiero's",
"\"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle change",
"self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set",
"str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from",
"value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to handle change",
"for: # {frametype} - Position where the thumbnail was taken from (first/middle/last/custom) #",
"QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as",
"exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame type",
"offset, relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for",
"else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index): # Slot to handle change",
"self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to handle change of thumbnail format",
"= QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as Default to",
"size or specify a box or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To",
"elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value ==",
"dialog via Shot, Clip or Sequence Processor # To install copy the ThumbnailExportTask.py",
"frame offset, relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame)",
"self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the thumbnail.\\nCustom allows",
"self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the thumbnail.\\nCustom allows you to specify",
"change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to",
"Export dialog via Shot, Clip or Sequence Processor # To install copy the",
"# Thumbnail image export task which can be used via the Export dialog",
"from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * import",
"thumbnail.\\nLeave as Default to use Hiero's internal thumbnail size or specify a box",
"- The frame number of the original source clip file used for thumbnail",
"= self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle change",
"first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)),",
"(first/middle/last/custom) # {srcframe} - The frame number of the original source clip file",
"unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo",
"Clip or Sequence Processor # To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to",
"to make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout) layout.addRow(\"Size:\",thumbSizeLayout) layout.addRow(\"File",
"from (first/middle/last/custom) # {srcframe} - The frame number of the original source clip",
"import * from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame",
"is the frame offset from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80);",
"item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage",
"customOffsetTextChanged(self): # Slot to handle change of thumbnail format combo change state value",
"QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as Default to use",
"which can be used via the Export dialog via Shot, Clip or Sequence",
"thumbnail.\\nCustom allows you to specify a custom frame offset, relative from the first",
"ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle change of thumbnail",
"copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist",
"v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import",
"ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\"",
"elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled",
"Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout",
"\"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item ==",
"or specify a box or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\",",
"Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes",
"thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\")",
"# {dstframe} - The destination frame (timeline time) number used for the thumbnail",
"self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged)",
"= self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value ==",
"handle change of thumbnail format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] =",
"the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save",
"(timeline time) number used for the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore",
"unicode(value) def widthTextChanged(self): # Slot to handle change of thumbnail format combo change",
"self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type",
"change of thumbnail format combo change state value = self._thumbSizeComboBox.currentText() if value ==",
"self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox",
"to handle change of thumbnail format combo change state value = self._frameTypeComboBox.currentText() if",
"= unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0)",
"state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to",
"#thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\", \"jpg\",",
"self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame type layout thumbSizeLayout = QHBoxLayout()",
"state value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif",
"to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]):",
"- The destination frame (timeline time) number used for the thumbnail # <NAME>,",
"of thumbnail format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def",
"self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox =",
"= self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to handle change of",
"change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to",
"Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines",
"type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which",
"thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged)",
"UI # Thumbnail image export task which can be used via the Export",
"import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame",
"handle change of thumbnail format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] =",
"pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox",
"of thumbnail format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def",
"str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width",
"format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): #",
"self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set the enabled state",
"self._thumbSizeComboBox.setToolTip(\"This determines the size of the thumbnail.\\nLeave as Default to use Hiero's internal",
"to Width\", \"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if",
"frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() #",
"set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout) layout.addRow(\"Size:\",thumbSizeLayout) layout.addRow(\"File Type:\",self._formatComboBox) hiero.ui.taskUIRegistry.registerTaskUI(ThumbnailExportTask.ThumbnailExportPreset, ThumbnailExportUI)",
"pick the thumbnail.\\nCustom allows you to specify a custom frame offset, relative from",
"self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator())",
"\"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True)",
"\"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item ==",
"import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\"",
"# Keyword tokens exist for: # {frametype} - Position where the thumbnail was",
"format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): #",
"thumbnail # {dstframe} - The destination frame (timeline time) number used for the",
"self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True)",
"QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel =",
"QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the thumbnail.\\nCustom allows you to",
"# Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This",
"which to pick the thumbnail.\\nCustom allows you to specify a custom frame offset,",
"self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9,",
"frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the",
"combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): #",
"thumbnail format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self,",
"zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height",
"change state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text())",
"via the Export dialog via Shot, Clip or Sequence Processor # To install",
"image export task which can be used via the Export dialog via Shot,",
"def thumbSizeComboBoxChanged(self, index): # Slot to handle change of thumbnail format combo change",
"value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True)",
"the Export dialog via Shot, Clip or Sequence Processor # To install copy",
"\"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True)",
"# Trigger to make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout)",
"self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft)",
"= \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self,",
"to handle change of thumbnail format combo change state value = self._thumbSizeComboBox.currentText() if",
"for thumbnail # {dstframe} - The destination frame (timeline time) number used for",
"def formatComboBoxChanged(self): # Slot to handle change of thumbnail format combo change state",
"Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True)",
"change of thumbnail format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value)",
"== str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame type layout",
"of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage",
"self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first frame",
"Width\", \"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item",
"allows you to specify a custom frame offset, relative from the first frame.\")",
"To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword",
"Exporter Task UI # Thumbnail image export task which can be used via",
"exist for: # {frametype} - Position where the thumbnail was taken from (first/middle/last/custom)",
"the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui import",
"thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui import *",
"<NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets",
"def heightTextChanged(self): # Slot to handle change of thumbnail format combo change state",
"- Position where the thumbnail was taken from (first/middle/last/custom) # {srcframe} - The",
"the thumbnail was taken from (first/middle/last/custom) # {srcframe} - The frame number of",
"self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:')",
"self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first frame of the shot/sequence\")",
"width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to",
"frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from",
"Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox = QComboBox() thumbFrameTypes = (\"png\",",
"self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to",
"specify a box or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled",
"Exporter\") def formatComboBoxChanged(self): # Slot to handle change of thumbnail format combo change",
"value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle",
"QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout =",
"Sequence Processor # To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup",
"of thumbnail format combo change state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame:",
"to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False)",
"QComboBox() thumbFrameTypes = (\"png\", \"jpg\", \"tiff\", \"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes):",
"= QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40) self._widthBox.setText(str(self._preset.properties()[\"width\"])) self._widthBox.textChanged.connect(self.widthTextChanged) thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel",
"\"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\")",
"format combo change state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"]",
"QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40)",
"ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: # {frametype} -",
"in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:')",
"self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self, widget, exportTemplate): layout = QFormLayout()",
"from which to pick the thumbnail.\\nCustom allows you to specify a custom frame",
"thumbnail format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self):",
"self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True) self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value ==",
"13/10/13 from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import *",
"via Shot, Clip or Sequence Processor # To install copy the ThumbnailExportTask.py and",
"thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged)",
"internal thumbnail size or specify a box or width/height scaling in pixels.\") thumbSizeTypes",
"or Sequence Processor # To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your",
"# Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the",
"the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for:",
"Position where the thumbnail was taken from (first/middle/last/custom) # {srcframe} - The frame",
"directory. # Keyword tokens exist for: # {frametype} - Position where the thumbnail",
"self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item ==",
"if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox =",
"<HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: # {frametype} - Position where the",
"thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox = QComboBox()",
"item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item) if item == str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel =",
"\"Scaled to Width\", \"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes): self._thumbSizeComboBox.addItem(item)",
"QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator()) self._widthBox.setMaximumWidth(40)",
"value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def",
"used for thumbnail # {dstframe} - The destination frame (timeline time) number used",
"handle change of thumbnail format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] =",
"shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format",
"(\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)),",
"thumbSizeLayout.addWidget(self._widthBox,Qt.AlignLeft) self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\")",
"heightTextChanged(self): # Slot to handle change of thumbnail format combo change state value",
"kFirstFrame = \"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def",
"frame from which to pick the thumbnail.\\nCustom allows you to specify a custom",
"scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\")",
"if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame",
"= QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout",
"offset from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft)",
"Task UI # Thumbnail image export task which can be used via the",
"preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle",
"\"bmp\") for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index)",
"= self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"]",
"PySide2.QtGui import * from PySide2.QtWidgets import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase):",
"zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False)",
"of thumbnail format combo change state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def",
"Box\", \"Scaled to Width\", \"Scaled to Height\") for index, item in zip(range(0,len(thumbSizeTypes)), thumbSizeTypes):",
"combo change state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] =",
"source clip file used for thumbnail # {dstframe} - The destination frame (timeline",
"number of the original source clip file used for thumbnail # {dstframe} -",
"import * import hiero.ui import ThumbnailExportTask class ThumbnailExportUI(hiero.ui.TaskUIBase): kFirstFrame = \"First\" kMiddleFrame =",
"in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\") for",
"PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * import hiero.ui",
"formatComboBoxChanged(self): # Slot to handle change of thumbnail format combo change state value",
"save height # Thumb frame type layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox()",
"self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]):",
"self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value",
"layout thumbSizeLayout = QHBoxLayout() self._thumbSizeComboBox = QComboBox() self._thumbSizeComboBox.setMaximumWidth(115) self._thumbSizeComboBox.setToolTip(\"This determines the size of",
"= QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator())",
"self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make",
"size of the thumbnail.\\nLeave as Default to use Hiero's internal thumbnail size or",
"\"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle change of thumbnail format combo",
"# <NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui import * from",
"for the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import * from PySide2.QtGui",
"state value = self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to handle",
"Keyword tokens exist for: # {frametype} - Position where the thumbnail was taken",
"self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox =",
"self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] = unicode(value) def thumbSizeComboBoxChanged(self, index):",
"== \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"] = unicode(value) def populateUI(self,",
"item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height # Thumb frame type",
"Slot to handle change of thumbnail format combo change state value = self._formatComboBox.currentText()",
"QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0)",
"Shot, Clip or Sequence Processor # To install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py",
"def populateUI(self, widget, exportTemplate): layout = QFormLayout() layout.setContentsMargins(9, 0, 9, 0) widget.setLayout(layout) #",
"self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): # Slot to handle change of thumbnail",
"preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle change of thumbnail format",
"= QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame from which to pick the",
"The destination frame (timeline time) number used for the thumbnail # <NAME>, v1.0,",
"self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle change of",
"{srcframe} - The frame number of the original source clip file used for",
"# Slot to handle change of thumbnail format combo change state value =",
"thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) # Trigger to make it set the enabled",
"your <HIERO_PATH>/Python/Startup directory. # Keyword tokens exist for: # {frametype} - Position where",
"== \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"To Box\": self._widthBox.setEnabled(True) self._heightBox.setEnabled(True)",
"\"First\" kMiddleFrame = \"Middle\" kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset):",
"index): # Slot to handle change of thumbnail format combo change state value",
"Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox = QComboBox() self._frameTypeComboBox.setToolTip(\"Specify the frame",
"= unicode(value) def heightTextChanged(self): # Slot to handle change of thumbnail format combo",
"thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item)",
"unicode(value) def heightTextChanged(self): # Slot to handle change of thumbnail format combo change",
"the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in",
"used via the Export dialog via Shot, Clip or Sequence Processor # To",
"format combo change state value = self._thumbSizeComboBox.currentText() if value == \"Default\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False)",
"kLastFrame = \"Last\" kCustomFrame = \"Custom\" def __init__(self, preset): \"\"\"Initialize\"\"\" hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset,",
"in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged) self.frameTypeComboBoxChanged(0) #",
"= QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged)",
"self.frameTypeComboBoxChanged(0) # Trigger to make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame",
"def widthTextChanged(self): # Slot to handle change of thumbnail format combo change state",
"0, 9, 0) widget.setLayout(layout) # Thumb frame type layout thumbFrameLayout = QHBoxLayout() self._frameTypeComboBox",
"thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This",
"custom frame offset, relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame,",
"or width/height scaling in pixels.\") thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled",
"self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True) self._preset.properties()[\"customFrameOffset\"] = unicode(self._customFrameLineEdit.text()) else: self._customFrameLineEdit.setEnabled(False) self._preset.properties()[\"frameType\"] =",
"thumbSizeTypes = (\"Default\",\"To Box\", \"Scaled to Width\", \"Scaled to Height\") for index, item",
"Thumbnail Exporter Task UI # Thumbnail image export task which can be used",
"thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save height #",
"format combo change state value = self._formatComboBox.currentText() self._preset.properties()[\"format\"] = unicode(value) def customOffsetTextChanged(self): #",
"format combo change state value = self._heightBox.text() self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index):",
"from the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit,",
"= self._widthBox.text() self._preset.properties()[\"width\"] = unicode(value) def heightTextChanged(self): # Slot to handle change of",
"self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit = QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first",
"the thumbnail.\\nLeave as Default to use Hiero's internal thumbnail size or specify a",
"thumbnail format combo change state value = self._frameTypeComboBox.currentText() if str(value) == self.kCustomFrame: self._customFrameLineEdit.setEnabled(True)",
"= QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in pixels\") self._widthBox.setEnabled(False) self._widthBox.setValidator(QIntValidator())",
"hiero.ui.TaskUIBase.__init__(self, ThumbnailExportTask.ThumbnailExportTask, preset, \"Thumbnail Exporter\") def formatComboBoxChanged(self): # Slot to handle change of",
"Default to use Hiero's internal thumbnail size or specify a box or width/height",
"it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout) layout.addRow(\"Size:\",thumbSizeLayout) layout.addRow(\"File Type:\",self._formatComboBox) hiero.ui.taskUIRegistry.registerTaskUI(ThumbnailExportTask.ThumbnailExportPreset,",
"self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False) self._heightBox.setEnabled(True) self._hLabel.setEnabled(True) self._preset.properties()[\"thumbSize\"]",
"self._hLabel = QLabel('h:') self._hLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._hLabel,Qt.AlignLeft) self._heightBox = QLineEdit() self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False)",
"the original source clip file used for thumbnail # {dstframe} - The destination",
"QLineEdit() self._customFrameLineEdit.setEnabled(False) self._customFrameLineEdit.setToolTip(\"This is the frame offset from the first frame of the",
"item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80) self._customFrameLineEdit =",
"self._wLabel.setEnabled(True) self._hLabel.setEnabled(True) elif value == \"Scaled to Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif",
"self._heightBox.setToolTip(\"Thumbnail height in pixels\") self._heightBox.setEnabled(False) self._heightBox.setValidator(QIntValidator()) self._heightBox.setMaximumWidth(40) self._heightBox.setText(str(self._preset.properties()[\"height\"])) self._heightBox.textChanged.connect(self.heightTextChanged) thumbSizeLayout.addWidget(self._heightBox,Qt.AlignLeft) self._thumbSizeComboBox.currentIndexChanged.connect(self.thumbSizeComboBoxChanged) self.thumbSizeComboBoxChanged(0) self._frameTypeComboBox.currentIndexChanged.connect(self.frameTypeComboBoxChanged)",
"self._preset.properties()[\"height\"] = unicode(value) def frameTypeComboBoxChanged(self, index): # Slot to handle change of thumbnail",
"The frame number of the original source clip file used for thumbnail #",
"self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to handle change of thumbnail format",
"time) number used for the thumbnail # <NAME>, v1.0, 13/10/13 from PySide2.QtCore import",
"export task which can be used via the Export dialog via Shot, Clip",
"for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._frameTypeComboBox.addItem(item) if item == str(self._preset.properties()[\"frameType\"]): self._frameTypeComboBox.setCurrentIndex(index) self._frameTypeComboBox.setMaximumWidth(80)",
"specify a custom frame offset, relative from the first frame.\") thumbFrameTypes = (self.kFirstFrame,",
"make it set the enabled state correctly self._customFrameLineEdit.textChanged.connect(self.customOffsetTextChanged) layout.addRow(\"Frame Type:\",thumbFrameLayout) layout.addRow(\"Size:\",thumbSizeLayout) layout.addRow(\"File Type:\",self._formatComboBox)",
"of thumbnail format combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def",
"frame.\") thumbFrameTypes = (self.kFirstFrame, self.kMiddleFrame, self.kLastFrame, self.kCustomFrame) for index, item in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes):",
"= self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to handle change of",
"== str(self._preset.properties()[\"thumbSize\"]): self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail",
"self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft) #thumbFrameLayout.addStretch() # QImage save format type self._formatComboBox",
"in zip(range(0,len(thumbFrameTypes)), thumbFrameTypes): self._formatComboBox.addItem(item) if item == str(self._preset.properties()[\"format\"]): self._formatComboBox.setCurrentIndex(index) self._formatComboBox.currentIndexChanged.connect(self.formatComboBoxChanged) # QImage save",
"{dstframe} - The destination frame (timeline time) number used for the thumbnail #",
"import * from PySide2.QtGui import * from PySide2.QtWidgets import * import hiero.ui import",
"Width\": self._widthBox.setEnabled(True) self._wLabel.setEnabled(True) self._heightBox.setEnabled(False) self._hLabel.setEnabled(False) elif value == \"Scaled to Height\": self._widthBox.setEnabled(False) self._wLabel.setEnabled(False)",
"the first frame of the shot/sequence\") self._customFrameLineEdit.setValidator(QIntValidator()) self._customFrameLineEdit.setMaximumWidth(80); self._customFrameLineEdit.setText(str(self._preset.properties()[\"customFrameOffset\"])) thumbFrameLayout.addWidget(self._frameTypeComboBox, Qt.AlignLeft) thumbFrameLayout.addWidget(self._customFrameLineEdit, Qt.AlignLeft)",
"combo change state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot",
"state value = self._customFrameLineEdit.text() self._preset.properties()[\"customFrameOffset\"] = unicode(value) def widthTextChanged(self): # Slot to handle",
"= unicode(value) def widthTextChanged(self): # Slot to handle change of thumbnail format combo",
"install copy the ThumbnailExportTask.py and ThumbnailExportTaskUI.py to your <HIERO_PATH>/Python/Startup directory. # Keyword tokens",
"self._thumbSizeComboBox.setCurrentIndex(index) thumbSizeLayout.addWidget(self._thumbSizeComboBox) self._wLabel = QLabel('w:') self._wLabel.setFixedWidth(12) thumbSizeLayout.addWidget(self._wLabel,Qt.AlignLeft) self._widthBox = QLineEdit() self._widthBox.setToolTip(\"Thumbnail width in"
] |
[
"KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl', 'wb'), protocol=2) print('weights_matrix is created')",
"in f: line = l.decode().split() word = line[0] words.append(word) word2idx[word] = idx idx",
"{w: vectors[word2idx[w]] for w in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300))",
"import json from scipy import misc import bcolz words = [] idx =",
"1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl', 'wb'), protocol=2) print('weights_matrix",
"generates GloVe embeddings ''' # coding: utf-8 import pickle from preprocess import Vocabulary",
"and generates GloVe embeddings ''' # coding: utf-8 import pickle from preprocess import",
"[] idx = 0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with",
"open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f: line = l.decode().split() word =",
"words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove =",
"= bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f:",
"embeddings ''' # coding: utf-8 import pickle from preprocess import Vocabulary import numpy",
"following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings ''' #",
"np import json from scipy import misc import bcolz words = [] idx",
"open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words",
"except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl', 'wb'), protocol=2) print('weights_matrix is",
"as np import json from scipy import misc import bcolz words = []",
"'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]] for",
"glove = {w: vectors[word2idx[w]] for w in words} matrix_len = len(vocab) weights_matrix =",
"= len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for i, word in",
"= bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with",
"loaded...') glove = {w: vectors[word2idx[w]] for w in words} matrix_len = len(vocab) weights_matrix",
"by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe",
"for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1 except",
"following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings",
"f: for l in f: line = l.decode().split() word = line[0] words.append(word) word2idx[word]",
"line[0] words.append(word) word2idx[word] = idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors",
"pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]]",
"= idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)),",
"+= 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush()",
"300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb')",
"bcolz words = [] idx = 0 word2idx = {} vectors = bcolz.carray(np.zeros(1),",
"was written by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and",
"processes and generates GloVe embeddings ''' # coding: utf-8 import pickle from preprocess",
"as f: vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl',",
"words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for i,",
"print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb'))",
"preprocess import Vocabulary import numpy as np import json from scipy import misc",
"enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6,",
"pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]] for w in words}",
"vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx",
"= pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx =",
"= np.zeros((matrix_len, 300)) words_found = 0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i]",
"word2idx[word] = idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000,",
"mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f:",
"written by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates",
"pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl',",
"= 0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb')",
"= pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w:",
"vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove",
"words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl', 'wb'),",
"script processes and generates GloVe embeddings ''' # coding: utf-8 import pickle from",
"weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for i, word in enumerate(vocab.idx2word): try:",
"This code was written by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script",
"import pickle from preprocess import Vocabulary import numpy as np import json from",
"i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1 except KeyError:",
"= bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...')",
"scipy import misc import bcolz words = [] idx = 0 word2idx =",
"utf-8 import pickle from preprocess import Vocabulary import numpy as np import json",
"import bcolz words = [] idx = 0 word2idx = {} vectors =",
"for w in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found =",
"= 0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found +=",
"with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f: line = l.decode().split() word",
"'wb')) with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading vocab...') vectors =",
"words = [] idx = 0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat',",
"misc import bcolz words = [] idx = 0 word2idx = {} vectors",
"https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings ''' # coding: utf-8 import",
"f: line = l.decode().split() word = line[0] words.append(word) word2idx[word] = idx idx +=",
"w in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0",
"np.zeros((matrix_len, 300)) words_found = 0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] =",
"code was written by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes",
"import numpy as np import json from scipy import misc import bcolz words",
"This script processes and generates GloVe embeddings ''' # coding: utf-8 import pickle",
"rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as",
"words.append(word) word2idx[word] = idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors =",
"idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat',",
"l in f: line = l.decode().split() word = line[0] words.append(word) word2idx[word] = idx",
"'rb') as f: vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words =",
"f: vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb'))",
"with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading vocab...') vectors = bcolz.open('glove.6B/6B.300.dat')[:]",
"word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]] for w",
"1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words,",
"import Vocabulary import numpy as np import json from scipy import misc import",
"GloVe embeddings ''' # coding: utf-8 import pickle from preprocess import Vocabulary import",
"Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings ''' # coding: utf-8",
"+= 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl', 'wb'), protocol=2)",
"rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f: line =",
"idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w')",
"pickle from preprocess import Vocabulary import numpy as np import json from scipy",
"json from scipy import misc import bcolz words = [] idx = 0",
"300)) words_found = 0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word]",
"= l.decode().split() word = line[0] words.append(word) word2idx[word] = idx idx += 1 vect",
"the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings '''",
"vectors[word2idx[w]] for w in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found",
"bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove",
"from scipy import misc import bcolz words = [] idx = 0 word2idx",
"as f: for l in f: line = l.decode().split() word = line[0] words.append(word)",
"word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1 except KeyError: weights_matrix[i]",
"= np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb'))",
"= {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for",
"word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f:",
"len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for i, word in enumerate(vocab.idx2word):",
"line = l.decode().split() word = line[0] words.append(word) word2idx[word] = idx idx += 1",
"in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1 except KeyError: weights_matrix[i] =",
"coding: utf-8 import pickle from preprocess import Vocabulary import numpy as np import",
"= glove[word] words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix,",
"bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl',",
"matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for i, word",
"is loaded...') glove = {w: vectors[word2idx[w]] for w in words} matrix_len = len(vocab)",
"glove[word] words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, )) pickle.dump(weights_matrix, open('glove.6B/glove_words.pkl',",
"= [] idx = 0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w')",
"vect = np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl',",
"vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl',",
"'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]] for w in words} matrix_len",
"import misc import bcolz words = [] idx = 0 word2idx = {}",
"= pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is loaded...') glove = {w: vectors[word2idx[w]] for w in",
"np.array(line[1:]).astype(np.float) vectors.append(vect) vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx,",
"in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len, 300)) words_found = 0 for",
"pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab =",
"0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found += 1",
"open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f)",
"'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading",
"open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading vocab...') vectors",
"''' This code was written by following the following tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This",
"mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f: line = l.decode().split()",
"word = line[0] words.append(word) word2idx[word] = idx idx += 1 vect = np.array(line[1:]).astype(np.float)",
"words_found = 0 for i, word in enumerate(vocab.idx2word): try: weights_matrix[i] = glove[word] words_found",
"= line[0] words.append(word) word2idx[word] = idx idx += 1 vect = np.array(line[1:]).astype(np.float) vectors.append(vect)",
"tutorial: Link: https://medium.com/@martinpella/how-to-use-pre-trained-word-embeddings-in-pytorch-71ca59249f76 This script processes and generates GloVe embeddings ''' # coding:",
"pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab = pickle.load(f) print('Loading vocab...')",
"''' # coding: utf-8 import pickle from preprocess import Vocabulary import numpy as",
"from preprocess import Vocabulary import numpy as np import json from scipy import",
"'rb') as f: for l in f: line = l.decode().split() word = line[0]",
"{} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l",
"for l in f: line = l.decode().split() word = line[0] words.append(word) word2idx[word] =",
"l.decode().split() word = line[0] words.append(word) word2idx[word] = idx idx += 1 vect =",
"vectors = bcolz.carray(vectors[1:].reshape((400000, 300)), rootdir='glove.6B/6B.300.dat', mode='w') vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb'))",
"# coding: utf-8 import pickle from preprocess import Vocabulary import numpy as np",
"vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in",
"Vocabulary import numpy as np import json from scipy import misc import bcolz",
"try: weights_matrix[i] = glove[word] words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300,",
"vectors.flush() pickle.dump(words, open('glove.6B/6B.300_words.pkl', 'wb')) pickle.dump(word2idx, open('glove.6B/6B.300_idx.pkl', 'wb')) with open('data/vocab.pkl', 'rb') as f: vocab",
"print('glove is loaded...') glove = {w: vectors[word2idx[w]] for w in words} matrix_len =",
"bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as f: for l in f: line",
"weights_matrix[i] = glove[word] words_found += 1 except KeyError: weights_matrix[i] = np.random.normal(scale=0.6, size=(300, ))",
"= {w: vectors[word2idx[w]] for w in words} matrix_len = len(vocab) weights_matrix = np.zeros((matrix_len,",
"0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt', 'rb') as",
"idx = 0 word2idx = {} vectors = bcolz.carray(np.zeros(1), rootdir='glove.6B/6B.300.dat', mode='w') with open('glove.6B/glove.6B.300d.txt',",
"numpy as np import json from scipy import misc import bcolz words =",
"vectors = bcolz.open('glove.6B/6B.300.dat')[:] words = pickle.load(open('glove.6B/6B.300_words.pkl', 'rb')) word2idx = pickle.load(open('glove.6B/6B.300_idx.pkl', 'rb')) print('glove is"
] |
[
"rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}]",
"A list of parameter combinations created by taking the cartesian product of all",
"self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level",
"ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params(): if",
"passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic as ps",
"to be constant (its value will be the same in all combinations). Returns:",
"-> int: \"\"\"Use this function to generate random numbers seeded by the experiment",
"concurrent processes to use for running the experiments. Defaults to 1. \"\"\" pool",
"self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ =",
"optional): The number of bits to use to represent the generated number. Defaults",
"to \" \"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read",
"_wait(self): sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs =",
"def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params",
"if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK",
"the current process is a subprocess. \"\"\" return self.params[\"subprocess\"] is not None def",
"class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes =",
"key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent",
"seeded by the experiment parameter ``random_seed``. Expected use is to seed your own",
"from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to",
"class StandardPlugin: def __init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment,",
"as the current process. If this is not what you want, you should",
"See :func:`pystematic.param_matrix` for a convenient way of generating such a list. max_num_processes (int,",
"finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes: if proc.sentinel in",
"eariler run. When this option is \" \"set from the command line, any",
"import multiprocessing.connection import pathlib import random import string import pystematic import pystematic.core as",
"taking the cartesian product of all values in the input. \"\"\" # Make",
"= self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters",
"params. At most :obj:`max_num_processes` concurrent processes will be used. This call will block",
"The output of this function can be passed directly to :func:`pystematic.run_parameter_sweep`. For example:",
"\"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ =",
"proc.kill() except Exception: pass for proc in procs: try: proc.join() except Exception: pass",
"range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0:",
"experiment. See :func:`pystematic.param_matrix` for a convenient way of generating such a list. max_num_processes",
"def local_rank(self): \"\"\"Returns the local rank of the current process. The master process",
"\"This parameter is set automatically by the framework, and should not \" \"be",
"value will be the same in all combinations). Returns: list of dicts: A",
"to execute the main function of the currently running experiment, and have the",
"+ escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or",
"1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true",
"starting at 1. Returns: int: The local rank of the current process. \"\"\"",
"Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\")",
"have rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a",
"of parameter values appear once in the list. The output of this function",
"function of the currently running experiment, and have the same output directory and",
"A random number seeded by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def",
"\"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"])",
"'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False) if no_style: theme =",
"from rich.markup import escape from rich.theme import Theme from .. import parametric from",
"name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file)",
"is \" \"set from the command line, any other options supplied after this",
"further subprocesses.\") subprocess_params = {name: value for name, value in self.params.items()} for name,",
"and have the same output directory and parameters as the current process. Args:",
"param_values[key] = [value] keys = param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()):",
"\"be used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context",
"return experiment def extend_api(self, api_object): for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object,",
"= multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def _wait(self): sentinels = [proc.sentinel",
"process will always have rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess` will",
"parameter. If a value is not a list or tuple, it is assumed",
"Exception: pass for proc in procs: try: proc.join() except Exception: pass def new_seed(self,",
"assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir,",
"if this process is a subprocess. I.e. it has been launched by a",
"assigned a new local rank from an incrementing integer counter starting at 1.",
"until all experiments have been run. Args: experiment (Experiment): The experiment to run.",
"by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process:",
"local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self,",
"'name': 'green' }, inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme)",
"parameter dictionaries such that all combinations of parameter values appear once in the",
"try for that parameter. If a value is not a list or tuple,",
"\" \"This parameter is set automatically by the framework, and should not \"",
"at 1. Returns: int: The local rank of the current process. \"\"\" return",
"else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True,",
"for running the experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params)",
"force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False)",
"self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments",
"same random seed as the current process. If this is not what you",
"current process. If this is not what you want, you should pass a",
"parameter and a list of all values that you want to try for",
"subprocess. The subprocess will be instructed to execute the main function of the",
"current process is a subprocess. \"\"\" return self.params[\"subprocess\"] is not None def local_rank(self):",
"in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank ==",
"experiment. .. warning:: The subprocess will be initialized with the same random seed",
"I.e. it has been launched by a call to :func:`launch_subprocess` in a parent",
"if not isinstance(value, (list, tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations =",
"is not None: logger.error(f\"Experiment ended at {end_time} with an error: {error}\", exc_info=error) else:",
"), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local rank for this",
"random number seeded by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self,",
"function to generate random numbers seeded by the experiment parameter ``random_seed``. Expected use",
"subprocess cannot launch further subprocesses.\") subprocess_params = {name: value for name, value in",
"not exist: '{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\")",
"super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank':",
"subprocess. \"\"\" return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the local rank",
"true if this process is a subprocess. I.e. it has been launched by",
"be passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic as",
"pass for proc in procs: try: proc.join() except Exception: pass def new_seed(self, nbits=32)",
"name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars =",
"while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc) while len(self._live_processes) > 0:",
"num_processes self._live_processes = [] def _wait(self): sentinels = [proc.sentinel for proc in self._live_processes]",
"0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler],",
"process is a subprocess. I.e. it has been launched by a call to",
"in a parent process. Returns: bool: Whether or not the current process is",
":func:`pystematic.launch_subprocess` will be assigned a new local rank from an incrementing integer counter",
"directory and parameters as the current process. Args: **additional_params: Any additional parameters that",
"Console from rich.markup import escape from rich.theme import Theme from .. import parametric",
"return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will",
"Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\")",
"concurrent processes will be used. This call will block until all experiments have",
"1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\")",
"to seed the master random number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter(",
"\" \"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off.",
"%H:%M:%S') if error is not None: logger.error(f\"Experiment ended at {end_time} with an error:",
"The subprocess will be initialized with the same random seed as the current",
"it is assumed to be constant (its value will be the same in",
"the one \" \"dumped in the output dir from an eariler run. When",
"params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ =",
"+ string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return",
"number of keywork arguments, where each argument is a parameter and a list",
"'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False) if",
"to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time =",
"logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params,",
"for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params:",
"= wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random =",
"gives the local rank for this process. \" \"This parameter is set automatically",
"rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a new",
"params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"])",
"and a list of all values that you want to try for that",
"for key, value in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] = [value]",
"for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir,",
"after this one \" \"will override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(),",
"proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params):",
"%H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank = \"[rank]\" +",
"parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot",
"def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # +",
"ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value",
"core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master random number generator",
"**param_values: A mapping from parameter name to a list of values to try",
"suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment",
"different params. At most :obj:`max_num_processes` concurrent processes will be used. This call will",
"to use to represent the generated number. Defaults to 32. Returns: int: A",
"the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A",
"the current experiment. .. warning:: The subprocess will be initialized with the same",
"inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\")",
"the current process. The master process will always have rank 0, and every",
"procs: try: proc.kill() except Exception: pass for proc in procs: try: proc.join() except",
"= experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\"",
"of the experiment. See :func:`pystematic.param_matrix` for a convenient way of generating such a",
"values are lists for key, value in param_values.items(): if not isinstance(value, (list, tuple)):",
"\"will override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\",",
"with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None:",
"for that parameter. If a value is not a list or tuple, it",
"is not None: if not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops",
"multiprocessing import multiprocessing.connection import pathlib import random import string import pystematic import pystematic.core",
"for proc in procs: try: proc.join() except Exception: pass def new_seed(self, nbits=32) ->",
"for a convenient way of generating such a list. max_num_processes (int, optional): The",
"value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"]",
"Whether or not the current process is a subprocess. \"\"\" return self.params[\"subprocess\"] is",
"It takes an arbitrary number of keywork arguments, where each argument is a",
"__init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def _wait(self):",
"should not \" \"be used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def",
"number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to",
"a subprocess. I.e. it has been launched by a call to :func:`launch_subprocess` in",
"assert param_list == [ { \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1,",
"random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment,",
"else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir,",
"manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn')",
"function can be passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import",
"instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value:",
"{ \"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values: A mapping from parameter",
"= _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level,",
"result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file",
"log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__",
"current process. Args: **additional_params: Any additional parameters that should be passed to the",
"run. Args: experiment (Experiment): The experiment to run. list_of_params (list of dict): A",
"running parameter sweeps. It takes an arbitrary number of keywork arguments, where each",
"list of all values that you want to try for that parameter. It",
"), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that this process is a",
"> 0 or pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") +",
"= StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\")",
"a list of values to try for that parameter. If a value is",
"'.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment",
"num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def _wait(self): sentinels",
"ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list == [ { \"int_param\": 1,",
"multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc)",
"to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns",
"to try for that parameter. It then builds a list of parameter dictionaries",
"raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params = {name: value for name,",
"been run. Args: experiment (Experiment): The experiment to run. list_of_params (list of dict):",
"every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a new local rank from",
"not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = [] for param",
"name, value in self.params.items()} for name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter",
"(list of dict): A list of parameter dictionaries. Each corresponding to one run",
"32), help=\"The value to seed the master random number generator with.\", type=int, default_help=\"<randomly",
"int: \"\"\"Use this function to generate random numbers seeded by the experiment parameter",
"used. This call will block until all experiments have been run. Args: experiment",
"or not the current process is a subprocess. \"\"\" return self.params[\"subprocess\"] is not",
"+= 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{'",
"close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None)",
"generating such a list. max_num_processes (int, optional): The maximum number of concurrent processes",
"list of dicts: A list of parameter combinations created by taking the cartesian",
"incrementing integer counter starting at 1. Returns: int: The local rank of the",
"from the current experiment. .. warning:: The subprocess will be initialized with the",
"an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children()",
"ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if this process is",
"param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list == [ {",
"file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\"",
"all combinations). Returns: list of dicts: A list of parameter combinations created by",
"DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a",
"by taking the cartesian product of all values in the input. \"\"\" #",
"subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a new local rank from an",
"params_from_file = yaml.load(f) for key, value in params_from_file.items(): if key not in blacklisted_config_ops:",
"type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local",
"cannot launch further subprocesses.\") subprocess_params = {name: value for name, value in self.params.items()}",
"then builds a list of parameter dictionaries such that all combinations of parameter",
"as the one \" \"dumped in the output dir from an eariler run.",
"a new seed to this function in the ``random_seed`` parameter. E.g.: .. code-block::",
"param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class",
"value, result_dict) if value is not None: if not value.exists(): raise ValueError(f\"File does",
"most :obj:`max_num_processes` concurrent processes will be used. This call will block until all",
"f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None:",
"such as the one \" \"dumped in the output dir from an eariler",
"__init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow',",
"multiprocessing.connection import pathlib import random import string import pystematic import pystematic.core as core",
"that parameter. It then builds a list of parameter dictionaries such that all",
"with a set of different params. At most :obj:`max_num_processes` concurrent processes will be",
"nbits (int, optional): The number of bits to use to represent the generated",
"= wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__",
"log_level = \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0",
"for this process. \" \"This parameter is set automatically by the framework, and",
"self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while len(self._live_processes) >= self._num_processes:",
"itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict:",
"in the list. The output of this function can be passed directly to",
"if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')",
"= datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment ended at {end_time} with",
"for name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] =",
"return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme =",
"= datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars)",
"self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level",
"\"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank}",
"import wrapt from rich.console import Console from rich.markup import escape from rich.theme import",
"options supplied after this one \" \"will override the ones loaded from the",
"ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The",
"Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self,",
"name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master random number generator with.\",",
"of all values that you want to try for that parameter. It then",
"of this function can be passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block::",
"should be passed to the subprocess. Params given here takes precedence over the",
":func:`pystematic.param_matrix` for a convenient way of generating such a list. max_num_processes (int, optional):",
"error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment ended at",
"allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master random",
"pass a new seed to this function in the ``random_seed`` parameter. E.g.: ..",
"\"dumped in the output dir from an eariler run. When this option is",
"processes will be used. This call will block until all experiments have been",
"pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\")",
"has been launched by a call to :func:`launch_subprocess` in a parent process. Returns:",
"-> None: \"\"\"Runs an experiment multiple times with a set of different params.",
"function in the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess():",
"not None: logger.error(f\"Experiment ended at {end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment",
"function can be used to build parameter combinations to use when running parameter",
"in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for",
"> 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level,",
"and should not \" \"be used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue:",
"= value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess",
"a call to :func:`launch_subprocess` in a parent process. Returns: bool: Whether or not",
"an eariler run. When this option is \" \"set from the command line,",
"] Args: **param_values: A mapping from parameter name to a list of values",
"generators. Args: nbits (int, optional): The number of bits to use to represent",
"is a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter(",
"str_param=[\"hello\", \"world\"] ) assert param_list == [ { \"int_param\": 1, \"str_param\": \"hello\" },",
"as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error",
"'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False) if no_style:",
"to try for that parameter. If a value is not a list or",
"arbitrary number of keywork arguments, where each argument is a parameter and a",
"in self.params.items()} for name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1",
"not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the",
"parametric from . import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def",
"= f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str",
"= None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__",
"try: proc.kill() except Exception: pass for proc in procs: try: proc.join() except Exception:",
"\"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0",
"default=False, help=\"Sets debug flag on/off. Configures the python logging mechanism to \" \"print",
"experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix",
"**additional_params: Any additional parameters that should be passed to the subprocess. Params given",
"parameters from a yaml file, such as the one \" \"dumped in the",
"Theme from .. import parametric from . import yaml_wrapper as yaml logger =",
"Any additional parameters that should be passed to the subprocess. Params given here",
"def param_matrix(self, **param_values): \"\"\"This function can be used to build parameter combinations to",
"as f: params_from_file = yaml.load(f) for key, value in params_from_file.items(): if key not",
"a parameter and a list of all values that you want to try",
"exist: '{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and",
"or tuple, it is assumed to be constant (its value will be the",
"hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local rank for",
"logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None: self.api_object = StandardApi()",
"in all combinations). Returns: list of dicts: A list of parameter combinations created",
"\"set from the command line, any other options supplied after this one \"",
"proc.join() except Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use this function to",
"return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the local rank of the",
"for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in",
"params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\"",
"\"\"\" # Make sure all values are lists for key, value in param_values.items():",
"seeded by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) ->",
"running experiment, and have the same output directory and parameters as the current",
"by the experiment parameter ``random_seed``. Expected use is to seed your own random",
"block until all experiments have been run. Args: experiment (Experiment): The experiment to",
"that parameter. If a value is not a list or tuple, it is",
"is a parameter and a list of all values that you want to",
"directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return",
"= escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S')",
"a list of all values that you want to try for that parameter.",
"pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank}",
"Make sure all values are lists for key, value in param_values.items(): if not",
"-> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def",
"{ \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" }, {",
"dir from an eariler run. When this option is \" \"set from the",
"wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ =",
"1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2,",
"file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time",
"completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in",
"as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None: self.api_object",
"arguments, where each argument is a parameter and a list of all values",
"_get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def",
"The master process will always have rank 0, and every subprocess launched with",
"for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if",
"result_dict: dict): super().on_value(param, value, result_dict) if value is not None: if not value.exists():",
"one run of the experiment. See :func:`pystematic.param_matrix` for a convenient way of generating",
"of parameter dictionaries such that all combinations of parameter values appear once in",
"string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory =",
"name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase #",
"'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False)",
"of the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can",
"functools import itertools import logging import multiprocessing import multiprocessing.connection import pathlib import random",
"experiment to run. list_of_params (list of dict): A list of parameter dictionaries. Each",
"process. \" \"This parameter is set automatically by the framework, and should not",
"suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment",
"raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params():",
"for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\")",
"logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self,",
"(int, optional): The number of bits to use to represent the generated number.",
"f: params_from_file = yaml.load(f) for key, value in params_from_file.items(): if key not in",
"escape from rich.theme import Theme from .. import parametric from . import yaml_wrapper",
"maximum number of concurrent processes to use for running the experiments. Defaults to",
"[value] keys = param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance)))",
"is_subprocess(self) -> bool: \"\"\"Returns true if this process is a subprocess. I.e. it",
"this function in the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if",
"one \" \"dumped in the output dir from an eariler run. When this",
"list_of_params): for params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params)",
"def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait()",
"= [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs in. Will",
"value to seed the master random number generator with.\", type=int, default_help=\"<randomly generated>\" ),",
"in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc) while len(self._live_processes)",
"{pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else:",
"counter starting at 1. Returns: int: The local rank of the current process.",
"= [] for proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc",
"no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red',",
"be initialized with the same random seed as the current process. If this",
"For example: .. code-block:: python import pystematic as ps param_list = ps.param_matrix( int_param=[1,",
"used to build parameter combinations to use when running parameter sweeps. It takes",
"f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str =",
"{level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if",
"multiple times with a set of different params. At most :obj:`max_num_processes` concurrent processes",
"corresponding to one run of the experiment. See :func:`pystematic.param_matrix` for a convenient way",
"def is_subprocess(self) -> bool: \"\"\"Returns true if this process is a subprocess. I.e.",
"in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time",
"else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in procs:",
"0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level",
"process. Args: **additional_params: Any additional parameters that should be passed to the subprocess.",
"pystematic import pystematic.core as core import wrapt from rich.console import Console from rich.markup",
"process. Returns: bool: Whether or not the current process is a subprocess. \"\"\"",
"list or tuple, it is assumed to be constant (its value will be",
"in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def",
"self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file",
"be instructed to execute the main function of the currently running experiment, and",
"ended at {end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\")",
"== 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__()",
"wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__",
"{msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def",
"this is not what you want, you should pass a new seed to",
"int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0",
"completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while len(self._live_processes) >=",
"app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object())",
"max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times with a set of different",
"lists for key, value in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] =",
"allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes",
"'rank': 'green', 'name': 'green' }, inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output",
"this function to generate random numbers seeded by the experiment parameter ``random_seed``. Expected",
"default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master random number generator with.\", type=int,",
"Args: **param_values: A mapping from parameter name to a list of values to",
"directory to store all run-logs in. Will be created if it \" \"does",
"a parent process. Returns: bool: Whether or not the current process is a",
"will always have rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess` will be",
"If a value is not a list or tuple, it is assumed to",
"set of different params. At most :obj:`max_num_processes` concurrent processes will be used. This",
"{rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info:",
"param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value is not None:",
"= \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir,",
"experiment (Experiment): The experiment to run. list_of_params (list of dict): A list of",
"ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = []",
"is set automatically by the framework, and should not \" \"be used manually.\",",
"\" \"dumped in the output dir from an eariler run. When this option",
"run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc",
"bits to use to represent the generated number. Defaults to 32. Returns: int:",
"import itertools import logging import multiprocessing import multiprocessing.connection import pathlib import random import",
"from . import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self,",
"= 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]:",
"precedence over the parameters copied from the current experiment. .. warning:: The subprocess",
"launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be instructed to",
"Params given here takes precedence over the parameters copied from the current experiment.",
"\"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if",
"value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = [] for param in",
"= str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params)",
"multiprocessing.active_children() for proc in procs: try: proc.kill() except Exception: pass for proc in",
"argument is a parameter and a list of all values that you want",
"this one \" \"will override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False",
"MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the",
"len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc) while len(self._live_processes) > 0: self._wait()",
"return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug':",
"new_seed(self, nbits=32) -> int: \"\"\"Use this function to generate random numbers seeded by",
"parameter. It then builds a list of parameter dictionaries such that all combinations",
"type=int, default=0, help=\"For multiprocessing, gives the local rank for this process. \" \"This",
"convenient way of generating such a list. max_num_processes (int, optional): The maximum number",
"__init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir:",
"a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\",",
"input. \"\"\" # Make sure all values are lists for key, value in",
"name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs in. Will be created if",
"in procs: try: proc.join() except Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use",
"of the current process. The master process will always have rank 0, and",
"is not None def local_rank(self): \"\"\"Returns the local rank of the current process.",
"core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that this process is a subprocess.",
"self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self,",
"processes to use for running the experiments. Defaults to 1. \"\"\" pool =",
"by the framework, and should not \" \"be used manually.\", allow_from_file=False, hidden=True, ),",
"as core import wrapt from rich.console import Console from rich.markup import escape from",
"{ \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" } ]",
"{name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def",
"created by taking the cartesian product of all values in the input. \"\"\"",
"theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green',",
"the list. The output of this function can be passed directly to :func:`pystematic.run_parameter_sweep`.",
"is not what you want, you should pass a new seed to this",
"handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f)",
"\"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be used to build",
"mechanism to \" \"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path,",
"import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) ->",
"subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return",
"A mapping from parameter name to a list of values to try for",
"datetime import functools import itertools import logging import multiprocessing import multiprocessing.connection import pathlib",
"local rank for this process. \" \"This parameter is set automatically by the",
"experiment, list_of_params): for params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc =",
"from parameter name to a list of values to try for that parameter.",
"run-logs in. Will be created if it \" \"does not exist.\", type=str ),",
"rank for this process. \" \"This parameter is set automatically by the framework,",
"constant (its value will be the same in all combinations). Returns: list of",
"2, \"str_param\": \"world\" } ] Args: **param_values: A mapping from parameter name to",
"subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching",
". import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app)",
"current experiment. .. warning:: The subprocess will be initialized with the same random",
"parent process. Returns: bool: Whether or not the current process is a subprocess.",
"from rich.theme import Theme from .. import parametric from . import yaml_wrapper as",
"new seed to this function in the ``random_seed`` parameter. E.g.: .. code-block:: python",
"\"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess",
"int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list == [ { \"int_param\": 1, \"str_param\":",
"Defaults to 32. Returns: int: A random number seeded by the experiment parameter",
"param_matrix(self, **param_values): \"\"\"This function can be used to build parameter combinations to use",
"= [proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for",
"\"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank):",
"pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\")",
"{level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class",
"self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"]))",
"represent the generated number. Defaults to 32. Returns: int: A random number seeded",
"this process is a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True",
"that should be passed to the subprocess. Params given here takes precedence over",
"way of generating such a list. max_num_processes (int, optional): The maximum number of",
"'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False) if no_style: theme = Theme({},",
"{ \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" }, {",
"current process. The master process will always have rank 0, and every subprocess",
"= Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg =",
"a set of different params. At most :obj:`max_num_processes` concurrent processes will be used.",
"override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits,",
"error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for",
"the generated number. Defaults to 32. Returns: int: A random number seeded by",
"self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close()",
"it \" \"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag",
"= \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() >",
"a subprocess. \"\"\" return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the local",
"yaml file, such as the one \" \"dumped in the output dir from",
"dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random",
"to the subprocess. Params given here takes precedence over the parameters copied from",
"will be assigned a new local rank from an incrementing integer counter starting",
"param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as",
"experiments have been run. Args: experiment (Experiment): The experiment to run. list_of_params (list",
"{name: value for name, value in self.params.items()} for name, value in additional_params.items(): subprocess_params[name]",
"have the same output directory and parameters as the current process. Args: **additional_params:",
"not isinstance(value, (list, tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations = []",
"}, { \"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values: A mapping from",
"= multiprocessing.active_children() for proc in procs: try: proc.kill() except Exception: pass for proc",
"code-block:: python import pystematic as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"]",
"logging import multiprocessing import multiprocessing.connection import pathlib import random import string import pystematic",
"logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10)",
"a subprocess. The subprocess will be instructed to execute the main function of",
"be created if it \" \"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False,",
"self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be",
"self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self,",
"app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param)",
"is a subprocess. \"\"\" return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the",
"proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while",
"dict): super().on_value(param, value, result_dict) if value is not None: if not value.exists(): raise",
"value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value is not None: if",
":func:`launch_subprocess` in a parent process. Returns: bool: Whether or not the current process",
"import string import pystematic import pystematic.core as core import wrapt from rich.console import",
"None: if not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = []",
"of values to try for that parameter. If a value is not a",
"will block until all experiments have been run. Args: experiment (Experiment): The experiment",
"list of values to try for that parameter. If a value is not",
"not None: if not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops =",
"escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter",
"logger.error(f\"Experiment ended at {end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at",
"experiment parameters from a yaml file, such as the one \" \"dumped in",
"seed the master random number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\",",
"that you want to try for that parameter. It then builds a list",
"= wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None",
"with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that",
"parameter ``random_seed``. Expected use is to seed your own random number generators. Args:",
"name=\"subprocess\", default=None, help=\"Internally used to indicate that this process is a subprocess. \"",
"be used to build parameter combinations to use when running parameter sweeps. It",
"currently running experiment, and have the same output directory and parameters as the",
"if error is not None: logger.error(f\"Experiment ended at {end_time} with an error: {error}\",",
"tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations = [] for instance in",
"have been run. Args: experiment (Experiment): The experiment to run. list_of_params (list of",
"the same random seed as the current process. If this is not what",
"None: \"\"\"Runs an experiment multiple times with a set of different params. At",
"self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes: if proc.sentinel",
"``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess",
"all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from",
"rich.theme import Theme from .. import parametric from . import yaml_wrapper as yaml",
"+ escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name}",
"\"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params = {name:",
"keys = param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return",
"the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed",
"Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green'",
"process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be used to",
"= Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def",
"generated number. Defaults to 32. Returns: int: A random number seeded by the",
"api_object): for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def",
"for proc in procs: try: proc.kill() except Exception: pass for proc in procs:",
"= ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list == [ { \"int_param\":",
"python logging mechanism to \" \"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter(",
"for key, value in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params",
"}, { \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" }",
"optional): The maximum number of concurrent processes to use for running the experiments.",
"parameter is set automatically by the framework, and should not \" \"be used",
"will be the same in all combinations). Returns: list of dicts: A list",
"parameter dictionaries. Each corresponding to one run of the experiment. See :func:`pystematic.param_matrix` for",
"core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the python logging mechanism to",
"StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__",
"the input. \"\"\" # Make sure all values are lists for key, value",
"can be passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic",
"type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the python logging",
"_ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank",
"_create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase",
"can be used to build parameter combinations to use when running parameter sweeps.",
"self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] >",
".. code-block:: python import pystematic as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\",",
"pystematic.core as core import wrapt from rich.console import Console from rich.markup import escape",
"self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen:",
"keywork arguments, where each argument is a parameter and a list of all",
"The maximum number of concurrent processes to use for running the experiments. Defaults",
"experiment): for param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name",
"store all run-logs in. Will be created if it \" \"does not exist.\",",
"output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({",
"always have rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned",
"call to :func:`launch_subprocess` in a parent process. Returns: bool: Whether or not the",
"class StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict",
"try: proc.join() except Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use this function",
"a list or tuple, it is assumed to be constant (its value will",
"msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d",
"name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the python logging mechanism to \"",
"self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else:",
"+ string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory",
"}, inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle =",
"from .. import parametric from . import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard')",
"'{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not",
"{rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}]",
"\"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\":",
"{name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True,",
"and every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a new local rank",
"all combinations of parameter values appear once in the list. The output of",
"launched with :func:`pystematic.launch_subprocess` will be assigned a new local rank from an incrementing",
"def _wait(self): sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs",
"pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int",
"if it \" \"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug",
"number of concurrent processes to use for running the experiments. Defaults to 1.",
"nbits=32) -> int: \"\"\"Use this function to generate random numbers seeded by the",
"experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for",
"wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None)",
"param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations",
"the subprocess. Params given here takes precedence over the parameters copied from the",
"for params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc)",
"used to indicate that this process is a subprocess. \" \"DO NOT USE",
"``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The",
"random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert",
"random import string import pystematic import pystematic.core as core import wrapt from rich.console",
"running the experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def",
"local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False):",
"\" \"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment",
"random numbers seeded by the experiment parameter ``random_seed``. Expected use is to seed",
"else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent",
"will be used. This call will block until all experiments have been run.",
"str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def",
"been launched by a call to :func:`launch_subprocess` in a parent process. Returns: bool:",
"parameter combinations created by taking the cartesian product of all values in the",
"[] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with",
"not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars",
"help=\"Parent directory to store all run-logs in. Will be created if it \"",
"import pathlib import random import string import pystematic import pystematic.core as core import",
"self._log_handler.close() procs = multiprocessing.active_children() for proc in procs: try: proc.kill() except Exception: pass",
"\"\"\"Returns the local rank of the current process. The master process will always",
"suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def",
"takes an arbitrary number of keywork arguments, where each argument is a parameter",
"from an eariler run. When this option is \" \"set from the command",
"with value.open(\"r\") as f: params_from_file = yaml.load(f) for key, value in params_from_file.items(): if",
"builds a list of parameter dictionaries such that all combinations of parameter values",
"help=\"Read experiment parameters from a yaml file, such as the one \" \"dumped",
"{name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi:",
"= param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations",
"a convenient way of generating such a list. max_num_processes (int, optional): The maximum",
"= pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__",
"at {end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close()",
"def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object):",
"hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes =",
"f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is",
"rank from an incrementing integer counter starting at 1. Returns: int: The local",
"\"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values: A",
"experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a",
"(Experiment): The experiment to run. list_of_params (list of dict): A list of parameter",
"self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter:",
"proc in procs: try: proc.kill() except Exception: pass for proc in procs: try:",
"StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as",
"local_rank(self): \"\"\"Returns the local rank of the current process. The master process will",
"'red', 'rank': 'green', 'name': 'green' }, inherit=False) if no_style: theme = Theme({}, inherit=False)",
"Returns: bool: Whether or not the current process is a subprocess. \"\"\" return",
"= params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level =",
"list of parameter combinations created by taking the cartesian product of all values",
"instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param,",
"not the current process is a subprocess. \"\"\" return self.params[\"subprocess\"] is not None",
"multiprocessing, gives the local rank for this process. \" \"This parameter is set",
"additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter)",
"messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml",
"'green', 'name': 'green' }, inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output =",
"the current process. Args: **additional_params: Any additional parameters that should be passed to",
"(int, optional): The maximum number of concurrent processes to use for running the",
"subprocesses.\") subprocess_params = {name: value for name, value in self.params.items()} for name, value",
"import escape from rich.theme import Theme from .. import parametric from . import",
"subprocess will be initialized with the same random seed as the current process.",
"pass def new_seed(self, nbits=32) -> int: \"\"\"Use this function to generate random numbers",
"force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def",
"logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in procs: try:",
"import pystematic.core as core import wrapt from rich.console import Console from rich.markup import",
"getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase",
"def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning':",
"(list, tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations = [] for instance",
"NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing,",
"instructed to execute the main function of the currently running experiment, and have",
"an arbitrary number of keywork arguments, where each argument is a parameter and",
"int: A random number seeded by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits)",
"if value is not None: if not value.exists(): raise ValueError(f\"File does not exist:",
"def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be instructed",
"with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs =",
"list of parameter dictionaries such that all combinations of parameter values appear once",
"for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param,",
"own random number generators. Args: nbits (int, optional): The number of bits to",
") assert param_list == [ { \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\":",
"sure all values are lists for key, value in param_values.items(): if not isinstance(value,",
"experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) ->",
"an incrementing integer counter starting at 1. Returns: int: The local rank of",
"self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\")",
"string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6))",
"cartesian product of all values in the input. \"\"\" # Make sure all",
"all values that you want to try for that parameter. It then builds",
"+ \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level}",
"number seeded by the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params)",
"core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local rank for this process.",
"takes precedence over the parameters copied from the current experiment. .. warning:: The",
"= yaml.load(f) for key, value in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key,",
"standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name in dir(self.api_object): if not",
"0, and every subprocess launched with :func:`pystematic.launch_subprocess` will be assigned a new local",
"StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue',",
"result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all",
"use is to seed your own random number generators. Args: nbits (int, optional):",
"list_of_params (list of dict): A list of parameter dictionaries. Each corresponding to one",
"indicate that this process is a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path,",
"be used. This call will block until all experiments have been run. Args:",
"dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time =",
"\"str_param\": \"world\" } ] Args: **param_values: A mapping from parameter name to a",
"use for running the experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment,",
"= datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank =",
"if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment,",
"such a list. max_num_processes (int, optional): The maximum number of concurrent processes to",
"Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use this function to generate random",
"used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context =",
"inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record):",
"experiment multiple times with a set of different params. At most :obj:`max_num_processes` concurrent",
"all values are lists for key, value in param_values.items(): if not isinstance(value, (list,",
"def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment",
"on/off. Configures the python logging mechanism to \" \"print all DEBUG messages.\", type=bool,",
"the local rank for this process. \" \"This parameter is set automatically by",
"the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32),",
"with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')",
"name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local rank for this process. \"",
"the same in all combinations). Returns: list of dicts: A list of parameter",
"import parametric from . import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin:",
"Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool:",
"no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output =",
"rich.console import Console from rich.markup import escape from rich.theme import Theme from ..",
"directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class",
"The subprocess will be instructed to execute the main function of the currently",
"logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler",
"flag on/off. Configures the python logging mechanism to \" \"print all DEBUG messages.\",",
"self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True)",
"combinations to use when running parameter sweeps. It takes an arbitrary number of",
"on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value is not",
"def new_seed(self, nbits=32) -> int: \"\"\"Use this function to generate random numbers seeded",
"from rich.console import Console from rich.markup import escape from rich.theme import Theme from",
"= StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name)",
"rank of the current process. The master process will always have rank 0,",
"handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True,",
"if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file =",
"standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs in.",
"of parameter dictionaries. Each corresponding to one run of the experiment. See :func:`pystematic.param_matrix`",
"new local rank from an incrementing integer counter starting at 1. Returns: int:",
"experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True)",
"command line, any other options supplied after this one \" \"will override the",
"params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"]))",
"all run-logs in. Will be created if it \" \"does not exist.\", type=str",
"itertools import logging import multiprocessing import multiprocessing.connection import pathlib import random import string",
"def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value is",
"line, any other options supplied after this one \" \"will override the ones",
"'{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an",
"list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if this process is a subprocess.",
"be assigned a new local rank from an incrementing integer counter starting at",
"value.open(\"r\") as f: params_from_file = yaml.load(f) for key, value in params_from_file.items(): if key",
"multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be instructed to execute the main",
"the experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self)",
"\"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\":",
"same output directory and parameters as the current process. Args: **additional_params: Any additional",
"hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f)",
"= wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int =",
"to this function in the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\"",
"dict): A list of parameter dictionaries. Each corresponding to one run of the",
"0 or pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\"",
"\"\"\"Returns true if this process is a subprocess. I.e. it has been launched",
"logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1)",
"experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else:",
"random number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used",
"wrapt from rich.console import Console from rich.markup import escape from rich.theme import Theme",
"seed your own random number generators. Args: nbits (int, optional): The number of",
"level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\"",
"int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params,",
"given here takes precedence over the parameters copied from the current experiment. ..",
"list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc) while len(self._live_processes) >",
"blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f) for key, value in params_from_file.items():",
"experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name in dir(self.api_object): if not name.startswith(\"_\"):",
"= wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def _before_experiment(self, experiment, params):",
"string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory",
"Args: experiment (Experiment): The experiment to run. list_of_params (list of dict): A list",
"value in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] = [value] keys =",
"pathlib import random import string import pystematic import pystematic.core as core import wrapt",
"2], str_param=[\"hello\", \"world\"] ) assert param_list == [ { \"int_param\": 1, \"str_param\": \"hello\"",
"in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] = [value] keys = param_values.keys()",
"automatically by the framework, and should not \" \"be used manually.\", allow_from_file=False, hidden=True,",
"StandardPlugin: def __init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10)",
"by a call to :func:`launch_subprocess` in a parent process. Returns: bool: Whether or",
"\"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values: A mapping",
"this process is a subprocess. I.e. it has been launched by a call",
"= file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level =",
"logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\")",
"= [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def",
"passed to the subprocess. Params given here takes precedence over the parameters copied",
"Args: nbits (int, optional): The number of bits to use to represent the",
"= pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\")",
"parameter combinations to use when running parameter sweeps. It takes an arbitrary number",
"the local rank of the current process. The master process will always have",
"setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits",
"param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict):",
"the experiment. See :func:`pystematic.param_matrix` for a convenient way of generating such a list.",
"the cartesian product of all values in the input. \"\"\" # Make sure",
"directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic as ps param_list",
"\" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0,",
"string import pystematic import pystematic.core as core import wrapt from rich.console import Console",
"It then builds a list of parameter dictionaries such that all combinations of",
"app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return experiment",
"not None def local_rank(self): \"\"\"Returns the local rank of the current process. The",
"to a list of values to try for that parameter. If a value",
"subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int,",
"bool: \"\"\"Returns true if this process is a subprocess. I.e. it has been",
"pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler =",
"wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None)",
"def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times with",
"number. Defaults to 32. Returns: int: A random number seeded by the experiment",
"self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler",
": core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file:",
"procs = multiprocessing.active_children() for proc in procs: try: proc.kill() except Exception: pass for",
"list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times with a set of",
"\"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\":",
"values in the input. \"\"\" # Make sure all values are lists for",
"(its value will be the same in all combinations). Returns: list of dicts:",
"'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' }, inherit=False) if no_style: theme",
"self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params = {name: value for",
"{error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc",
"pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if this process is a",
"sweeps. It takes an arbitrary number of keywork arguments, where each argument is",
"core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml file, such as the",
"subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler =",
"rank of the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function",
"_create_log_dir_name(params[\"output_dir\"], experiment.name) self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler],",
"import pystematic as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert",
"exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\")",
"yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None:",
"will be instructed to execute the main function of the currently running experiment,",
"and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f) for key,",
"in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f:",
"= string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in",
"launch further subprocesses.\") subprocess_params = {name: value for name, value in self.params.items()} for",
"Configures the python logging mechanism to \" \"print all DEBUG messages.\", type=bool, is_flag=True",
"level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" +",
"exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the python",
"}, { \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" },",
"combinations created by taking the cartesian product of all values in the input.",
"params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\",",
"parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None):",
"except Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use this function to generate",
"or pystematic.subprocess_counter > 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level}",
"import random import string import pystematic import pystematic.core as core import wrapt from",
"want to try for that parameter. It then builds a list of parameter",
"handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name =",
"value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with",
"output of this function can be passed directly to :func:`pystematic.run_parameter_sweep`. For example: ..",
"USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives",
"are lists for key, value in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key]",
"time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank",
"\"\"\" return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the local rank of",
"experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times with a set",
"pystematic as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list",
"), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml file, such as",
"in the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise",
"None: logger.error(f\"Experiment ended at {end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended",
"StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict =",
"from the command line, any other options supplied after this one \" \"will",
"self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ = _create_log_dir_name(params[\"output_dir\"],",
"self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str",
"key, value in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params =",
"to one run of the experiment. See :func:`pystematic.param_matrix` for a convenient way of",
"None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self,",
"to build parameter combinations to use when running parameter sweeps. It takes an",
"of parameter combinations created by taking the cartesian product of all values in",
"of dict): A list of parameter dictionaries. Each corresponding to one run of",
"if not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\") blacklisted_config_ops = [] for",
"to indicate that this process is a subprocess. \" \"DO NOT USE MANUALLY.\",",
"if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params = {name: value",
"dicts: A list of parameter combinations created by taking the cartesian product of",
"self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment :",
"in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params in list_of_params: while len(self._live_processes)",
"== [ { \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\"",
"experiment def extend_api(self, api_object): for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name,",
"self._log_handler = None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment",
"_after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment ended",
"\" \"will override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter(",
"the experiment parameter ``random_seed``. Expected use is to seed your own random number",
"default=0, help=\"For multiprocessing, gives the local rank for this process. \" \"This parameter",
"} ] Args: **param_values: A mapping from parameter name to a list of",
"with the same random seed as the current process. If this is not",
"current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix =",
"{end_time} with an error: {error}\", exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs",
"blacklisted_config_ops = [] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file:",
"datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for",
"completed_procs = [] for proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for",
"\"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f) for",
"an experiment multiple times with a set of different params. At most :obj:`max_num_processes`",
"self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times",
"build parameter combinations to use when running parameter sweeps. It takes an arbitrary",
"32. Returns: int: A random number seeded by the experiment parameter ``random_seed``. \"\"\"",
"process is a subprocess. \"\"\" return self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns",
"default=\"./output\", help=\"Parent directory to store all run-logs in. Will be created if it",
"default=None, help=\"Internally used to indicate that this process is a subprocess. \" \"DO",
"over the parameters copied from the current experiment. .. warning:: The subprocess will",
"run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple times with a",
"generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that this process is",
"parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess.",
"return directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\")",
"= StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for",
"from an incrementing integer counter starting at 1. Returns: int: The local rank",
"self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be used to build parameter combinations",
"self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None)",
"a list. max_num_processes (int, optional): The maximum number of concurrent processes to use",
"[] def _wait(self): sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels)",
"in the input. \"\"\" # Make sure all values are lists for key,",
"params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with self.params_file.open(\"w\") as f:",
"**additional_params) -> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be instructed to execute",
"class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if",
"your own random number generators. Args: nbits (int, optional): The number of bits",
"the currently running experiment, and have the same output directory and parameters as",
"finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self, experiment, list_of_params): for params",
"__init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10)",
"a new local rank from an incrementing integer counter starting at 1. Returns:",
"[] for proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in",
"of keywork arguments, where each argument is a parameter and a list of",
"\"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0:",
"additional parameters that should be passed to the subprocess. Params given here takes",
"yaml.load(f) for key, value in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value)",
"name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank()",
"other options supplied after this one \" \"will override the ones loaded from",
"type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that this",
"process is a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ),",
"Will be created if it \" \"does not exist.\", type=str ), core.Parameter( name=\"debug\",",
"output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta',",
"in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to",
"= random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]:",
"this function can be passed directly to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python",
"\"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" } ] Args:",
"all experiments have been run. Args: experiment (Experiment): The experiment to run. list_of_params",
"appear once in the list. The output of this function can be passed",
"of bits to use to represent the generated number. Defaults to 32. Returns:",
"the python logging mechanism to \" \"print all DEBUG messages.\", type=bool, is_flag=True ),",
"to store all run-logs in. Will be created if it \" \"does not",
"subprocess_params = {name: value for name, value in self.params.items()} for name, value in",
"**param_values): \"\"\"This function can be used to build parameter combinations to use when",
"def close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment =",
"super().on_value(param, value, result_dict) if value is not None: if not value.exists(): raise ValueError(f\"File",
"parameters as the current process. Args: **additional_params: Any additional parameters that should be",
"random number generators. Args: nbits (int, optional): The number of bits to use",
"# Make sure all values are lists for key, value in param_values.items(): if",
"datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment ended at {end_time} with an",
"does not exist: '{value}'.\") blacklisted_config_ops = [] for param in result_dict.get_params(): if hasattr(param,",
"the parameters copied from the current experiment. .. warning:: The subprocess will be",
"import logging import multiprocessing import multiprocessing.connection import pathlib import random import string import",
"output dir from an eariler run. When this option is \" \"set from",
"= ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if this process",
"not what you want, you should pass a new seed to this function",
"<reponame>evalldor/pystematic import datetime import functools import itertools import logging import multiprocessing import multiprocessing.connection",
"priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return experiment def",
"in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"] = str(self.params_file) subprocess_params[\"local_rank\"] =",
"combinations of parameter values appear once in the list. The output of this",
"values to try for that parameter. If a value is not a list",
"\" \"set from the command line, any other options supplied after this one",
"is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml file, such",
"1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2,",
"core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs in. Will be created",
"\" \"be used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self, num_processes):",
"= \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level}",
"experiment parameter ``random_seed``. Expected use is to seed your own random number generators.",
"[] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self,",
"help=\"The value to seed the master random number generator with.\", type=int, default_help=\"<randomly generated>\"",
"self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\" if",
"default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate that this process",
"parameters copied from the current experiment. .. warning:: The subprocess will be initialized",
"chars = string.digits + string.ascii_lowercase # + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _",
"of generating such a list. max_num_processes (int, optional): The maximum number of concurrent",
"max_num_processes (int, optional): The maximum number of concurrent processes to use for running",
"of the currently running experiment, and have the same output directory and parameters",
"\"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters",
"= Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name':",
"theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle)",
"when running parameter sweeps. It takes an arbitrary number of keywork arguments, where",
"\"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures",
"file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error':",
"integer counter starting at 1. Returns: int: The local rank of the current",
"name to a list of values to try for that parameter. If a",
"parameter sweeps. It takes an arbitrary number of keywork arguments, where each argument",
"value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs",
"in the output dir from an eariler run. When this option is \"",
"The local rank of the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values):",
"escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\")",
"def extend_api(self, api_object): for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object,",
"subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) ->",
"pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing subprocess...\") else: self.output_dir.__wrapped__ =",
"value is not a list or tuple, it is assumed to be constant",
"assumed to be constant (its value will be the same in all combinations).",
"want, you should pass a new seed to this function in the ``random_seed``",
"if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self)",
"yaml logger = logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None: self.api_object =",
"self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if",
"= {name: value for name, value in self.params.items()} for name, value in additional_params.items():",
"\"\"\"Use this function to generate random numbers seeded by the experiment parameter ``random_seed``.",
"bool: Whether or not the current process is a subprocess. \"\"\" return self.params[\"subprocess\"]",
"proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes:",
"E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch",
"except Exception: pass for proc in procs: try: proc.join() except Exception: pass def",
"self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if",
"in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name in dir(self.api_object): if",
"escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') + \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if",
"if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path,",
"arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs",
"in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter(",
"pool = ProcessQueue(max_num_processes) pool.run_and_wait_for_completion(experiment, list_of_params) def is_subprocess(self) -> bool: \"\"\"Returns true if this",
"{end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in procs: try: proc.kill() except Exception:",
"value in self.params.items()} for name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter +=",
"name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name):",
"multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def _wait(self): sentinels = [proc.sentinel for",
"the current process. If this is not what you want, you should pass",
"list of parameter dictionaries. Each corresponding to one run of the experiment. See",
"if self.params[\"debug\"]: log_level = \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"]",
"python import pystematic as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] )",
"mapping from parameter name to a list of values to try for that",
"= escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]')",
"{msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self):",
"a list of parameter dictionaries such that all combinations of parameter values appear",
"run. list_of_params (list of dict): A list of parameter dictionaries. Each corresponding to",
"product of all values in the input. \"\"\" # Make sure all values",
"Returns: list of dicts: A list of parameter combinations created by taking the",
"help=\"For multiprocessing, gives the local rank for this process. \" \"This parameter is",
"app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in",
"should pass a new seed to this function in the ``random_seed`` parameter. E.g.:",
"\"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\":",
"import Theme from .. import parametric from . import yaml_wrapper as yaml logger",
"be constant (its value will be the same in all combinations). Returns: list",
"= \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ =",
"you want, you should pass a new seed to this function in the",
"self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to '{self.params_file}'.\") with",
"run. When this option is \" \"set from the command line, any other",
"{msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name}",
"for proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs:",
"file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the",
"is a subprocess. I.e. it has been launched by a call to :func:`launch_subprocess`",
"local rank from an incrementing integer counter starting at 1. Returns: int: The",
"here takes precedence over the parameters copied from the current experiment. .. warning::",
"\"world\" } ] Args: **param_values: A mapping from parameter name to a list",
"run of the experiment. See :func:`pystematic.param_matrix` for a convenient way of generating such",
"numbers seeded by the experiment parameter ``random_seed``. Expected use is to seed your",
"where each argument is a parameter and a list of all values that",
"pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict) if value is not None: if not",
"record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\"",
"+ \"[/name]\" time_str = datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter >",
"debug flag on/off. Configures the python logging mechanism to \" \"print all DEBUG",
"pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\") return directory def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return",
"{msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core])",
"local rank of the current process. The master process will always have rank",
"not a list or tuple, it is assumed to be constant (its value",
"a value is not a list or tuple, it is assumed to be",
"= multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes: if proc.sentinel in finished_sentinels:",
"in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path,",
"as the current process. Args: **additional_params: Any additional parameters that should be passed",
"The experiment to run. list_of_params (list of dict): A list of parameter dictionaries.",
"experiment, and have the same output directory and parameters as the current process.",
"_before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__",
"not param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f) for key, value",
"as ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list ==",
"not \" \"be used manually.\", allow_from_file=False, hidden=True, ), ] class ProcessQueue: def __init__(self,",
"Returns: int: The local rank of the current process. \"\"\" return self.params[\"local_rank\"] def",
"it has been launched by a call to :func:`launch_subprocess` in a parent process.",
"once in the list. The output of this function can be passed directly",
"number generators. Args: nbits (int, optional): The number of bits to use to",
"key, value in param_values.items(): if not isinstance(value, (list, tuple)): param_values[key] = [value] keys",
"wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None) self._log_handler = None def",
"example: .. code-block:: python import pystematic as ps param_list = ps.param_matrix( int_param=[1, 2],",
"such that all combinations of parameter values appear once in the list. The",
"generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally used to indicate",
"extend_api(self, api_object): for name in dir(self.api_object): if not name.startswith(\"_\"): setattr(api_object, name, getattr(self.api_object, name))",
"ps param_list = ps.param_matrix( int_param=[1, 2], str_param=[\"hello\", \"world\"] ) assert param_list == [",
"master process will always have rank 0, and every subprocess launched with :func:`pystematic.launch_subprocess`",
"= logging.getLogger('pystematic.standard') class StandardPlugin: def __init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created,",
"isinstance(value, (list, tuple)): param_values[key] = [value] keys = param_values.keys() param_combinations = [] for",
"value in params_from_file.items(): if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [",
"framework, and should not \" \"be used manually.\", allow_from_file=False, hidden=True, ), ] class",
"Returns: int: A random number seeded by the experiment parameter ``random_seed``. \"\"\" return",
"datetime.datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S') if pystematic.local_rank() > 0 or pystematic.subprocess_counter > 0: rank = \"[rank]\"",
"in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc in self._live_processes: if",
"= pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Initializing",
"for that parameter. It then builds a list of parameter dictionaries such that",
"params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler =",
"what you want, you should pass a new seed to this function in",
"subprocess will be instructed to execute the main function of the currently running",
"= int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment,",
"\"world\"] ) assert param_list == [ { \"int_param\": 1, \"str_param\": \"hello\" }, {",
"def __init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None)",
"param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys, instance))) return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour):",
"the master random number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None,",
"If this is not what you want, you should pass a new seed",
"The number of bits to use to represent the generated number. Defaults to",
"return param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value,",
"copied from the current experiment. .. warning:: The subprocess will be initialized with",
"list. max_num_processes (int, optional): The maximum number of concurrent processes to use for",
"A list of parameter dictionaries. Each corresponding to one run of the experiment.",
"-> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path",
"return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self, experiment, list_of_params, max_num_processes=1) -> None: \"\"\"Runs an experiment multiple",
"pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params =",
"this process. \" \"This parameter is set automatically by the framework, and should",
"file, such as the one \" \"dumped in the output dir from an",
"priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params: experiment.add_parameter(param) return",
"if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__ = pathlib.Path(params[\"subprocess\"]).parent self.params_file.__wrapped__ = pathlib.Path(params[\"subprocess\"]) self._log_handler",
"be the same in all combinations). Returns: list of dicts: A list of",
"self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self) -> None:",
"import datetime import functools import itertools import logging import multiprocessing import multiprocessing.connection import",
"[ { \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" },",
"combinations). Returns: list of dicts: A list of parameter combinations created by taking",
"priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param in standard_params:",
"escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name = \"[name]\" + escape(f'[{record.name}]') +",
"), ] class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes",
"in procs: try: proc.kill() except Exception: pass for proc in procs: try: proc.join()",
"for name, value in self.params.items()} for name, value in additional_params.items(): subprocess_params[name] = value",
"Expected use is to seed your own random number generators. Args: nbits (int,",
"= Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output = Console(file=self.file_handle) def handle(self, record): level_str =",
"name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml file, such as the one",
"record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core]) def close(self): self.file_handle.close() class StandardApi: def __init__(self) ->",
"Each corresponding to one run of the experiment. See :func:`pystematic.param_matrix` for a convenient",
"# + string.ascii_uppercase suffix = \"\".join(random.SystemRandom().choice(chars) for _ in range(6)) directory = pathlib.Path(output_dir).resolve().joinpath(experiment_name).joinpath(f\"{current_time}-{suffix}\")",
"to represent the generated number. Defaults to 32. Returns: int: A random number",
"def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def",
"the output dir from an eariler run. When this option is \" \"set",
"all values in the input. \"\"\" # Make sure all values are lists",
"proc in procs: try: proc.join() except Exception: pass def new_seed(self, nbits=32) -> int:",
"the main function of the currently running experiment, and have the same output",
"self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing parameters file to",
"if no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle = file_path.open(\"a\") self.file_output",
"option is \" \"set from the command line, any other options supplied after",
"the experiment parameter ``random_seed``. \"\"\" return self.random_gen.getrandbits(nbits) def launch_subprocess(self, **additional_params) -> multiprocessing.Process: \"\"\"Launches",
"When this option is \" \"set from the command line, any other options",
".. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further",
"2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values:",
"of different params. At most :obj:`max_num_processes` concurrent processes will be used. This call",
"that all combinations of parameter values appear once in the list. The output",
"be passed to the subprocess. Params given here takes precedence over the parameters",
"int: The local rank of the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self,",
"params in list_of_params: while len(self._live_processes) >= self._num_processes: self._wait() proc = experiment.run_in_new_process(params) self._live_processes.append(proc) while",
"a yaml file, such as the one \" \"dumped in the output dir",
"\"\"\"Launches a subprocess. The subprocess will be instructed to execute the main function",
"to :func:`launch_subprocess` in a parent process. Returns: bool: Whether or not the current",
"python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params",
"import functools import itertools import logging import multiprocessing import multiprocessing.connection import pathlib import",
".. import parametric from . import yaml_wrapper as yaml logger = logging.getLogger('pystematic.standard') class",
"wrapt.ObjectProxy(None) self.params_file: pathlib.Path = wrapt.ObjectProxy(None) self.random_gen: random.Random = wrapt.ObjectProxy(None) self.subprocess_counter: int = wrapt.ObjectProxy(None)",
"= wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path =",
"proc in self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc)",
"subprocess_params[\"local_rank\"] = int(self.subprocess_counter) logger.debug(f\"Launching subprocess with arguments '{' '.join(subprocess_params)}'.\") return self.current_experiment.run_in_new_process(subprocess_params) def run_parameter_sweep(self,",
"the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be",
"= [value] keys = param_values.keys() param_combinations = [] for instance in itertools.product(*param_values.values()): param_combinations.append(dict(zip(keys,",
"\"\"\"This function can be used to build parameter combinations to use when running",
"of concurrent processes to use for running the experiments. Defaults to 1. \"\"\"",
"try for that parameter. It then builds a list of parameter dictionaries such",
"to 32. Returns: int: A random number seeded by the experiment parameter ``random_seed``.",
"result_dict) if value is not None: if not value.exists(): raise ValueError(f\"File does not",
"each argument is a parameter and a list of all values that you",
"type=pathlib.Path, help=\"Read experiment parameters from a yaml file, such as the one \"",
"name, getattr(self.api_object, name)) def _create_log_dir_name(output_dir, experiment_name): current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') chars = string.digits +",
"execute the main function of the currently running experiment, and have the same",
"local rank of the current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This",
"to use when running parameter sweeps. It takes an arbitrary number of keywork",
"from a yaml file, such as the one \" \"dumped in the output",
"> 0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name}",
"not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory",
"yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not",
"loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value",
"0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme",
"set automatically by the framework, and should not \" \"be used manually.\", allow_from_file=False,",
"parameter name to a list of values to try for that parameter. If",
"{name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level}",
"is not a list or tuple, it is assumed to be constant (its",
"process. The master process will always have rank 0, and every subprocess launched",
"initialized with the same random seed as the current process. If this is",
":func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic as ps param_list = ps.param_matrix(",
"that this process is a subprocess. \" \"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False,",
"seed to this function in the ``random_seed`` parameter. E.g.: .. code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed())",
"to seed your own random number generators. Args: nbits (int, optional): The number",
"class StandardLogHandler(logging.Handler): def __init__(self, file_path, no_style=False): super().__init__() theme = Theme({ 'debug': 'magenta', 'info':",
"self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes = [] def _wait(self): sentinels =",
"self.params.items()} for name, value in additional_params.items(): subprocess_params[name] = value self.subprocess_counter += 1 subprocess_params[\"subprocess\"]",
"process. If this is not what you want, you should pass a new",
"def __init__(self, app) -> None: self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment,",
"None def local_rank(self): \"\"\"Returns the local rank of the current process. The master",
":obj:`max_num_processes` concurrent processes will be used. This call will block until all experiments",
"is assumed to be constant (its value will be the same in all",
"rich.markup import escape from rich.theme import Theme from .. import parametric from .",
"subprocess. I.e. it has been launched by a call to :func:`launch_subprocess` in a",
"self._live_processes = [] def _wait(self): sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels",
"self.api_object = StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment):",
"any other options supplied after this one \" \"will override the ones loaded",
"allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For multiprocessing, gives the local rank",
"code-block:: python pystematic.launch_subprocess(random_seed=pystematic.new_seed()) \"\"\" if self.is_subprocess(): raise AssertionError(\"A subprocess cannot launch further subprocesses.\")",
"= [] def _wait(self): sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels =",
"help=\"Sets debug flag on/off. Configures the python logging mechanism to \" \"print all",
"if key not in blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\",",
"import pystematic import pystematic.core as core import wrapt from rich.console import Console from",
"tuple, it is assumed to be constant (its value will be the same",
"supplied after this one \" \"will override the ones loaded from the file.\",",
"value is not None: if not value.exists(): raise ValueError(f\"File does not exist: '{value}'.\")",
"return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be used to build parameter",
"def _get_log_file_name(output_dir, local_rank): if local_rank == 0: return output_dir.joinpath(\"log.txt\") return output_dir.joinpath(f\"log.rank-{local_rank}.txt\") class StandardLogHandler(logging.Handler):",
"\"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name}",
"generate random numbers seeded by the experiment parameter ``random_seed``. Expected use is to",
"self._num_processes = num_processes self._live_processes = [] def _wait(self): sentinels = [proc.sentinel for proc",
"parameters that should be passed to the subprocess. Params given here takes precedence",
"), core.Parameter( name=\"debug\", default=False, help=\"Sets debug flag on/off. Configures the python logging mechanism",
"Args: **additional_params: Any additional parameters that should be passed to the subprocess. Params",
"to :func:`pystematic.run_parameter_sweep`. For example: .. code-block:: python import pystematic as ps param_list =",
"-> bool: \"\"\"Returns true if this process is a subprocess. I.e. it has",
"exc_info=error) else: logger.info(f\"Experiment ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in",
"), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master random number",
"at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in procs: try: proc.kill() except",
"the command line, any other options supplied after this one \" \"will override",
"this option is \" \"set from the command line, any other options supplied",
"behaviour=ParamsFileBehaviour(), allow_from_file=False ), core.Parameter( name=\"random_seed\", default=functools.partial(random.getrandbits, 32), help=\"The value to seed the master",
"error is not None: logger.error(f\"Experiment ended at {end_time} with an error: {error}\", exc_info=error)",
"same in all combinations). Returns: list of dicts: A list of parameter combinations",
"dictionaries such that all combinations of parameter values appear once in the list.",
"subprocess. Params given here takes precedence over the parameters copied from the current",
"AssertionError(\"A subprocess cannot launch further subprocesses.\") subprocess_params = {name: value for name, value",
"self._live_processes: if proc.sentinel in finished_sentinels: completed_procs.append(proc) for proc in completed_procs: self._live_processes.remove(proc) def run_and_wait_for_completion(self,",
"None def _before_experiment(self, experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ =",
"times with a set of different params. At most :obj:`max_num_processes` concurrent processes will",
"number of bits to use to represent the generated number. Defaults to 32.",
"logging mechanism to \" \"print all DEBUG messages.\", type=bool, is_flag=True ), core.Parameter( name=\"params_file\",",
"def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg = escape(f\"{record.getMessage()}\") name",
"you should pass a new seed to this function in the ``random_seed`` parameter.",
"At most :obj:`max_num_processes` concurrent processes will be used. This call will block until",
"values that you want to try for that parameter. It then builds a",
"to generate random numbers seeded by the experiment parameter ``random_seed``. Expected use is",
"\"int_param\": 2, \"str_param\": \"world\" } ] Args: **param_values: A mapping from parameter name",
"param.allow_from_file: blacklisted_config_ops.append(param.name) with value.open(\"r\") as f: params_from_file = yaml.load(f) for key, value in",
"self.params_file.__wrapped__ = self.output_dir.joinpath(\"parameters.yaml\") self.output_dir.mkdir(parents=True, exist_ok=False) self._log_handler = StandardLogHandler(_get_log_file_name(self.output_dir, params[\"local_rank\"])) logging.basicConfig(level=log_level, handlers=[self._log_handler], force=True) logger.debug(f\"Writing",
"= [] for param in result_dict.get_params(): if hasattr(param, \"allow_from_file\") and not param.allow_from_file: blacklisted_config_ops.append(param.name)",
"call will block until all experiments have been run. Args: experiment (Experiment): The",
"use when running parameter sweeps. It takes an arbitrary number of keywork arguments,",
"import multiprocessing import multiprocessing.connection import pathlib import random import string import pystematic import",
"the same output directory and parameters as the current process. Args: **additional_params: Any",
"and parameters as the current process. Args: **additional_params: Any additional parameters that should",
"will be initialized with the same random seed as the current process. If",
"output directory and parameters as the current process. Args: **additional_params: Any additional parameters",
"help=\"Internally used to indicate that this process is a subprocess. \" \"DO NOT",
"StandardApi() app.on_experiment_created(self.experiment_created, priority=10) app.on_before_experiment(self.api_object._before_experiment, priority=10) app.on_after_experiment(self.api_object._after_experiment, priority=10) self.extend_api(app.get_api_object()) def experiment_created(self, experiment): for param",
"warning:: The subprocess will be initialized with the same random seed as the",
"for param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name in",
"'{self.params_file}'.\") with self.params_file.open(\"w\") as f: yaml.dump(params, f) def _after_experiment(self, error=None): end_time = datetime.datetime.now().strftime('%Y-%m-%d",
".. warning:: The subprocess will be initialized with the same random seed as",
"\"DO NOT USE MANUALLY.\", type=pathlib.Path, allow_from_file=False, hidden=True ), core.Parameter( name=\"local_rank\", type=int, default=0, help=\"For",
"parameter values appear once in the list. The output of this function can",
"of all values in the input. \"\"\" # Make sure all values are",
"end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if error is not None: logger.error(f\"Experiment ended at {end_time}",
"'debug': 'magenta', 'info': 'blue', 'warning': 'yellow', 'error': 'red', 'rank': 'green', 'name': 'green' },",
"self.file_handle.close() class StandardApi: def __init__(self) -> None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params:",
"use to represent the generated number. Defaults to 32. Returns: int: A random",
"master random number generator with.\", type=int, default_help=\"<randomly generated>\" ), core.Parameter( name=\"subprocess\", default=None, help=\"Internally",
"= \"DEBUG\" else: log_level = \"INFO\" if params[\"subprocess\"]: assert params[\"local_rank\"] > 0 self.output_dir.__wrapped__",
"to use for running the experiments. Defaults to 1. \"\"\" pool = ProcessQueue(max_num_processes)",
"'green' }, inherit=False) if no_style: theme = Theme({}, inherit=False) self.console_output = Console(theme=theme) self.file_handle",
"= num_processes self._live_processes = [] def _wait(self): sentinels = [proc.sentinel for proc in",
"value for name, value in self.params.items()} for name, value in additional_params.items(): subprocess_params[name] =",
"[proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = [] for proc",
"None: self.current_experiment : core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path =",
"you want to try for that parameter. It then builds a list of",
"values appear once in the list. The output of this function can be",
"ended at {end_time}.\") self._log_handler.close() procs = multiprocessing.active_children() for proc in procs: try: proc.kill()",
"to run. list_of_params (list of dict): A list of parameter dictionaries. Each corresponding",
"dictionaries. Each corresponding to one run of the experiment. See :func:`pystematic.param_matrix` for a",
"\"world\" }, { \"int_param\": 2, \"str_param\": \"hello\" }, { \"int_param\": 2, \"str_param\": \"world\"",
"1. Returns: int: The local rank of the current process. \"\"\" return self.params[\"local_rank\"]",
"\"hello\" }, { \"int_param\": 1, \"str_param\": \"world\" }, { \"int_param\": 2, \"str_param\": \"hello\"",
"0: rank = \"[rank]\" + escape(f\"[RANK {pystematic.local_rank()}]\") + \"[/rank]\" self.console_output.print(f\"{level} {rank} {name} {msg}\")",
"This call will block until all experiments have been run. Args: experiment (Experiment):",
"experiment, params): self.subprocess_counter.__wrapped__ = 0 self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ =",
"self.params[\"subprocess\"] is not None def local_rank(self): \"\"\"Returns the local rank of the current",
"main function of the currently running experiment, and have the same output directory",
"[ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store all run-logs in. Will be",
"current process. \"\"\" return self.params[\"local_rank\"] def param_matrix(self, **param_values): \"\"\"This function can be used",
"launched by a call to :func:`launch_subprocess` in a parent process. Returns: bool: Whether",
"self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\") if record.exc_info: self.console_output.print_exception(show_locals=True, suppress=[core]) self.file_output.print_exception(show_locals=True, suppress=[core])",
"is to seed your own random number generators. Args: nbits (int, optional): The",
"import Console from rich.markup import escape from rich.theme import Theme from .. import",
"self.file_output = Console(file=self.file_handle) def handle(self, record): level_str = escape(f\"[{record.levelname}]\") level = f\"[{record.levelname.lower()}]{level_str}[/{record.levelname.lower()}]\" msg",
"of dicts: A list of parameter combinations created by taking the cartesian product",
"created if it \" \"does not exist.\", type=str ), core.Parameter( name=\"debug\", default=False, help=\"Sets",
"-> multiprocessing.Process: \"\"\"Launches a subprocess. The subprocess will be instructed to execute the",
"procs: try: proc.join() except Exception: pass def new_seed(self, nbits=32) -> int: \"\"\"Use this",
"param_list == [ { \"int_param\": 1, \"str_param\": \"hello\" }, { \"int_param\": 1, \"str_param\":",
"self.file_output.print(f\"[{time_str}] {level} {rank} {name} {msg}\") else: self.console_output.print(f\"{level} {name} {msg}\") self.file_output.print(f\"[{time_str}] {level} {name} {msg}\")",
"] class ProcessQueue: def __init__(self, num_processes): self._mp_context = multiprocessing.get_context('spawn') self._num_processes = num_processes self._live_processes",
"core.Experiment = wrapt.ObjectProxy(None) self.params: dict = wrapt.ObjectProxy(None) self.output_dir: pathlib.Path = wrapt.ObjectProxy(None) self.params_file: pathlib.Path",
"``random_seed``. Expected use is to seed your own random number generators. Args: nbits",
"\"\"\"Runs an experiment multiple times with a set of different params. At most",
"with :func:`pystematic.launch_subprocess` will be assigned a new local rank from an incrementing integer",
"one \" \"will override the ones loaded from the file.\", behaviour=ParamsFileBehaviour(), allow_from_file=False ),",
"blacklisted_config_ops: result_dict.set_value_by_name(key, value) standard_params = [ core.Parameter( name=\"output_dir\", default=\"./output\", help=\"Parent directory to store",
"core import wrapt from rich.console import Console from rich.markup import escape from rich.theme",
"type=bool, is_flag=True ), core.Parameter( name=\"params_file\", type=pathlib.Path, help=\"Read experiment parameters from a yaml file,",
"seed as the current process. If this is not what you want, you",
"param_combinations class ParamsFileBehaviour(parametric.DefaultParameterBehaviour): def on_value(self, param, value: pathlib.Path, result_dict: dict): super().on_value(param, value, result_dict)",
"random seed as the current process. If this is not what you want,",
"in. Will be created if it \" \"does not exist.\", type=str ), core.Parameter(",
"sentinels = [proc.sentinel for proc in self._live_processes] finished_sentinels = multiprocessing.connection.wait(sentinels) completed_procs = []",
"the framework, and should not \" \"be used manually.\", allow_from_file=False, hidden=True, ), ]",
"param in standard_params: experiment.add_parameter(param) return experiment def extend_api(self, api_object): for name in dir(self.api_object):",
"list. The output of this function can be passed directly to :func:`pystematic.run_parameter_sweep`. For",
"self.current_experiment.__wrapped__ = experiment self.params.__wrapped__ = params self.random_gen.__wrapped__ = random.Random(params[\"random_seed\"]) if self.params[\"debug\"]: log_level ="
] |
[
"as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up",
"rows to create. cols : int Number of columns to create. figsize :",
"an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs =",
"if not _on_rtd: import numpy as _np from .setup_figure import setup_figure as _setup_figure",
"with a number of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through to",
"_on_rtd: import numpy as _np from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1,",
"tight_layout=None, **kwargs): \"\"\" Sets up a figure of size *figsize* with a number",
"_on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import numpy as _np",
"figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1,",
"to create. figsize : tuple Size of figure to create. expand : bool",
"axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand:",
"= (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif",
"the axes. (Unless there's only one axis, in which case it returns an",
"= _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i",
"figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure of size *figsize*",
"bool Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure`",
"which case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize =",
"**kwargs): \"\"\" Sets up a figure of size *figsize* with a number of",
"figure of size *figsize* with a number of rows (*rows*) and columns (*cols*).",
"fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of",
"= kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes =",
"_np from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True,",
"cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure of size",
"with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray`",
"= _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import numpy as _np from",
":class:`numpy.ndarray` An array of all of the axes. (Unless there's only one axis,",
"(figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout",
"in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if",
":class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the axes.",
"\"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig,",
"expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure of size *figsize* with a",
"number of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. ..",
"(Unless there's only one axis, in which case it returns an object instance",
"figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\":",
"dtype=object) for i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i,",
"columns to create. figsize : tuple Size of figure to create. expand :",
"\"\"\" Sets up a figure of size *figsize* with a number of rows",
"`figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array",
"in which case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize",
":meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to",
": tuple Size of figure to create. expand : bool Make the entire",
"object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {}",
"int Number of columns to create. figsize : tuple Size of figure to",
"axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols):",
"axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig,",
"import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\"",
"= _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols): axes[i,",
"for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape ==",
"The figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless",
"if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"]",
"**figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in",
"from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None,",
"*figsize* with a number of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through",
":class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout,",
"to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows",
": int Number of rows to create. cols : int Number of columns",
"kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows,",
"cols : int Number of columns to create. figsize : tuple Size of",
"_os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import numpy as _np from .setup_figure",
"(0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols,",
"\"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict):",
"up a figure of size *figsize* with a number of rows (*rows*) and",
"<reponame>joelfrederico/mytools import os as _os _on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not",
"------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all",
"= {\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs =",
"0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs)",
"1.2 Parameters ---------- rows : int Number of rows to create. cols :",
"Sets up a figure of size *figsize* with a number of rows (*rows*)",
"= fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0]",
"'True' if not _on_rtd: import numpy as _np from .setup_figure import setup_figure as",
"passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number",
"there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.)",
"as _os _on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import numpy",
"all of the axes. (Unless there's only one axis, in which case it",
"figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs",
"os as _os _on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import",
"expand : bool Make the entire figure with size `figsize`. Returns ------- fig",
"in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1):",
"array of all of the axes. (Unless there's only one axis, in which",
"elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi =",
"_np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols): axes[i, j]",
"if axes.shape == (1, 1): return fig, axes[0, 0] else: return fig, axes",
"tuple Size of figure to create. expand : bool Make the entire figure",
"figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for",
"An array of all of the axes. (Unless there's only one axis, in",
"None) == 'True' if not _on_rtd: import numpy as _np from .setup_figure import",
"cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows):",
"numpy as _np from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8,",
"fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object)",
"figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes :",
"not _on_rtd: import numpy as _np from .setup_figure import setup_figure as _setup_figure def",
"= {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"]",
"axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's only",
"j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else: return",
"to create. expand : bool Make the entire figure with size `figsize`. Returns",
"figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout",
"Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The",
"a figure of size *figsize* with a number of rows (*rows*) and columns",
"isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0,",
"it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows)",
"== \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None)",
"def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure",
"---------- rows : int Number of rows to create. cols : int Number",
"**kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else: return fig,",
"_setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in",
"i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs)",
"through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of",
"_setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a",
"size *figsize* with a number of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed",
".. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create.",
"(*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows :",
"= tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)}",
"dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j",
"dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0,",
"Parameters ---------- rows : int Number of rows to create. cols : int",
"_os _on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd: import numpy as",
": int Number of columns to create. figsize : tuple Size of figure",
"j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1,",
"Size of figure to create. expand : bool Make the entire figure with",
"dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes",
"the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure.",
"range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return",
"one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if",
"import os as _os _on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' if not _on_rtd:",
"tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi",
"setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets",
"axes. (Unless there's only one axis, in which case it returns an object",
"entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes",
"size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An",
"of columns to create. figsize : tuple Size of figure to create. expand",
"of rows to create. cols : int Number of columns to create. figsize",
"of the axes. (Unless there's only one axis, in which case it returns",
"None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols),",
"create. cols : int Number of columns to create. figsize : tuple Size",
"Number of columns to create. figsize : tuple Size of figure to create.",
"== 'True' if not _on_rtd: import numpy as _np from .setup_figure import setup_figure",
"0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize,",
"cols), dtype=object) for i in range(rows): for j in range(cols): axes[i, j] =",
"Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of",
"of figure to create. expand : bool Make the entire figure with size",
"gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for",
"figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's",
"rows : int Number of rows to create. cols : int Number of",
".setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs):",
"figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout ==",
"of size *figsize* with a number of rows (*rows*) and columns (*cols*). \\*\\*kwargs",
"Number of rows to create. cols : int Number of columns to create.",
"fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else:",
": :class:`numpy.ndarray` An array of all of the axes. (Unless there's only one",
"returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs",
"tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi',",
": bool Make the entire figure with size `figsize`. Returns ------- fig :",
"expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] =",
"for i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j],",
"case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols,",
"6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure of size *figsize* with",
"instance :class:`matplotlib.axis.Axis`.) \"\"\" if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if",
"of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded::",
"setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): \"\"\" Sets up a figure of",
"int Number of rows to create. cols : int Number of columns to",
"figsize : tuple Size of figure to create. expand : bool Make the",
"create. expand : bool Make the entire figure with size `figsize`. Returns -------",
"as _np from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1, figsize=(8, 6),",
"rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2",
"\\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int",
"and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ----------",
"create. figsize : tuple Size of figure to create. expand : bool Make",
"only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) \"\"\"",
"versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols",
"figure to create. expand : bool Make the entire figure with size `figsize`.",
"{\"rect\": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows,",
"1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi,",
"(*rows*) and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters",
"if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] = {\"rect\":",
"to create. cols : int Number of columns to create. figsize : tuple",
": :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the",
"j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0,",
"columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows",
"import numpy as _np from .setup_figure import setup_figure as _setup_figure def setup_axes(rows=1, cols=1,",
"of all of the axes. (Unless there's only one axis, in which case",
"{} if isinstance(tight_layout, dict): figargs[\"tight_layout\"] = tight_layout elif tight_layout == \"pdf\": figargs[\"tight_layout\"] =",
"range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape",
"a number of rows (*rows*) and columns (*cols*). \\*\\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`."
] |
[
"sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in onlyTwo: sys.stdout.write(\"Table:",
"{} in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches",
"in range(numColumns): if row[col] != row2[col]: return False, rowNum return True, 0 return",
"tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName",
"cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if",
"'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND",
"= self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND name NOT LIKE",
"cursor2.fetchone() if (row is None) or (row2 is None): return False, rowNum for",
"= False sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName, rowNum + 1))",
"tableInfo in db.tables.items(): if tableName not in self.tables: matches = False onlyTwo.append(tableName) if",
"{} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0:",
"__init__(self, name): self.name = name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory =",
"= db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if (row",
"TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql = \"SELECT",
"FROM '\" + tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) >",
"+ \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor()",
"= \"SELECT * FROM '\" + tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall()",
"range(numColumns): if row[col] != row2[col]: return False, rowNum return True, 0 return False,",
"* FROM '\" + tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows)",
"matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in {}",
"+ tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0: cursor2",
"for col in range(numColumns): if row[col] != row2[col]: return False, rowNum return True,",
"tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum =",
"= [] onlyOne = [] onlyTwo = [] for tableName, tableInfo in self.tables.items():",
"if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for",
"tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"***************",
"if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for",
"0: tableNames = [] for row in rows: tableNames.append(row[0]) for tableName in tableNames:",
"if tableName not in self.tables: matches = False onlyTwo.append(tableName) if len(matched) > 0:",
"False, rowNum return True, 0 return False, 0 def compare(self, db): matches =",
"rows = cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum,",
"= name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x: str(x,",
"matches = True matched = [] onlyOne = [] onlyTwo = [] for",
"row in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def",
"sys import sqlite3 from tableinfo import TableInfo class DbInfo(object): def __init__(self, name): self.name",
"import TableInfo class DbInfo(object): def __init__(self, name): self.name = name self.conn = sqlite3.connect(name)",
"self.name = name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x:",
"in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in",
"rowNum return True, 0 return False, 0 def compare(self, db): matches = True",
"self.tables: matches = False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables",
"= lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master",
"(row2 is None): return False, rowNum for col in range(numColumns): if row[col] !=",
"{}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name))",
"matches = False sys.stdout.write('Different Table: {} {} {} but in {} {}\\n'.format(tableName, self.name,",
"tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items():",
"> 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True)))",
"def compare(self, db): matches = True matched = [] onlyOne = [] onlyTwo",
"class DbInfo(object): def __init__(self, name): self.name = name self.conn = sqlite3.connect(name) self.tables =",
"DbInfo(object): def __init__(self, name): self.name = name self.conn = sqlite3.connect(name) self.tables = {}",
"name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x: str(x, 'utf-8',",
"tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if",
"for Table: {} in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo)",
"sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo)",
"db): matches = True matched = [] onlyOne = [] onlyTwo = []",
"return True, 0 return False, 0 def compare(self, db): matches = True matched",
"onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in",
"= cursor2.fetchone() if (row is None) or (row2 is None): return False, rowNum",
"for tableName, tableInfo in db.tables.items(): if tableName not in self.tables: matches = False",
"len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2",
"Data for Table: {} in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else:",
"table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only",
"from tableinfo import TableInfo class DbInfo(object): def __init__(self, name): self.name = name self.conn",
"cursor.fetchall() if len(rows) > 0: tableNames = [] for row in rows: tableNames.append(row[0])",
"\\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0: tableNames = [] for row",
"tableName, numColumns, db): cursor = self.conn.cursor() sql = \"SELECT * FROM '\" +",
"> 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 =",
"rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if (row is None) or (row2",
"onlyOne = [] onlyTwo = [] for tableName, tableInfo in self.tables.items(): tableInfo2 =",
"tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None: if",
"not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns),",
"{}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different",
"or (row2 is None): return False, rowNum for col in range(numColumns): if row[col]",
"else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {} {} {} but in",
"{} {} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches",
"Table: {} in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else:",
"in db.tables.items(): if tableName not in self.tables: matches = False onlyTwo.append(tableName) if len(matched)",
"tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns,",
"< 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches =",
"False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table",
"0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if",
"FROM sqlite_master WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall()",
"return False, rowNum for col in range(numColumns): if row[col] != row2[col]: return False,",
"def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql = \"SELECT * FROM",
"> 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in",
"'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND name",
"sqlite_master WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if",
"WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows)",
"is None) or (row2 is None): return False, rowNum for col in range(numColumns):",
"tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows <",
"{} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in onlyTwo: sys.stdout.write(\"Table: {}\\n\".format(table))",
"rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName,",
"cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if (row is None)",
"tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor",
"in enumerate(rows): row2 = cursor2.fetchone() if (row is None) or (row2 is None):",
"compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql = \"SELECT * FROM '\"",
"lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE",
"False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName not in self.tables: matches",
"sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table:",
"table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only",
"self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {}",
"db): cursor = self.conn.cursor() sql = \"SELECT * FROM '\" + tableName +",
"matches = False sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName, rowNum +",
"tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in onlyTwo: sys.stdout.write(\"Table: {}\\n\".format(table)) return",
"enumerate(rows): row2 = cursor2.fetchone() if (row is None) or (row2 is None): return",
"tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor()",
"in self.tables: matches = False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched",
"name): self.name = name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda",
"only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in onlyTwo: sys.stdout.write(\"Table: {}\\n\".format(table)) return matches",
"0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 = cursor2.fetchone()",
"= [] for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is",
"matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0:",
"TableInfo class DbInfo(object): def __init__(self, name): self.name = name self.conn = sqlite3.connect(name) self.tables",
"= False sys.stdout.write('Different Table: {} {} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False),",
"name FROM sqlite_master WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows =",
"if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if",
"type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) >",
"numColumns, db): cursor = self.conn.cursor() sql = \"SELECT * FROM '\" + tableName",
"is None): return False, rowNum for col in range(numColumns): if row[col] != row2[col]:",
"in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for",
"= self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches = False sys.stdout.write('Different Data for",
"if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in matched:",
"****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {}",
"=\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0:",
"rows = cursor.fetchall() if len(rows) > 0: tableNames = [] for row in",
"1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches = False",
"matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {} {} {} but",
"else: matches = False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName not",
"if len(rows) > 0: tableNames = [] for row in rows: tableNames.append(row[0]) for",
"col in range(numColumns): if row[col] != row2[col]: return False, rowNum return True, 0",
"for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables",
"in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor =",
"'\" + tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0:",
"not dataMatched: matches = False sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName,",
"else: matches = False sys.stdout.write('Different Table: {} {} {} but in {} {}\\n'.format(tableName,",
"str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\'",
"= True matched = [] onlyOne = [] onlyTwo = [] for tableName,",
"sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne),",
"self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows",
"Table: {} {} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else:",
"tableinfo import TableInfo class DbInfo(object): def __init__(self, name): self.name = name self.conn =",
"0 def compare(self, db): matches = True matched = [] onlyOne = []",
"cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in",
"tableName not in self.tables: matches = False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"***************",
"[] for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not",
"return False, 0 def compare(self, db): matches = True matched = [] onlyOne",
"dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches = False sys.stdout.write('Different",
"in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if",
"> 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in",
"[] onlyOne = [] onlyTwo = [] for tableName, tableInfo in self.tables.items(): tableInfo2",
"{}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName, tableInfo",
"tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0: cursor2 =",
"0 return False, 0 def compare(self, db): matches = True matched = []",
"import sys import sqlite3 from tableinfo import TableInfo class DbInfo(object): def __init__(self, name):",
"rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table:",
"None): return False, rowNum for col in range(numColumns): if row[col] != row2[col]: return",
"1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {} {}",
"for row in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName)",
"compare(self, db): matches = True matched = [] onlyOne = [] onlyTwo =",
"len(rows) > 0: tableNames = [] for row in rows: tableNames.append(row[0]) for tableName",
"self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql",
"= cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row",
"self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\")",
"{} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name",
"is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName,",
"{} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches =",
"row in enumerate(rows): row2 = cursor2.fetchone() if (row is None) or (row2 is",
"tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2):",
"None) or (row2 is None): return False, rowNum for col in range(numColumns): if",
"row2[col]: return False, rowNum return True, 0 return False, 0 def compare(self, db):",
"len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table:",
"cursor = self.conn.cursor() sql = \"SELECT * FROM '\" + tableName + \"'\"",
"{} matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne) >",
"[] for row in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn,",
"= self.conn.cursor() sql = \"SELECT * FROM '\" + tableName + \"'\" cursor.execute(sql)",
"db.tables.items(): if tableName not in self.tables: matches = False onlyTwo.append(tableName) if len(matched) >",
"{} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False",
"sql = \"SELECT * FROM '\" + tableName + \"'\" cursor.execute(sql) rows =",
"in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) >",
"row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False",
"= False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName not in self.tables:",
"{} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName,",
"db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched,",
"row[col] != row2[col]: return False, rowNum return True, 0 return False, 0 def",
"False sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName, rowNum + 1)) else:",
"only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo)",
"in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in",
"self.conn.cursor() sql = \"SELECT * FROM '\" + tableName + \"'\" cursor.execute(sql) rows",
"!= row2[col]: return False, rowNum return True, 0 return False, 0 def compare(self,",
"False, 0 def compare(self, db): matches = True matched = [] onlyOne =",
"= False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for",
"None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db)",
"sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo),",
"{} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table))",
"onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName not in self.tables: matches =",
"onlyTwo = [] for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2",
"db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if (row is",
"False sys.stdout.write('Different Table: {} {} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name,",
"import sqlite3 from tableinfo import TableInfo class DbInfo(object): def __init__(self, name): self.name =",
"= db.tables.get(tableName) if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000:",
"cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND name NOT",
"= [] for row in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] =",
"len(tableInfo.columns), db) if not dataMatched: matches = False sys.stdout.write('Different Data for Table: {}",
"if not dataMatched: matches = False sys.stdout.write('Different Data for Table: {} in row",
"tableName, tableInfo in db.tables.items(): if tableName not in self.tables: matches = False onlyTwo.append(tableName)",
"True, 0 return False, 0 def compare(self, db): matches = True matched =",
"len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table",
"= cursor.fetchall() if len(rows) > 0: tableNames = [] for row in rows:",
"if tableInfo2 is not None: if tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum",
"NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0: tableNames = []",
"for rowNum, row in enumerate(rows): row2 = cursor2.fetchone() if (row is None) or",
"cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for",
"\"'\" cursor.execute(sql) rows = cursor.fetchall() if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql)",
"sys.stdout.write('Different Table: {} {} {} but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False)))",
"if row[col] != row2[col]: return False, rowNum return True, 0 return False, 0",
"self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches = False sys.stdout.write('Different Data for Table:",
"0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne:",
"sqlite3 from tableinfo import TableInfo class DbInfo(object): def __init__(self, name): self.name = name",
"sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor =",
"for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables",
"False, rowNum for col in range(numColumns): if row[col] != row2[col]: return False, rowNum",
"self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName, tableInfo in",
"if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched:",
"True matched = [] onlyOne = [] onlyTwo = [] for tableName, tableInfo",
"[] onlyTwo = [] for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if",
"dataMatched: matches = False sys.stdout.write('Different Data for Table: {} in row {}\\n'.format(tableName, rowNum",
"tableName) def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql = \"SELECT *",
"in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self,",
"matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {} {} {} but in {}",
"in row {}\\n'.format(tableName, rowNum + 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches =",
"db) if not dataMatched: matches = False sys.stdout.write('Different Data for Table: {} in",
"if len(rows) > 0: cursor2 = db.conn.cursor() cursor2.execute(sql) for rowNum, row in enumerate(rows):",
"(row is None) or (row2 is None): return False, rowNum for col in",
"onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in {}",
"= TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db): cursor = self.conn.cursor() sql =",
"cursor.execute(\"SELECT name FROM sqlite_master WHERE type =\\'table\\' AND name NOT LIKE \\'sqlite_%\\'\") rows",
"> 0: tableNames = [] for row in rows: tableNames.append(row[0]) for tableName in",
"LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0: tableNames = [] for",
"****************\\n\".format(len(onlyOne), self.name)) for table in onlyOne: sys.stdout.write(\"Table: {}\\n\".format(table)) if len(onlyTwo) > 0: sys.stdout.write(\"***************",
"if (row is None) or (row2 is None): return False, rowNum for col",
"matches = False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched)))",
"db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if",
"tableNames = [] for row in rows: tableNames.append(row[0]) for tableName in tableNames: self.tables[tableName]",
"for tableName in tableNames: self.tables[tableName] = TableInfo(self.conn, tableName) def compareTables(self, tableName, numColumns, db):",
"def __init__(self, name): self.name = name self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory",
"= sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor",
"self.tables = {} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor()",
"matches = False onlyOne.append(tableName) for tableName, tableInfo in db.tables.items(): if tableName not in",
"not in self.tables: matches = False onlyTwo.append(tableName) if len(matched) > 0: sys.stdout.write(\"*************** {}",
"for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName) if tableInfo2 is not None:",
"{}\\n\".format(table.toStr(True))) if len(onlyOne) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyOne), self.name))",
"row2 = cursor2.fetchone() if (row is None) or (row2 is None): return False,",
"rowNum for col in range(numColumns): if row[col] != row2[col]: return False, rowNum return",
"tableInfo.compare(tableInfo2): if tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not",
"name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0: tableNames =",
"+ 1)) else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {}",
"matched = [] onlyOne = [] onlyTwo = [] for tableName, tableInfo in",
"return False, rowNum return True, 0 return False, 0 def compare(self, db): matches",
"len(onlyTwo) > 0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table",
"tableInfo.numRows < 1000: dataMatched, rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches",
"= {} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT",
"rowNum = self.compareTables(tableName, len(tableInfo.columns), db) if not dataMatched: matches = False sys.stdout.write('Different Data",
"self.conn = sqlite3.connect(name) self.tables = {} self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore')",
"else: matched.append(tableInfo) else: matched.append(tableInfo) else: matches = False sys.stdout.write('Different Table: {} {} {}",
"but in {} {}\\n'.format(tableName, self.name, tableInfo.toStr(False), db.name, tableInfo2.toStr(False))) else: matches = False onlyOne.append(tableName)",
"sys.stdout.write(\"*************** {} matched tables ****************\\n\".format(len(matched))) for table in matched: sys.stdout.write(\"Table: {}\\n\".format(table.toStr(True))) if len(onlyOne)",
"self.conn.text_factory = lambda x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM",
"AND name NOT LIKE \\'sqlite_%\\'\") rows = cursor.fetchall() if len(rows) > 0: tableNames",
"\"SELECT * FROM '\" + tableName + \"'\" cursor.execute(sql) rows = cursor.fetchall() if",
"x: str(x, 'utf-8', 'ignore') cursor = self.conn.cursor() cursor.execute(\"SELECT name FROM sqlite_master WHERE type",
"0: sys.stdout.write(\"*************** {} tables only in {} ****************\\n\".format(len(onlyTwo), db.name)) for table in onlyTwo:",
"= [] onlyTwo = [] for tableName, tableInfo in self.tables.items(): tableInfo2 = db.tables.get(tableName)"
] |
[
"version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status ::",
"long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements,",
"Multimedia :: Video\", \"Topic :: Software Development :: Libraries\", \"License :: OSI Approved",
"setup from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with",
":: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays using shared",
":: MIT License\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python",
"f.read().splitlines() with open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\",",
"\"Topic :: Software Development :: Libraries\", \"License :: OSI Approved :: MIT License\",",
"open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\") as f: long_description = f.read()",
":: Libraries\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python",
"\"Intended Audience :: Developers\", \"Topic :: Multimedia :: Video\", \"Topic :: Software Development",
"Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing",
"open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines()",
":: 4 - Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia :: Video\",",
"from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\")",
":: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues",
"@portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 -",
"Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia ::",
"Development :: Libraries\", \"License :: OSI Approved :: MIT License\", \"Programming Language ::",
"as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with",
"Audience :: Developers\", \"Topic :: Multimedia :: Video\", \"Topic :: Software Development ::",
"requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\") as",
"extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"Topic",
":: OSI Approved :: MIT License\", \"Programming Language :: Python :: 3.7\", \"Programming",
"\"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience ::",
"= f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\") as f:",
"install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\",",
":: Video\", \"Topic :: Software Development :: Libraries\", \"License :: OSI Approved ::",
"find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements",
"\"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia",
"Libraries\", \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python ::",
"packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience",
"Developers\", \"Topic :: Multimedia :: Video\", \"Topic :: Software Development :: Libraries\", \"License",
"= f.read().splitlines() with open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME>",
"Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy",
"3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays using shared memory\",",
":: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays",
"OSI Approved :: MIT License\", \"Programming Language :: Python :: 3.7\", \"Programming Language",
"= f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev),",
"MIT License\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python ::",
"Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays using",
"\"Topic :: Multimedia :: Video\", \"Topic :: Software Development :: Libraries\", \"License ::",
"setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development",
":: Multimedia :: Video\", \"Topic :: Software Development :: Libraries\", \"License :: OSI",
":: Software Development :: Libraries\", \"License :: OSI Approved :: MIT License\", \"Programming",
"License\", \"Programming Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\",",
"\"Programming Language :: Python :: 3.7\", \"Programming Language :: Python :: 3.8\", ],",
"with open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\",",
"f: requirements = f.read().splitlines() with open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\",",
"3.7\", \"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues",
"import setup from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines()",
"open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\",",
"<filename>setup.py from distutils.core import setup from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f:",
"Python :: 3.7\", \"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\",",
"requirements = f.read().splitlines() with open(\"README.md\") as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\",",
"\"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for",
"f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")),",
"], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays using shared memory\", long_description=long_description,",
"as f: long_description = f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\",",
"classifiers=[ \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"Topic ::",
"- Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia :: Video\", \"Topic ::",
":: Developers\", \"Topic :: Multimedia :: Video\", \"Topic :: Software Development :: Libraries\",",
"keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing queues for numpy arrays using shared memory\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f:",
"from distutils.core import setup from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev",
"Approved :: MIT License\", \"Programming Language :: Python :: 3.7\", \"Programming Language ::",
"with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements =",
"license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\", \"Intended",
"queues arrays\", description=\"Multiprocessing queues for numpy arrays using shared memory\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/portugueslab/arrayqueues\",",
"author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4 - Beta\",",
"\"License :: OSI Approved :: MIT License\", \"Programming Language :: Python :: 3.7\",",
"arrays\", description=\"Multiprocessing queues for numpy arrays using shared memory\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/portugueslab/arrayqueues\", )",
"Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia :: Video\", \"Topic :: Software",
":: 3.7\", \"Programming Language :: Python :: 3.8\", ], keywords=\"multiprocessing queues arrays\", description=\"Multiprocessing",
"f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\")",
"Software Development :: Libraries\", \"License :: OSI Approved :: MIT License\", \"Programming Language",
"f.read() setup( name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[",
"4 - Beta\", \"Intended Audience :: Developers\", \"Topic :: Multimedia :: Video\", \"Topic",
"name=\"arrayqueues\", version=\"1.3.0\", author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status",
"as f: requirements = f.read().splitlines() with open(\"README.md\") as f: long_description = f.read() setup(",
"author=\"<NAME> @portugueslab\", author_email=\"<EMAIL>\", license=\"MIT\", packages=find_namespace_packages(exclude=(\"docs\", \"tests*\")), install_requires=requirements, extras_require=dict(dev=requirements_dev), classifiers=[ \"Development Status :: 4",
"f.read().splitlines() with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\") as f: long_description",
"with open(\"requirements.txt\") as f: requirements = f.read().splitlines() with open(\"README.md\") as f: long_description =",
"distutils.core import setup from setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev =",
"Video\", \"Topic :: Software Development :: Libraries\", \"License :: OSI Approved :: MIT",
"setuptools import find_namespace_packages with open(\"requirements_dev.txt\") as f: requirements_dev = f.read().splitlines() with open(\"requirements.txt\") as"
] |
[
"different altitudes. The biker starts his trip on point 0 with altitude equal",
"altitudes. The biker starts his trip on point 0 with altitude equal 0.",
"the net gain in altitude between points i and i + 1 for",
"are given an integer array gain of length n where gain[i] is the",
"< n). Return the highest altitude of a point. Example 1: Input: gain",
"Return the highest altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7]",
"The road trip consists of n + 1 points at different altitudes. The",
"where gain[i] is the net gain in altitude between points i and i",
"<reponame>vanigupta20024/Programming-Challenges<filename>FindHighestAltitude.py ''' There is a biker going on a road trip. The road",
"n + 1 points at different altitudes. The biker starts his trip on",
"trip. The road trip consists of n + 1 points at different altitudes.",
"points at different altitudes. The biker starts his trip on point 0 with",
"biker going on a road trip. The road trip consists of n +",
"class Solution: def largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)):",
"of n + 1 points at different altitudes. The biker starts his trip",
"1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for i in",
"a biker going on a road trip. The road trip consists of n",
"Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest",
"a road trip. The road trip consists of n + 1 points at",
"at different altitudes. The biker starts his trip on point 0 with altitude",
"array gain of length n where gain[i] is the net gain in altitude",
"altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self, gain:",
"are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int])",
"equal 0. You are given an integer array gain of length n where",
"-> int: for i in range(1, len(gain)): gain[i] += gain[i - 1] if",
"1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution:",
"gain in altitude between points i and i + 1 for all (0",
"in altitude between points i and i + 1 for all (0 <=",
"i + 1 for all (0 <= i < n). Return the highest",
"i < n). Return the highest altitude of a point. Example 1: Input:",
"biker starts his trip on point 0 with altitude equal 0. You are",
"= [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.",
"0. You are given an integer array gain of length n where gain[i]",
"a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes",
"[-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. '''",
"Solution: def largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)): gain[i]",
"There is a biker going on a road trip. The road trip consists",
"altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation:",
"1 points at different altitudes. The biker starts his trip on point 0",
"length n where gain[i] is the net gain in altitude between points i",
"highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for",
"altitude equal 0. You are given an integer array gain of length n",
"def largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)): gain[i] +=",
"the highest altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output:",
"road trip. The road trip consists of n + 1 points at different",
"an integer array gain of length n where gain[i] is the net gain",
"given an integer array gain of length n where gain[i] is the net",
"on a road trip. The road trip consists of n + 1 points",
"is the net gain in altitude between points i and i + 1",
"points i and i + 1 for all (0 <= i < n).",
"is a biker going on a road trip. The road trip consists of",
"i and i + 1 for all (0 <= i < n). Return",
"largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)): gain[i] += gain[i",
"his trip on point 0 with altitude equal 0. You are given an",
"range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) < 0: return 0",
"for all (0 <= i < n). Return the highest altitude of a",
"List[int]) -> int: for i in range(1, len(gain)): gain[i] += gain[i - 1]",
"gain[i] += gain[i - 1] if max(gain) < 0: return 0 return max(gain)",
"point 0 with altitude equal 0. You are given an integer array gain",
"i in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) < 0:",
"gain: List[int]) -> int: for i in range(1, len(gain)): gain[i] += gain[i -",
"n where gain[i] is the net gain in altitude between points i and",
"[0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) ->",
"gain of length n where gain[i] is the net gain in altitude between",
"consists of n + 1 points at different altitudes. The biker starts his",
"''' There is a biker going on a road trip. The road trip",
"altitude between points i and i + 1 for all (0 <= i",
"+ 1 points at different altitudes. The biker starts his trip on point",
"(0 <= i < n). Return the highest altitude of a point. Example",
"going on a road trip. The road trip consists of n + 1",
"int: for i in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain)",
"net gain in altitude between points i and i + 1 for all",
"len(gain)): gain[i] += gain[i - 1] if max(gain) < 0: return 0 return",
"gain[i] is the net gain in altitude between points i and i +",
"trip on point 0 with altitude equal 0. You are given an integer",
"for i in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) <",
"n). Return the highest altitude of a point. Example 1: Input: gain =",
"1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The",
"road trip consists of n + 1 points at different altitudes. The biker",
"integer array gain of length n where gain[i] is the net gain in",
"all (0 <= i < n). Return the highest altitude of a point.",
"is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for i",
"with altitude equal 0. You are given an integer array gain of length",
"+ 1 for all (0 <= i < n). Return the highest altitude",
"between points i and i + 1 for all (0 <= i <",
"You are given an integer array gain of length n where gain[i] is",
"0 with altitude equal 0. You are given an integer array gain of",
"in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) < 0: return",
"point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are",
"The biker starts his trip on point 0 with altitude equal 0. You",
"of length n where gain[i] is the net gain in altitude between points",
"''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for i in range(1,",
"The highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int:",
"and i + 1 for all (0 <= i < n). Return the",
"Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6].",
"1 for all (0 <= i < n). Return the highest altitude of",
"The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self,",
"highest altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1",
"starts his trip on point 0 with altitude equal 0. You are given",
"on point 0 with altitude equal 0. You are given an integer array",
"<= i < n). Return the highest altitude of a point. Example 1:",
"trip consists of n + 1 points at different altitudes. The biker starts",
"Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class",
"of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The",
"gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is",
"Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def"
] |
[
"**kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string -> (:class:Function) \"\"\"",
"F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5 hash of @string, returning",
"zero bytes and high-bit-set bytes to octal sequences (\\nnn) and doubles backslashes. ->",
"\"\"\" return F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary data",
"bytes and high-bit-set bytes to octal sequences (\\nnn) and doubles backslashes. -> (:class:Function)",
"Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from",
"representation. Supported formats are: base64, hex, escape. escape converts zero bytes and high-bit-set",
"self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_ to @for_",
"**kwargs): \"\"\" Set bit in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value,",
"octet_length(self, **kwargs): \"\"\" Number of bytes in binary string -> (:class:Function) \"\"\" return",
"from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps",
"**kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP,",
"as in encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset,",
"@substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def",
"*exps), **kwargs) def position(self, substring): \"\"\" Location of specified @substring -> (:class:Function) \"\"\"",
"from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs):",
"def get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string -> (:class:Function) \"\"\" return",
"same as in encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self,",
"string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if",
"__slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string, bytes): return",
"\"\"\" Length of binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self,",
"of binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\"",
"= self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both: exp = Clause('both', exp)",
"textual representation in string. Options for format are same as in encode. ->",
"textual representation. Supported formats are: base64, hex, escape. escape converts zero bytes and",
"Calculates the MD5 hash of @string, returning the result in hexadecimal. -> (:class:Function)",
"-> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from',",
"def decode(self, format, **kwargs): \"\"\" Decode binary data from textual representation in string.",
"exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location",
"for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps =",
"-> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both:",
"in string. Options for format are same as in encode. -> (:class:Function) \"\"\"",
"of @string, returning the result in hexadecimal. -> (:class:Function) \"\"\" return F.md5(self, **kwargs)",
"format, **kwargs): \"\"\" Decode binary data from textual representation in string. Options for",
"return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes in",
"of specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in',",
"in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset,",
"**kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in @string -> (:class:Function)",
"'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_ to",
"format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary data from textual representation",
"\"\"\" `Binary Logic and Operations` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT)",
"\"\"\" Set byte in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs)",
"**kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\"",
"the longest string containing only the bytes in @bytes_ from the start and",
"**kwargs): \"\"\" Remove the longest string containing only the bytes in @bytes_ from",
"position(self, substring): \"\"\" Location of specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring)",
"from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not None: exps.append(Expression(self.empty,",
"= ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self, string):",
"bytes in @bytes_ from the start and end of the string -> (:class:Expression)",
"in binary string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring,",
"*exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest string containing",
"F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string ->",
"offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in @string ->",
"**kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string -> (:class:Function) \"\"\"",
"self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes in binary string",
"String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs)",
"'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location of",
"exps.append(Expression(self.empty, 'from', from_)) if for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring',",
"None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_,",
"Set bit in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def",
"from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self,",
"Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary data into a",
"Decode binary data from textual representation in string. Options for format are same",
"(:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None,",
"-> (:class:Function) \"\"\" exps = [] if from_ is not None: exps.append(Expression(self.empty, 'from',",
"a textual representation. Supported formats are: base64, hex, escape. escape converts zero bytes",
"from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value,",
"Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location of specified @substring ->",
"* __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def",
"= '||' def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def",
"return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression)",
"F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in",
"BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string, bytes):",
"exp = Expression(bytes_, 'from', self) if both: exp = Clause('both', exp) return Function('trim',",
"Logic and Operations` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\"",
"return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte",
"**kwargs): \"\"\" Set byte in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value,",
"and high-bit-set bytes to octal sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\"",
"-> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs):",
"get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string -> (:class:Function) \"\"\" return F.get_bit(self,",
"representation in string. Options for format are same as in encode. -> (:class:Function)",
"overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring =",
"Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes in binary",
"= self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\"",
"\"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\"",
"**kwargs): \"\"\" Number of bytes in binary string -> (:class:Function) \"\"\" return Function('octet_length',",
"converts zero bytes and high-bit-set bytes to octal sequences (\\nnn) and doubles backslashes.",
"-> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract",
"F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary data from textual",
"self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest string",
"Remove the longest string containing only the bytes in @bytes_ from the start",
"offset, **kwargs): \"\"\" Extract bit from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset,",
"data into a textual representation. Supported formats are: base64, hex, escape. escape converts",
"and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self, format,",
"not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self,",
"**kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes in binary string -> (:class:Function)",
"(:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit",
"return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string",
"Encode binary data into a textual representation. Supported formats are: base64, hex, escape.",
"of the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from',",
"(\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self,",
"-> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5",
"return F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary data from",
"self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes",
"md5(self, **kwargs): \"\"\" Calculates the MD5 hash of @string, returning the result in",
"Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring ->",
"offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in @string",
"length(self, **kwargs): \"\"\" Length of binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs)",
"bit from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset,",
"new_value, **kwargs): \"\"\" Set byte in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset,",
"Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_",
"(:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set",
"binary data into a textual representation. Supported formats are: base64, hex, escape. escape",
"Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary",
"\"\"\" Extract byte from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def",
"for format are same as in encode. -> (:class:Function) \"\"\" return F.decode(self, format,",
"format are same as in encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs)",
"\"\"\" Remove the longest string containing only the bytes in @bytes_ from the",
"\"\"\" Set bit in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs)",
"string containing only the bytes in @bytes_ from the start and end of",
"Extract byte from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self,",
"psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple()",
"Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest",
"isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\" String concatenation",
"encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\"",
"string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self,",
"octal sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs)",
"(:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\"",
"http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic):",
"specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self))",
"return string def concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string",
"bit in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self,",
"concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def",
"hex, escape. escape converts zero bytes and high-bit-set bytes to octal sequences (\\nnn)",
"def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_ to @for_ ->",
"\"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit",
"@string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the",
"from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_ to @for_ -> (:class:Function) \"\"\"",
"('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if",
"\"\"\" Location of specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position',",
"exp) return Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary data",
"\"\"\" Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty,",
"is not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not None: exps.append(Expression(self.empty, 'for',",
"**kwargs): \"\"\" Encode binary data into a textual representation. Supported formats are: base64,",
"[] if from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not",
"@bytes_ from the start and end of the string -> (:class:Expression) \"\"\" bytes_",
"return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring",
"The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import * __all__",
"\"\"\" Decode binary data from textual representation in string. Options for format are",
"binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates",
"Length of binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs):",
"= self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty,",
"for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\"",
"**kwargs): \"\"\" Decode binary data from textual representation in string. Options for format",
"None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return",
"sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def",
"\"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte from",
"F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of binary @string ->",
"format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string -> (:class:Function)",
"set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in @string -> (:class:Function) \"\"\" return",
"@for_ -> (:class:Function) \"\"\" exps = [] if from_ is not None: exps.append(Expression(self.empty,",
"-> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs):",
"\"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both: exp =",
"**kwargs): \"\"\" Extract bit from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs)",
"escape. escape converts zero bytes and high-bit-set bytes to octal sequences (\\nnn) and",
"def concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string)",
"\"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit from",
"MD5 hash of @string, returning the result in hexadecimal. -> (:class:Function) \"\"\" return",
"Supported formats are: base64, hex, escape. escape converts zero bytes and high-bit-set bytes",
"offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of binary @string -> (:class:Function)",
"the MD5 hash of @string, returning the result in hexadecimal. -> (:class:Function) \"\"\"",
"if both: exp = Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self, format,",
"string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number",
"not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not None: exps.append(Expression(self.empty, 'for', for_))",
"return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in",
"**kwargs) def position(self, substring): \"\"\" Location of specified @substring -> (:class:Function) \"\"\" substring",
"return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location of specified @substring",
"if for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps),",
"new_value, **kwargs): \"\"\" Set bit in @string -> (:class:Function) \"\"\" return F.set_bit(self, offset,",
"return Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring",
"\"\"\" Extract bit from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def",
"\"\"\" String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string,",
"escape converts zero bytes and high-bit-set bytes to octal sequences (\\nnn) and doubles",
"offset, new_value, **kwargs): \"\"\" Set bit in @string -> (:class:Function) \"\"\" return F.set_bit(self,",
"encode(self, format, **kwargs): \"\"\" Encode binary data into a textual representation. Supported formats",
"byte from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset,",
"end of the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_,",
"to octal sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format,",
"cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP =",
"substring): \"\"\" Location of specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return",
"return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove",
"**kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5 hash of @string, returning the",
"substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_:",
"Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\",",
"Location of specified @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring,",
"self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function)",
"'from', self) if both: exp = Clause('both', exp) return Function('trim', exp, **kwargs) def",
"the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self)",
"return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of binary @string",
"Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs)",
"if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\" String",
"from cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP",
"base64, hex, escape. escape converts zero bytes and high-bit-set bytes to octal sequences",
"for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\"",
"exps = [] if from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if for_",
"<NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import",
"return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs): \"\"\" Extract bit from @string",
"is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def",
"the start and end of the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_)",
"(:class:Function) \"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5 hash",
"[self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay',",
"-> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract",
"offset, new_value, **kwargs): \"\"\" Set byte in @string -> (:class:Function) \"\"\" return F.set_byte(self,",
"substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts substring from @from_ to @for_ -> (:class:Function)",
"(MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',) class",
"byte in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self,",
"-> (:class:Function) \"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self,",
"in @bytes_ from the start and end of the string -> (:class:Expression) \"\"\"",
"trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest string containing only the bytes",
"2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions",
"\"\"\" Number of bytes in binary string -> (:class:Function) \"\"\" return Function('octet_length', self,",
"= Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode",
"get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string -> (:class:Function) \"\"\" return F.get_byte(self,",
"\"\"\" Calculates the MD5 hash of @string, returning the result in hexadecimal. ->",
"'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def",
"only the bytes in @bytes_ from the start and end of the string",
"to @for_ -> (:class:Function) \"\"\" exps = [] if from_ is not None:",
"string. Options for format are same as in encode. -> (:class:Function) \"\"\" return",
"self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both: exp = Clause('both', exp) return",
"set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in @string -> (:class:Function) \"\"\" return",
"containing only the bytes in @bytes_ from the start and end of the",
"both=False, **kwargs): \"\"\" Remove the longest string containing only the bytes in @bytes_",
"\"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of binary",
"Number of bytes in binary string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs)",
"(:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of",
"**kwargs): \"\"\" Extract byte from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs)",
"'from', from_)) if for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\",",
"def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in @string -> (:class:Function) \"\"\"",
"both: exp = Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self, format, **kwargs):",
"-> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\" Length",
"if from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is not None:",
"and Operations` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\" import",
"**kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self,",
"'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs):",
"bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\" String concatenation ->",
"(:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\"",
"data from textual representation in string. Options for format are same as in",
"Set byte in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def",
"are: base64, hex, escape. escape converts zero bytes and high-bit-set bytes to octal",
"class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string,",
"-> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\"",
"def octet_length(self, **kwargs): \"\"\" Number of bytes in binary string -> (:class:Function) \"\"\"",
"psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\"",
"**kwargs) def length(self, **kwargs): \"\"\" Length of binary @string -> (:class:Function) \"\"\" return",
"def encode(self, format, **kwargs): \"\"\" Encode binary data into a textual representation. Supported",
"F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in @string",
"= Expression(bytes_, 'from', self) if both: exp = Clause('both', exp) return Function('trim', exp,",
"and end of the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp =",
"= self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of",
"(:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte",
"def position(self, substring): \"\"\" Location of specified @substring -> (:class:Function) \"\"\" substring =",
"@from_ to @for_ -> (:class:Function) \"\"\" exps = [] if from_ is not",
"(:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary",
"= tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string)",
"return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5 hash of @string,",
"from the start and end of the string -> (:class:Expression) \"\"\" bytes_ =",
"**kwargs): \"\"\" Length of binary @string -> (:class:Function) \"\"\" return F.length(self, **kwargs) def",
"start and end of the string -> (:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp",
"_cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs):",
"\"\"\" return F.length(self, **kwargs) def md5(self, **kwargs): \"\"\" Calculates the MD5 hash of",
"CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string",
"def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string,",
"-> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\" Decode",
"`Binary Logic and Operations` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde",
"if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring):",
"def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring",
"string, **kwargs) def octet_length(self, **kwargs): \"\"\" Number of bytes in binary string ->",
"substring from @from_ to @for_ -> (:class:Function) \"\"\" exps = [] if from_",
"Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the",
"new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in @string ->",
"concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string = self._cast_bytes(string) return",
"\"\"\" exps = [] if from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if",
"high-bit-set bytes to octal sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return",
"Expression(bytes_, 'from', self) if both: exp = Clause('both', exp) return Function('trim', exp, **kwargs)",
"© The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import *",
"@string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs): \"\"\"",
"def length(self, **kwargs): \"\"\" Length of binary @string -> (:class:Function) \"\"\" return F.length(self,",
"substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs):",
"(:class:Expression) \"\"\" bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both: exp",
"@substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring,",
"for_)) return Function('overlay', Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location of specified",
"bytes_ = self._cast_bytes(bytes_) exp = Expression(bytes_, 'from', self) if both: exp = Clause('both',",
"'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return Function('overlay', Clause(\"\", *exps),",
"(:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self, **kwargs):",
"import psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ =",
"string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self, string, **kwargs): \"\"\"",
"--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from",
"\"\"\" substring = self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None,",
"def get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string -> (:class:Function) \"\"\" return",
"tuple() CONCAT_OP = '||' def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return",
"from textual representation in string. Options for format are same as in encode.",
"backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self, format, **kwargs): \"\"\"",
"@string -> (:class:Function) \"\"\" return F.get_byte(self, offset, **kwargs) def set_bit(self, offset, new_value, **kwargs):",
"binary string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring, from_,",
"def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest string containing only the",
"\"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None, **kwargs): \"\"\" Replace",
"Clause(\"\", *exps), **kwargs) def position(self, substring): \"\"\" Location of specified @substring -> (:class:Function)",
"Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing',",
"\"\"\" import psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__",
"new_value, **kwargs) def length(self, **kwargs): \"\"\" Length of binary @string -> (:class:Function) \"\"\"",
"format, **kwargs): \"\"\" Encode binary data into a textual representation. Supported formats are:",
"**kwargs): \"\"\" Calculates the MD5 hash of @string, returning the result in hexadecimal.",
"(:class:Function) \"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))]",
"exp = Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\"",
"__all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||' def _cast_bytes(self,",
"bytes_, both=False, **kwargs): \"\"\" Remove the longest string containing only the bytes in",
"return Function('trim', exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary data into",
"from_)) if for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self,",
"**kwargs) def trim(self, bytes_, both=False, **kwargs): \"\"\" Remove the longest string containing only",
"are same as in encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def",
"string def concat(self, string, **kwargs): \"\"\" String concatenation -> (:class:Expression) \"\"\" string =",
"longest string containing only the bytes in @bytes_ from the start and end",
"Options for format are same as in encode. -> (:class:Function) \"\"\" return F.decode(self,",
"exp, **kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary data into a textual",
"in @string -> (:class:Function) \"\"\" return F.set_byte(self, offset, new_value, **kwargs) def length(self, **kwargs):",
"@string -> (:class:Function) \"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value,",
"Operations` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 <NAME> © The MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions",
"bytes in binary string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self,",
"from @from_ to @for_ -> (:class:Function) \"\"\" exps = [] if from_ is",
"import * __all__ = ('BinaryLogic',) class BinaryLogic(BaseLogic): __slots__ = tuple() CONCAT_OP = '||'",
"for_=None, **kwargs): \"\"\" Extracts substring from @from_ to @for_ -> (:class:Function) \"\"\" exps",
"the bytes in @bytes_ from the start and end of the string ->",
"bytes to octal sequences (\\nnn) and doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self,",
"def set_bit(self, offset, new_value, **kwargs): \"\"\" Set bit in @string -> (:class:Function) \"\"\"",
"decode(self, format, **kwargs): \"\"\" Decode binary data from textual representation in string. Options",
"= [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_)) return",
"'||' def _cast_bytes(self, string): if isinstance(string, bytes): return psycopg2.extensions.Binary(string) return string def concat(self,",
"for_ is not None: exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs)",
"= [] if from_ is not None: exps.append(Expression(self.empty, 'from', from_)) if for_ is",
"F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string ->",
"self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for',",
"in encode. -> (:class:Function) \"\"\" return F.decode(self, format, **kwargs) def get_bit(self, offset, **kwargs):",
"def md5(self, **kwargs): \"\"\" Calculates the MD5 hash of @string, returning the result",
"(:class:Function) \"\"\" exps = [] if from_ is not None: exps.append(Expression(self.empty, 'from', from_))",
"of bytes in binary string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def",
"exps.append(Expression(self.empty, 'for', for_)) return Function('substring', Clause(\"\", self, *exps), **kwargs) def trim(self, bytes_, both=False,",
"Extract bit from @string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self,",
"Extracts substring from @from_ to @for_ -> (:class:Function) \"\"\" exps = [] if",
"License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import * __all__ = ('BinaryLogic',)",
"string -> (:class:Function) \"\"\" return Function('octet_length', self, **kwargs) def overlay(self, substring, from_, for_=None,",
"formats are: base64, hex, escape. escape converts zero bytes and high-bit-set bytes to",
"\"\"\" substring = self._cast_bytes(substring) exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if",
"into a textual representation. Supported formats are: base64, hex, escape. escape converts zero",
"substring, from_, for_=None, **kwargs): \"\"\" Replace @substring -> (:class:Function) \"\"\" substring = self._cast_bytes(substring)",
"@string -> (:class:Function) \"\"\" return F.get_bit(self, offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\"",
"MIT License (MIT) http://github.com/jaredlunde \"\"\" import psycopg2.extensions from cargo.expressions import * __all__ =",
"hash of @string, returning the result in hexadecimal. -> (:class:Function) \"\"\" return F.md5(self,",
"offset, **kwargs): \"\"\" Extract byte from @string -> (:class:Function) \"\"\" return F.get_byte(self, offset,",
"\"\"\" Extracts substring from @from_ to @for_ -> (:class:Function) \"\"\" exps = []",
"binary data from textual representation in string. Options for format are same as",
"\"\"\" return F.set_bit(self, offset, new_value, **kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set",
"self._cast_bytes(substring) return Function('position', Expression(substring, 'in', self)) def substring(self, from_=None, for_=None, **kwargs): \"\"\" Extracts",
"doubles backslashes. -> (:class:Function) \"\"\" return F.encode(self, format, **kwargs) def decode(self, format, **kwargs):",
"**kwargs) def decode(self, format, **kwargs): \"\"\" Decode binary data from textual representation in",
"**kwargs) def encode(self, format, **kwargs): \"\"\" Encode binary data into a textual representation.",
"\"\"\" Encode binary data into a textual representation. Supported formats are: base64, hex,",
"exps = [self, Expression(self.empty, 'placing', Expression(substring, 'from', from_))] if for_: exps.append(Expression(self.empty, 'for', for_))",
"self) if both: exp = Clause('both', exp) return Function('trim', exp, **kwargs) def encode(self,",
"**kwargs) def set_byte(self, offset, new_value, **kwargs): \"\"\" Set byte in @string -> (:class:Function)",
"-> (:class:Expression) \"\"\" string = self._cast_bytes(string) return Expression(self, self.CONCAT_OP, string, **kwargs) def octet_length(self,",
"offset, **kwargs) def get_byte(self, offset, **kwargs): \"\"\" Extract byte from @string -> (:class:Function)",
"**kwargs): \"\"\" Extracts substring from @from_ to @for_ -> (:class:Function) \"\"\" exps ="
] |
[
"u can get it from getAlbums or create a new album. albumId =",
"str groupId = None # Album ID: str, u can get it from",
"from getAlbums or create a new album. albumId = None # Image's path:",
"CHRLINE() # Group ID: str groupId = None # Album ID: str, u",
"Group ID: str groupId = None # Album ID: str, u can get",
"# Album ID: str, u can get it from getAlbums or create a",
"it from getAlbums or create a new album. albumId = None # Image's",
"<reponame>zbx911/CHRLINE # -*- coding: utf-8 -*- from CHRLINE import * cl = CHRLINE()",
"Album ID: str, u can get it from getAlbums or create a new",
"Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID: {oid}\") cl.addImageToAlbum(groupId,",
"# Image's path: list<str> images = [] for i in images: print(f\"--> Try",
"a new album. albumId = None # Image's path: list<str> images = []",
"albumId = None # Image's path: list<str> images = [] for i in",
"i in images: print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i)",
"str, u can get it from getAlbums or create a new album. albumId",
"or create a new album. albumId = None # Image's path: list<str> images",
"print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID: {oid}\")",
"new album. albumId = None # Image's path: list<str> images = [] for",
"= CHRLINE() # Group ID: str groupId = None # Album ID: str,",
"cl = CHRLINE() # Group ID: str groupId = None # Album ID:",
"None # Album ID: str, u can get it from getAlbums or create",
"Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID: {oid}\") cl.addImageToAlbum(groupId, albumId, oid)",
"coding: utf-8 -*- from CHRLINE import * cl = CHRLINE() # Group ID:",
"getAlbums or create a new album. albumId = None # Image's path: list<str>",
"ID: str groupId = None # Album ID: str, u can get it",
"album. albumId = None # Image's path: list<str> images = [] for i",
"= None # Image's path: list<str> images = [] for i in images:",
"utf-8 -*- from CHRLINE import * cl = CHRLINE() # Group ID: str",
"from CHRLINE import * cl = CHRLINE() # Group ID: str groupId =",
"get it from getAlbums or create a new album. albumId = None #",
"{i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID: {oid}\") cl.addImageToAlbum(groupId, albumId, oid) print(f\"Done.\")",
"images = [] for i in images: print(f\"--> Try to Upload {i}\") oid",
"ID: str, u can get it from getAlbums or create a new album.",
"# -*- coding: utf-8 -*- from CHRLINE import * cl = CHRLINE() #",
"in images: print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<--",
"-*- coding: utf-8 -*- from CHRLINE import * cl = CHRLINE() # Group",
"for i in images: print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId,",
"groupId = None # Album ID: str, u can get it from getAlbums",
"can get it from getAlbums or create a new album. albumId = None",
"Image's path: list<str> images = [] for i in images: print(f\"--> Try to",
"None # Image's path: list<str> images = [] for i in images: print(f\"-->",
"[] for i in images: print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId,",
"# Group ID: str groupId = None # Album ID: str, u can",
"images: print(f\"--> Try to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID:",
"-*- from CHRLINE import * cl = CHRLINE() # Group ID: str groupId",
"CHRLINE import * cl = CHRLINE() # Group ID: str groupId = None",
"= [] for i in images: print(f\"--> Try to Upload {i}\") oid =",
"= None # Album ID: str, u can get it from getAlbums or",
"to Upload {i}\") oid = cl.updateImageToAlbum(groupId, albumId, i) print(f\"<-- OID: {oid}\") cl.addImageToAlbum(groupId, albumId,",
"list<str> images = [] for i in images: print(f\"--> Try to Upload {i}\")",
"create a new album. albumId = None # Image's path: list<str> images =",
"* cl = CHRLINE() # Group ID: str groupId = None # Album",
"path: list<str> images = [] for i in images: print(f\"--> Try to Upload",
"import * cl = CHRLINE() # Group ID: str groupId = None #"
] |