Example #1
0
def add_open_question_command(dbservice: DBService):
    content = input("Question content: ")
    question = {
        constants['CONTENT_KEY']: content,
        constants['TYPE_KEY']: constants['OPEN_QUESTION_KEY']
    }
    dbservice.insert(question)
Example #2
0
def add_closed_question_command(dbservice: DBService):
    content = input("Question content: ")
    num_of_answers = int(input("Number of answers: "))
    answers = []
    for i in range(0, num_of_answers):
        answer = input("answer: ")
        answers.append(answer)
    question = {
        constants['CONTENT_KEY']: content,
        constants['TYPE_KEY']: constants['CLOSED_QUESTION_KEY'],
        constants['ANSWERS_KET']: answers
    }
    dbservice.insert(question)
Example #3
0
    def __init__(self):
        print("Please, fill in database information: ")
        ip = input("IP: ")
        port = int(input("Port: "))
        dbname = input("Database name: ")
        collection = input("Collection name: ")
        user = input("Username: "******"Password: "******"Connection error.")
            exit(1)
        except OperationFailure:
            print("Operation failed.")
            exit(1)

        self.commands = {
            '0': lambda: commands.illegal_choice_command(),
            '1': lambda: commands.add_question_command(self.db_service),
            '2': lambda: commands.delete_command(self.db_service),
            '3': lambda: commands.create_random_test_command(self.db_service),
            '9': lambda: commands.exit_command()
        }
Example #4
0
import logging
import logging.handlers
import tornado.websocket
from tornado.escape import json_encode, json_decode
import hashlib
from dbservice import DBService
from json_keys import *
from tornado.options import define, options, parse_command_line
import json

define('port', default=8000, help='run on the given port', type=int)

clients_online = dict()
i = 0

db_service = DBService.inst()

f = logging.Formatter(fmt='%(levelname)s:%(name)s: %(message)s '
                      '(%(asctime)s; %(filename)s:%(lineno)d)',
                      datefmt="%Y-%m-%d %H:%M:%S")
handlers = [
    logging.handlers.RotatingFileHandler('rotated.log',
                                         encoding='utf8',
                                         maxBytes=100000,
                                         backupCount=1),
    logging.StreamHandler()
]
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
for h in handlers:
    h.setFormatter(f)
Example #5
0
def main():
    csv_file, rate_overrides = get_arguments()
    reader = csv.DictReader(csv_file)
    if reader.fieldnames != [
            'State', 'System Size (kW)', 'Estimated Year 1 Production (kWh)'
    ]:
        raise Exception(
            "Column names : {} did not match expected column names".format(
                reader.fieldnames))
    dbservice = DBService()
    discount_rate = 0.05

    # Get cost structure info from DB
    portfolio_cost = dbservice.get_portfolio_cost()
    states = dbservice.get_states()
    upfront_incentives = dbservice.get_incentives()
    costs = dbservice.get_costs()
    per_kwh_rates = dbservice.get_per_kwh_rates()
    for state, rate in per_kwh_rates.iteritems():
        if rate_overrides[state]:
            per_kwh_rates[state] = rate_overrides[state]

    # assemble state information into simple dict for each state
    state_information = {
        state: {
            'per_system_cost':
            costs[state]['per_system_costs'],
            'per_kw_cost':
            costs[state]['per_kw_costs'],
            'incentives':
            upfront_incentives[state],
            'per_kwh_rates':
            per_kwh_rates[state],
            'maintenance_costs':
            costs[state]['maintenance_costs'],
            'maintenance_cost_inflation':
            costs[state]['maintenance_cost_inflation']
        }
        for state in states
    }

    # instantiating counters
    total_state_system_size = {state: 0 for state in states}
    total_state_system_count = {state: 0 for state in states}
    total_state_costs = {state: 0 for state in states}
    total_state_cash_streams = {state: [0] * 240 for state in states}

    # Read values from the csv into System objects
    for row in reader:
        state = row['State']
        size = float(row['System Size (kW)'])
        first_year_production = float(row['Estimated Year 1 Production (kWh)'])

        total_state_system_count[state] += 1
        total_state_system_size[state] += size
        if state not in state_information.keys():
            raise Exception(
                'No state information found in database for the following state: {}'
                .format(state))
        system = System(size, first_year_production, state_information[state])
        total_state_costs[state] += system.upfront_cost
        total_state_cash_streams[state] = numpy.add(
            total_state_cash_streams[state], system.monthly_payment_stream)

    systems_in_portfolio = reduce((lambda x, y: x + y),
                                  total_state_system_count.values())

    # distribute the portfolio cost among the states proportional to the number of systems in that state
    for state in states:
        total_state_costs[state] += portfolio_cost * total_state_system_count[
            state] / systems_in_portfolio

    # get portfolio level values
    total_cash_stream = reduce((lambda x, y: numpy.add(x, y)),
                               total_state_cash_streams.values())
    total_portfolio_cost = sum(total_state_costs.values())
    portfolio_npv = numpy.npv(discount_rate / 12, [-total_portfolio_cost] +
                              total_cash_stream.tolist())
    portfolio_pv = numpy.npv(discount_rate / 12,
                             [0] + total_cash_stream.tolist())

    # calculate state values
    state_pv = {
        state: numpy.npv(discount_rate / 12,
                         [0] + total_state_cash_streams[state].tolist())
        for state in states
    }
    state_npv = {
        state: numpy.npv(discount_rate / 12, [-total_state_costs[state]] +
                         total_state_cash_streams[state].tolist())
        for state in states
    }

    # output results
    output_portfolio_results(portfolio_npv, portfolio_pv, total_portfolio_cost)
    output_state_results("PV", states, state_pv, total_state_system_count,
                         total_state_system_size)
    output_state_results("Cost", states, total_state_costs,
                         total_state_system_count, total_state_system_size)
    output_state_results("NPV", states, state_npv, total_state_system_count,
                         total_state_system_size)
Example #6
0
app.config.update(
    dict(
        DATABASE='webcheck.db',
        DEBUG=True,
        SECRET_KEY='development key',
        USERNAME='******',
        PASSWORD='******',
        SCHEDULER_TIME_INTERVAL=60,
        NOTIFICATOR_EMAIL='',
        NOTIFICATOR_USER='',
        NOTIFICATOR_PASSWORD='',
        NOTIFICATOR_MAIL_SERVER='',
        NOTIFICATOR_EMAIL_TO='',
    ))

dbservice = DBService()
dbservice.app = app
web_check_scheduler = WebCheckScheduler(app, dbservice)


# Route functions
@app.route('/check_db_state', methods=['GET'])
def check_db_state():
    sites_number = len(dbservice.query_db('SELECT * FROM sites'))

    if sites_number == 0:
        dbservice.execute_db('UPDATE dbutil SET db_code=? WHERE id=?', [0, 1])

    return jsonify(dbservice.query_db('SELECT * FROM dbutil'))

Example #7
0
# App config
app.config.update(dict(
	DATABASE = 'webcheck.db',
	DEBUG = True,
	SECRET_KEY = 'development key',
	USERNAME = '******',
	PASSWORD = '******',
	SCHEDULER_TIME_INTERVAL=60,
	NOTIFICATOR_EMAIL = '',
	NOTIFICATOR_USER = '',
	NOTIFICATOR_PASSWORD = '',	
	NOTIFICATOR_MAIL_SERVER = '',
	NOTIFICATOR_EMAIL_TO = '',
))

dbservice = DBService()
dbservice.app = app
web_check_scheduler = WebCheckScheduler(app, dbservice)

# Route functions
@app.route('/check_db_state', methods = ['GET'])
def check_db_state():
    sites_number = len(dbservice.query_db('SELECT * FROM sites'))	
 	
    if sites_number == 0:	
        dbservice.execute_db('UPDATE dbutil SET db_code=? WHERE id=?', [0, 1])        
	
    return jsonify( dbservice.query_db('SELECT * FROM dbutil') )

@app.route('/set_db_state', methods = ['POST'])
def set_db_state():	
Example #8
0
def delete_command(dbservice: DBService):
    content = input("Content of the question to be deleted: ")
    dbservice.delete_question(content)
Example #9
0
def create_random_test_command(dbservice: DBService):

    open_questions = dbservice.get_open_questions()
    closed_questions = dbservice.get_closed_questions()
    num_open_questions = int(input("Number of open questions: "))
    num_closed_questions = int(input("Number of closed questions: "))
    output_file = input("name of the output file: ")

    def shuffle_answers(answers):
        ans = answers

        result = []
        for i in range(0, len(answers)):
            length = len(ans)
            num = random.randint(0, length - 1)
            answer = ans[num]
            result.append(answer)
            del ans[num]

        return result

    def fetch_answers(question):
        answers_key = constants['ANSWERS_KET']
        answers = question[answers_key]
        answers = shuffle_answers(answers)
        return answers

    def to_ascii(i):
        return chr(i + 97) + ")"

    def write_closed_question(number, question):
        with open(output_file, 'a') as f:
            f.write(str(number) + ". " + question['content'] + "\n")
            answers = fetch_answers(question)
            for i, answer in enumerate(answers):
                letter = to_ascii(i)
                f.write(letter + " " + answer + "\n")

    def write_open_question(number, question):
        with open(output_file, 'a') as f:
            f.write(str(number) + ". " + question['content'] + "\n")

    def pop_random_question(list_of_questions):
        num = random.randint(0, len(list_of_questions) - 1)
        question = list_of_questions[num]
        del list_of_questions[num]
        return question

    def write_closed_questions():
        for i in range(0, num_closed_questions):
            question = pop_random_question(closed_questions)
            write_closed_question(i + 1, question)

    def write_open_questions():
        for i in range(0, num_open_questions):
            question = pop_random_question(open_questions)
            write_open_question(num_closed_questions + i + 1, question)

    if num_open_questions > len(open_questions):
        raise NotEnoughOpenQuestionsError
    if num_closed_questions > len(closed_questions):
        raise NotEnoughClosedQuestionsError
    write_closed_questions()
    write_open_questions()