Example #1
0
 def run(self):
     init_logging()
     self.application = FireflyHTTPApplication(self.matcher, self.timeout)
     self.proxy = HTTPProxyServer(self.ip,
                                  self.port,
                                  self.application,
                                  log=None)
     self.proxy.run()
Example #2
0
    def handle(self, *args, **options):
        """Runs command."""
        init_logging()
        logger.debug("Starting processor...")

        try:
            AnalysisManager().run()
        except KeyboardInterrupt:
            print "Exiting... (requested by user)"
Example #3
0
    def handle(self, *args, **options):
        """Runs command."""
        init_logging()
        logger.debug("Starting processor...")

        try:
            AnalysisManager().run()
        except KeyboardInterrupt:
            print "Exiting... (requested by user)"
Example #4
0
 def run(self):
     init_logging()
     rootdir = self.coordinator.get('rootdir')
     confdata = self.coordinator.get('confdata')
     icon = os.path.join(rootdir, confdata['icon_path'])
     SysTrayIcon(
         icon,
         u'萤火虫翻墙代理',
         ((u'翻墙浏览', None, self.sytray_launch_browser),
          (u'配置代理', None, self.systray_open_webadmin),
          (u'退出', None, 'QUIT')),
         on_quit=self.systray_quit,
         default_menu_index=1,
     )
Example #5
0
 def run(self):
     init_logging()
     rootdir = self.coordinator.get('rootdir')
     confdata = self.coordinator.get('confdata')
     webpath = os.path.join(rootdir, confdata['web_path'])
     os.chdir(webpath)
     
     from webpanel import app
     try:
         WSGIServer((self.ip, self.port), application=app.create_app(self.coordinator), log=None).serve_forever()
     except socket.error, e:  # @UndefinedVariable
         print "failed to start web admin: %s, change port then try again" % str(e)
         self.port = idle_port()
         WSGIServer((self.ip, self.port), application=app.create_app(self.coordinator), log=None).serve_forever()
Example #6
0
 def run(self):
     init_logging()
     rootdir = self.coordinator.get('rootdir')
     confdata = self.coordinator.get('confdata')
     icon = os.path.join(rootdir, confdata['icon_path']) 
     SysTrayIcon(
         icon,
         u'萤火虫翻墙代理',
         (
             (u'翻墙浏览', None, self.sytray_launch_browser),
             (u'配置代理', None, self.systray_open_webadmin),
             (u'退出', None, 'QUIT')
         ),
         on_quit=self.systray_quit,
         default_menu_index=1,
     )
Example #7
0
    def run(self):
        init_logging()
        rootdir = self.coordinator.get('rootdir')
        confdata = self.coordinator.get('confdata')
        webpath = os.path.join(rootdir, confdata['web_path'])
        os.chdir(webpath)

        from webpanel import app
        try:
            WSGIServer((self.ip, self.port),
                       application=app.create_app(self.coordinator),
                       log=None).serve_forever()
        except socket.error, e:  # @UndefinedVariable
            print "failed to start web admin: %s, change port then try again" % str(
                e)
            self.port = idle_port()
            WSGIServer((self.ip, self.port),
                       application=app.create_app(self.coordinator),
                       log=None).serve_forever()
Example #8
0
        logger.trace(f"payments: {payments}")
        logger.trace(f"==========================================")

        # this is just new pge shares and assessments and new fees...
        # new charges
        new_charges = utils.get_new_charges(
            cur, acct_obj.acct_id, monthly_global_variables["start_date"])
        if new_charges is None:
            new_charges = 0
        acct_obj.new_charges = new_charges
        logger.trace(f"new charges: {acct_obj.new_charges}")

        acct_obj.current_balance = (acct_obj.prev_balance +
                                    acct_obj.adjustments + acct_obj.payments +
                                    acct_obj.new_charges)
    logger.trace(f"{monthly_global_variables['ttl_monthly_usage']}")

    for acct in acct_list:
        utils.generate_pdf(cur, acct, monthly_global_variables,
                           savings_data_list)

    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/reports.log")
    main()
Example #9
0
    cur = db.cursor()

    exec_str = f"""
        SELECT SUM(amount) 
        FROM activity
        WHERE type = (?)
        OR type = (?)
        OR type = (?)
    """
    const = constants.Constants()
    params = (
        const.savings_deposit_made,
        const.savings_disbursement,
        const.savings_dividend,
    )
    cur.execute(exec_str, params)
    current_savings_balance = cur.fetchone()[0]
    savings_logger.trace(f"current_savings_balance: {current_savings_balance}")
    print(f"===============================================")
    print(f" current savings balance: $ {current_savings_balance/100:,.2f}")
    print(f"===============================================")

    # close the cursor and db
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/get_savings_bal.log")
    main()
Example #10
0
                   choices=['test', 'dev'])

    parameter = p.parse_args()
    return parameter


if __name__ == '__main__':
    #os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
    setup_seed(8)
    opts = parse_args()
    os.environ['CUDA_VISIBLE_DEVICES'] = opts.gpu
    if not os.path.exists(opts.log_dir):
        print('Log DIR ({:s}) not exist! Make new folder.'.format(
            opts.log_dir))
        os.makedirs(opts.log_dir)
    init_logging(os.path.join(opts.log_dir, '{:s}_log.txt'.format(opts.task)))
    logging.info('Using random seed: 8')

    dataset_dev = PhoenixVideo(corpus_dir=opts.corpus_dir,
                               video_path=opts.video_path,
                               phase='dev',
                               DEBUG=opts.DEBUG)
    vocab_size = dataset_dev.voc.num_words
    blank_id = dataset_dev.voc.word2index['<BLANK>']
    del dataset_dev

    slr = SLR(opts, vocab_size=vocab_size, blank_id=blank_id)
    if opts.task == 'train':
        logging.info(slr.network)
        logging.info(opts)
        if len(opts.check_point) == 0:
Example #11
0
import sqlite3
from lib import utils


def main():
    database = "well.sqlite"

    db = sqlite3.connect(database)
    db.row_factory = sqlite3.Row
    cur = db.cursor()

    print(f"")
    utils.print_account_balances(cur)
    print(f"")
    utils.print_savings_account_balance(cur)
    print(f"")

    # close the cursor and db
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/balance_check.log")
    main()
Example #12
0
    """
    params = (deposit_date, const.savings_deposit_made, deposit_amount, note)
    cur.execute(exec_str, params)

    exec_str = f"""
            SELECT SUM(amount)
            FROM activity 
            WHERE type = (?)
            OR type = (?)
            OR type = (?)
        """
    params = (const.savings_deposit_made, const.savings_disbursement,
              const.savings_dividend)
    logger.trace(f"{params}")
    cur.execute(exec_str, params)
    current_savings_balance = cur.fetchone()[0]
    logger.trace(f"current_savings_balance: {current_savings_balance}")
    print(f"===============================================")
    print(f" current savings balance: ${current_savings_balance / 100: ,.2f}")
    print(f"===============================================")

    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == '__main__':
    utils.init_logging('logs/savings_dep.log')
    main()
Example #13
0
parser.add_argument('--epochs', type=int, default=10, metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--everyepochs', type=int, default=1, metavar='N',
                    help='number of epochs to learn structure (default: 10)')
parser.add_argument('--model', type=str, default="", metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--ltmodel', type=str, default="", metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--save', type=str, default="", metavar='N',
                    help='number of epochs to train (default: 10)')
parser.add_argument('--name', type=str, default="ltvae", metavar='N',
                    help='number of epochs to train (default: 10)')
args = parser.parse_args()

timestr = time.strftime("%Y%m%d-%H%M%S")
init_logging("logs/"+timestr+"-"+args.name+".log")

# according to the released code, mnist data is multiplied by 0.02
# 255*0.02 = 5.1. transforms.ToTensor() coverts 255 -> 1.0
# so add a customized Scale transform to multiple by 5.1
mnist_train = MNIST('../dataset/mnist', train=True, download=True)
mnist_test = MNIST('../dataset/mnist', train=False)
train_loader = torch.utils.data.DataLoader(mnist_train, 
    batch_size=args.batch_size, shuffle=True, num_workers=0)
test_loader = torch.utils.data.DataLoader(mnist_test,
    batch_size=args.batch_size, shuffle=False, num_workers=0)

z_dim = 10
ltvae = LTVAE(input_dim=784, z_dim=z_dim, binary=False,
        encodeLayer=[500,500,2000], decodeLayer=[2000,500,500],
        alpha=args.alpha)
Example #14
0
        logger.trace(f"reads in: {acct_obj.reads_in}")
        logger.trace(f"readings_list: {readings_list}")
        acct_obj.latest_reading = readings_list[0]
        acct_obj.previous_reading = readings_list[1]

        acct_obj.calculate_current_usage()
        logger.trace(f"current usage: {acct_obj.current_usage}")

        total_usage += acct_obj.current_usage
    logger.trace(f"total usage: {total_usage:.2f}")
    total_usage = round(total_usage, 2)
    logger.trace(f"total usage, rounded: {total_usage:.2f}")
    percents_total = 0
    for a in acct_list:
        a.current_usage_percent = round(a.current_usage / total_usage * 100, 2)
        print(f"{a.ln:20}...  {a.current_usage_percent:8.2f}%")
        logger.trace(f"{a.current_usage / total_usage * 100}")
        percents_total += a.current_usage_percent

    logger.trace(f"\n{'percents_total:':19} ... {percents_total:9.2f}%\n")
    print(f"")
    print(f"{'percents_total':20}...  {percents_total:8.2f}%")
    # close the cursor and db
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/percentages.log")
    main()
Example #15
0
    utils.backup_file(database)
    db = sqlite3.connect(database)
    db.row_factory = sqlite3.Row
    cur = db.cursor()

    # get date_paid
    payment_date = utils.prompt_for_current_date("Date paid")
    # get amount
    payment_amount = utils.prompt_for_amount("Amount paid")
    const = constants.Constants()

    # mark the bill paid in the activity account
    payment_amount = payment_amount * -1
    exec_str = f"""
                INSERT INTO activity (date, type, amount, note) 
                VALUES (?, ?, ?, ?)
            """
    params = (payment_date, const.pge_bill_paid, payment_amount, "PGE bill paid")
    logger.trace(params)
    cur.execute(exec_str, params)

    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == '__main__':
    utils.init_logging('logs/pge_bill_paid.log')
    main()
Example #16
0
 def run(self):
     init_logging()
     self.relayfactory = FireflyRelayFactory(self.matcher, self.timeout)
     self.proxy = SocksServer(self.ip, self.port, self.relayfactory)
     self.proxy.run()
Example #17
0
 def run(self):
     init_logging()
     self.application = FireflyHTTPApplication(self.matcher, self.timeout)
     self.proxy = HTTPProxyServer(self.ip, self.port, self.application, log=None)
     self.proxy.run()
Example #18
0
                acct.acct_id,
                const.savings_assessment,
                acct.savings_assessment,
                "Savings assessment",
            )
            cur.execute(exec_str, params)

            assessment_total += acct.savings_assessment
            logger.trace(
                f"Bill total: {int(round(acct.savings_assessment + acct.pge_bill_share, 2))}"
            )
        else:
            logger.trace(f"No assessment needed.")

    # added this to make the savings deposit easier
    # 2019.07.21
    #
    # 2019.08.24 ... this needed reformatting
    print(f"==============================================")
    print(f"assessment_total: ${assessment_total / 100:10.2f}")
    print(f"==============================================")
    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/pge_bill_recd.log")
    main()
Example #19
0
 def run(self):
     init_logging()
     self.relayfactory = FireflyRelayFactory(self.matcher, self.timeout)
     self.proxy = SocksServer(self.ip, self.port, self.relayfactory)
     self.proxy.run()
Example #20
0
        """
        params = (r["acct_id"], )
        cur.execute(exec_str, params)
        last_reading = cur.fetchone()
        print(f"Last month's reading: {last_reading['reading']}")

        # grab current reading and then insert it into the DB
        reading = input(f"{r['acct_id']} - {r['address']}: ")

        # this should allow empty input .... in case of inactive account
        if not reading:
            continue

        exec_str = f"""
            INSERT INTO reading (reading_id, account_id, reading)
            VALUES (?, ?, ?)
        """
        params = (last_inserted_row_id, r["acct_id"], reading)
        logger.trace(params)
        cur.execute(exec_str, params)

    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == "__main__":
    utils.init_logging("logs/monthly_readings.log")
    main()
Example #21
0
    """
    params = (dividend_date, const.savings_dividend, dividend_amount, note)
    cur.execute(exec_str, params)

    # check the balance again
    exec_str = f"""
            SELECT SUM(amount)
            FROM activity 
            WHERE type = (?)
            OR type = (?)
            OR type = (?)
        """
    params = (const.savings_deposit_made, const.savings_disbursement,
              const.savings_dividend)
    cur.execute(exec_str, params)
    current_savings_balance = cur.fetchone()[0]
    logger.debug(f"current_savings_balance: {current_savings_balance}")
    print(f"===============================================")
    print(f" current savings balance: ${current_savings_balance / 100: ,.2f}")
    print(f"===============================================")

    # save, then close the cursor and db
    db.commit()
    cur.close()
    db.close()


if __name__ == '__main__':
    utils.init_logging("logs/savings_dividend.log")
    main()
Example #22
0
    notes += utils.prompt_for_notes("Payment notes")

    payment_logger.debug(date)
    payment_logger.debug(amt)
    payment_logger.debug(acct)
    payment_logger.debug(notes)

    # backup the file prior to adding any data
    utils.backup_file(db)

    const = constants.Constants()
    # insert the payment into the DB
    cur.execute(
        "INSERT INTO activity (date, acct, type, amount, note) VALUES (?, ?, ?, ?, ?)",
        (date, acct, const.payment_received, amt, notes),
    )

    # fetch updated balance and display
    cur_balance = utils.get_acct_balance(acct, cur)
    print(f"Updated balance: ${cur_balance:.2f}\n")

    # save, then close the cursor and database
    database.commit()
    cur.close()
    database.close()


if __name__ == "__main__":
    utils.init_logging('logs/payment_recd.log')
    main()