<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import ConfigParser
import csv
import datetime
import logging
import os.path
import socket
import subprocess
import sys
import time

from trademybitapi import TradeMyBitAPI
from pycgminer import CgminerAPI


class Algo:
    def __init__(self, name):
        self.command    = '' # the command that is run when we want to mine this coin.
        self.name       = name
        self.cnt        = 0

class TradeMyBitSwitcher(object):
    def __init__(self):
        # Define supported algo
        self.algos = {}
        self.algos['scrypt']  =  Algo('Scrypt')
        self.algos['nscrypt'] =  Algo('N-Scrypt')

        self.profitability_log = None
        self.__load_config()
        self.api = TradeMyBitAPI(self.api_key, 'https://pool.trademybit.com/api/')
        self.cgminer = CgminerAPI(self.cgminer_host, self.cgminer_port)

        # We track state in a variable
        self.current_algo = None

    def main(self):
        # cnt_all = 0
        # main loop
        print '-' * 72

        while True:
            # print header
            # self.logger.info("<<< Round %d >>>" % (cnt_all+1))
          
            # get data from sources
            self.logger.debug("Fetching data...")
            bestalgo = self.best_algo()
          
            self.logger.debug("=> Best: %s | Currently mining: %s" % (bestalgo, self.current_algo))
         
            if bestalgo != self.current_algo and bestalgo != None:
                # i.e. if we're not already mining the best algo
                self.switch_algo(bestalgo)

            elif self.current_algo == None:
                # No miner running and profitability is similar, run the first algo
                self.logger.warning('No miner running')
                self.switch_algo(self.algos.keys()[0])

            # sleep
            self.logger.debug('Going to sleep for %dmin...' % self.idletime)
            i = 0
            while i < self.idletime*60:
                time.sleep(1)
                i += 1

    def best_algo(self):
        """Retrieves the "bestalgo" from TMB api"""
        try:
            data = self.api.bestalgo()
            # parse json data into variables
            algo1 = data[0]["algo"]
            score1 = float(data[0]["score"])
            algo2 = data[1]["algo"]
            score2 = float(data[1]["score"])

            self.logger.debug("%s : %f | %s: %f" % (algo1, score1, algo2, score2))

            # return result
            if (score2 - score1) / score1 > self.profitability_threshold:
                best = algo2
            elif (score1 - score2) / score2 > self.profitability_threshold:
                best = algo1
            else:
                best = None
<commit_msg>Clean exit<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import ConfigParser
import csv
import datetime
import logging
import os.path
import socket
import subprocess
import sys
import time

from trademybitapi import TradeMyBitAPI
from pycgminer import CgminerAPI


class Algo:
    def __init__(self, name):
        self.command    = '' # the command that is run when we want to mine this coin.
        self.name       = name
        self.cnt        = 0

class TradeMyBitSwitcher(object):
    def __init__(self):
        # Define supported algo
        self.algos = {}
        self.algos['scrypt']  =  Algo('Scrypt')
        self.algos['nscrypt'] =  Algo('N-Scrypt')

        self.profitability_log = None
        self.__load_config()
        self.api = TradeMyBitAPI(self.api_key, 'https://pool.trademybit.com/api/')
        self.cgminer = CgminerAPI(self.cgminer_host, self.cgminer_port)

        # We track state in a variable
        self.current_algo = None

    def main(self):
        try:
            # cnt_all = 0
            # main loop
            print '-' * 72

            while True:
                # print header
                # self.logger.info("<<< Round %d >>>" % (cnt_all+1))

                # get data from sources
                self.logger.debug("Fetching data...")
                bestalgo = self.best_algo()

                self.logger.debug("=> Best: %s | Currently mining: %s" % (bestalgo, self.current_algo))

                if bestalgo != self.current_algo and bestalgo != None:
                    # i.e. if we're not already mining the best algo
                    self.switch_algo(bestalgo)

                elif self.current_algo == None:
                    # No miner running and profitability is similar, run the first algo
                    self.logger.warning('No miner running')
                    self.switch_algo(self.algos.keys()[0])

                # sleep
                self.logger.debug('Going to sleep for %dmin...' % self.idletime)
                i = 0
                while i < self.idletime*60:
                    time.sleep(1)
                    i += 1
        except KeyboardInterrupt:
            self.logger.warn('Caught KeyboardInterrupt, terminating...')
            self.cleanup()


    def cleanup(self):
        """Cleanup our mess"""
        if self.profitability_log:
            self.profitability_file.close()

        sys.exit()

    def best_algo(self):
        """Retrieves the "bestalgo" from TMB api"""
        try:
            data = self.api.bestalgo()
            # parse json data into variables
            algo1 = data[0]["algo"]
            score1 = float(data[0]["score"])
            algo2 = data[1]["algo"]
            score2 = float(data[1]["score"])

            self.logger.debug("%s : %f | %s: %f" % (algo1, score1, algo2, score2))

            # return result
            if (score2 - score1) / score1 > self.profitability_threshold:
                best = algo2
            elif (score1 - score2) / score2 > self.profitability_threshold:
                best = algo1
            else:
                best = None

{'fraction_non_alphanumeric': 0.10841533763148965, 'fraction_numerical': 0.010858500169664066, 'mean_word_length': 1.6771117166212535, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6502844', 'n_tokens_mistral': 1785, 'n_tokens_neox': 1717, 'n_words': 443}