Beispiel #1
0
    def get_human_move(self, color):
        commands = {
            "help": self.help,
            "/raw": self.raw_cmd,
        }

        #pull messages until we get a valid command for @color
        while 1:
            self.send("Enter a legal move for %s:" % color)

            msg = self.message_queue.get()
            m = msg['message']
            cmd = m.split(" ")[0]

            if self.legalmove(color, m):
                self.gnugo.command("play", color, m)
                if m.lower() == "pass":
                    if self.gamestate == Serve.PASS:
                        self.gamestate = Serve.FINISHED
                    else:
                        self.gamestate = Serve.PASS
                else:
                    self.showboard()
                break
            elif cmd in commands:
                commands[cmd](m)

            p("didn't find command %s" % (cmd))
Beispiel #2
0
def run():
    """
    Solution: Basically just walk through the grid and check every possibility.
    It doesn't really take that long given the input size.
    """
    grid = get_grid()

    height = len(grid)
    width = len(grid[0])

    largest = 0
    for row in xrange(height):
        for col in xrange(width):
            horizontal = grid[row][col:col + 4] if col < width - 3 else []
            vertical = [grid[row][col], grid[row + 1][col], grid[row + 2][col],
                        grid[row + 3][col]] if row < height - 3 else []
            diagonal1 = [grid[row][col], grid[row + 1][col + 1],
                         grid[row + 2][col + 2], grid[row + 3][col + 3]] \
                         if row < height - 3 and col < width - 3 else []
            diagonal2 = [grid[row][col + 3], grid[row + 1][col + 2],
                         grid[row + 2][col + 1], grid[row + 3][col]] \
                         if row < height - 3 and col < width - 3 else []
            m = max([p(horizontal), p(vertical), p(diagonal1), p(diagonal2)])
            if m > largest:
                largest = m

    return largest
Beispiel #3
0
    def get_human_move(self, color):
        commands = {
            "help": self.help,
            "/raw": self.raw_cmd,
        }

        #pull messages until we get a valid command for @color
        while 1:
            self.send("Enter a legal move for %s:" % color)

            msg = self.message_queue.get()
            m = msg['message']
            cmd = m.split(" ")[0]

            if self.legalmove(color, m):
                self.gnugo.command("play", color, m)
                if m.lower() == "pass":
                    if self.gamestate == Serve.PASS:
                        self.gamestate = Serve.FINISHED
                    else:
                        self.gamestate = Serve.PASS
                else:
                    self.showboard()
                break
            elif cmd in commands:
                commands[cmd](m)

            p("didn't find command %s" % (cmd))
Beispiel #4
0
 def step_interval_predictor(self, x_i, args):
     A0, dAs, d_i = args
     dAp = sum(p(dAi) for dAi in dAs)
     dAn = sum(n(dAi) for dAi in dAs)
     Bp = p(self.B)
     Bn = n(self.B)
     x_m, x_M = x_i[0, :, np.newaxis], x_i[1, :, np.newaxis]
     d_m, d_M = d_i[0, :, np.newaxis], d_i[1, :, np.newaxis]
     dx_m = A0 @ x_m - dAp @ n(x_m) - dAn @ p(x_M) + Bp @ d_m - Bn @ d_M
     dx_M = A0 @ x_M + dAp @ p(x_M) + dAn @ n(x_m) + Bp @ d_M - Bn @ d_m
     dx_i = np.array([dx_m.squeeze(axis=-1), dx_M.squeeze(axis=-1)])
     return x_i + dx_i * dt
Beispiel #5
0
def colorize(line):
  done = False
  for c in long_colors:
    if line.startswith(c):
      if long_colors[c]=="-":
        return
      else:
        sc(long_colors[c]); done = True; break
  if not done:
    for c in short_colors:
      if line.startswith(c):
        sc(short_colors[c]); break
  p(line); sc(); p()
Beispiel #6
0
def parse_log_lines(line):
    if game_complete_pattern.match(line):
        player_state.clear_players()

    match = card_update_pattern.match(line)
    if not match:
        return

    id = match.group('id')
    cardId = match.group('card_id')
    alternate_card_id = match.group('alternate_card_id')
    player = match.group('player')

    if player_state.card_drawn(id, cardId or alternate_card_id, player):
        p("Updated player state")
def parse_log_lines(line):
	if game_complete_pattern.match(line):
		player_state.clear_players()

	match = card_update_pattern.match(line)
	if not match:
		return

	id = match.group('id')
	cardId = match.group('card_id')
	alternate_card_id = match.group('alternate_card_id')
	player = match.group('player')

	if player_state.card_drawn(id, cardId or alternate_card_id, player):
		p("Updated player state")
Beispiel #8
0
    def serve(self):
        #avoid the "new room quick message" bug
        sleep(.5)

        p("serving game!")

        self.gnugo = Gnugo()

        sz = False
        while not sz:
            sz = self.get_int(
                "What boardsize would you like? (Must be between 3 and 19, default is 19):",
                3, 19, 19)
        self.gnugo.command("boardsize", sz)

        handicap = False
        while not handicap:
            handicap = self.get_int(
                "What handicap would you like? (Must be between 0 and 12, default is 0):",
                0, 12, 0)
        if handicap > 0:
            self.gnugo.command("fixed_handicap", handicap)

        self.showboard()

        if handicap == 0:
            self.get_human_move("black")
        else:
            self.white = Serve.HUMAN
            self.black = Serve.COMPUTER

        #now black will have played, either via handicap or the previous command,
        #so white will go next.
        while self.gamestate != Serve.FINISHED:
            if self.white == Serve.HUMAN:
                self.get_human_move("white")
            else:
                self.get_computer_move("white")

            if self.gamestate == Serve.FINISHED: break

            if self.black == Serve.HUMAN:
                self.get_human_move("black")
            else:
                self.get_computer_move("black")

        score = self.gnugo.command("final_score").split()[1]
        self.send("Final Score: %s" % score)
Beispiel #9
0
    def serve(self):
        #avoid the "new room quick message" bug
        sleep(.5)

        p("serving game!")

        self.gnugo = Gnugo()
        
        sz = False
        while not sz:
            sz = self.get_int("What boardsize would you like? (Must be between 3 and 19, default is 19):", 3, 19, 19)
        self.gnugo.command("boardsize", sz)

        handicap = False
        while not handicap:
            handicap = self.get_int("What handicap would you like? (Must be between 0 and 12, default is 0):", 0, 12, 0)
        if handicap > 0:
            self.gnugo.command("fixed_handicap", handicap)

        self.showboard()

        if handicap == 0:
            self.get_human_move("black")
        else:
            self.white = Serve.HUMAN
            self.black = Serve.COMPUTER

        #now black will have played, either via handicap or the previous command,
        #so white will go next.
        while self.gamestate != Serve.FINISHED:
            if self.white == Serve.HUMAN:
                self.get_human_move("white")
            else:
                self.get_computer_move("white")

            if self.gamestate == Serve.FINISHED: break

            if self.black == Serve.HUMAN:
                self.get_human_move("black")
            else:
                self.get_computer_move("black")

        score = self.gnugo.command("final_score").split()[1]
        self.send("Final Score: %s" % score)
Beispiel #10
0
    def get_full_balance(self, full=False, allow_zero=False):
        # for ex in self.all_exchanges.values():
        #     if hasattr(ex, 'get_BTC_price'):
        #         BTC_price = ex.get_BTC_price()
        # assert(BTC_price)

        BTC_price = self.all_exchanges['huobi'].get_BTC_price()

        USD_out = 2000 + 8888 + 8338 + 4548 + 2034 + 5248 + 1099 + 3758
        all_coins = {
            'total': {
                'BTC': USD_out / BTC_price,
                'USD': USD_out,
                'num': 0
            }
        }

        for ex_name, exchange in self.all_exchanges.items():
            if exchange:
                coins = exchange.get_full_balance(allow_zero=allow_zero)
                combine_coins(all_coins, coins)
                p(ex_name + ': '),
                show_coins(coins)

        # add hot wallet EOS
        tp_eos = 500
        tp_usdt = tp_eos * self.all_exchanges['huobi'].get_price('EOS', 'USDT')
        tp_coins = {
            'EOS': {
                'BTC': tp_usdt / BTC_price,
                'USD': tp_usdt,
                'num': tp_eos
            }
        }
        combine_coins(all_coins, tp_coins)
        p('TP' + ': '),
        show_coins(tp_coins)

        print('Out:     ' + str(USD_out) + ' 100%'),

        p('Total:   '),
        show_coins(all_coins, full=full, USD_out=USD_out)

        p('Ratio:   ')
        base = 86800
        print(round(all_coins['total']['USD'] / base, 3))
Beispiel #11
0
 def legalmove(self, color, msg):
     p("checking color %s msg %s" % (color, msg))
     try:
         r = self.gnugo.command("is_legal", color, msg)
         isvalid = r.split(" ")[1][0] == '1'
         p("Is Legal? %s %s %s" % (isvalid, r, r.split(" ")))
         return isvalid
     except GnugoException as e:
         p("Got a gnugo exception: %s" % e)
         #TODO: print a nice error to the user
         return False
Beispiel #12
0
 def legalmove(self, color, msg):
     p("checking color %s msg %s" % (color, msg))
     try:
         r = self.gnugo.command("is_legal", color, msg)
         isvalid = r.split(" ")[1][0] == '1'
         p("Is Legal? %s %s %s" % (isvalid, r, r.split(" ")))
         return isvalid
     except GnugoException as e:
         p("Got a gnugo exception: %s" % e)
         #TODO: print a nice error to the user
         return False
def entropy_transform_old(word, ts,tots):
    """Perform entropy transform of the timeseries ts with respect to totals tots"""
    L=len(tots)
    n=float(sum(ts))
    N=float(sum(tots))
    max_width = L
    r=[]

    for w in xrange(1,max_width,2):
        for t in xrange(0,L-w,2):
            s = sum(ts[t:(t+w)])
            S = sum(tots[t:(t+w)])
            m_j = [ s, n-s ]
            M_j = [ S, N-S ]
            h = -sum( xlog2x(m/n) for m in m_j if m>0 )
            h_avg = -sum( p(n,m,M/N)*xlog2x(m/n)
                                for M in M_j
                                for m in xrange(1,1+int(min(n,M))))
            r.append( (w, t, (n/N) * (h_avg - h) ) )
    return (word,r)
Beispiel #14
0
def main():
    global p
    p(send)
    conv_auth = requests.AuthObject(config.username, config.password)

    def req(params={}):
        return requests.get('https://convore.com/api/live.json', params=params, auth=conv_auth)

    cursor = None
    while 1:
        try:
            p('requesting')
            r = req({'cursor': cursor}) if cursor else req()

            if r.status_code != 200:
                p("Got invalid status code %s on response body %s" % (r.status_code, r.content))
                continue

            response = json.loads(r.content)
            for message in response['messages']:
                cursor = message['_id']

                #ignore messages sent by ourselves to (try and) avoid infinite loops
                if message['user']['username'] == config.username:
                    continue

                if message['kind'] == 'message':
                    topic_id = message['topic']['id']
                    if topic_id in games:
                        p("forwarding message to topic_id %s" % topic_id)
                        games[topic_id][1].put(message)

                #if a new topic is created, launch a serving proces
                if message['kind'] == 'topic':
                    topic_id = message["id"]

                    queue = Queue()
                    proc = Process(target=Gogame(topic_id, queue).serve)
                    proc.start()

                    games[topic_id] = (proc, queue)

                    p("created a process to serve topic_id %s" % topic_id)

                #don't print login, logout, or read messages. Eventually TODO: DELETEME
                if message['kind'] not in ['login', 'logout', 'read']:
                    p(message)

        except KeyboardInterrupt:
            sys.exit(0)
Beispiel #15
0
	def calculate(self,idx):
		return p(self.source['ksPt'][idx],self.source['ksEta'][idx])
Beispiel #16
0
def main():
    global p
    p(send)
    conv_auth = requests.AuthObject(config.username, config.password)

    def req(params={}):
        return requests.get('https://convore.com/api/live.json',
                            params=params,
                            auth=conv_auth)

    cursor = None
    while 1:
        try:
            p('requesting')
            r = req({'cursor': cursor}) if cursor else req()

            if r.status_code != 200:
                p("Got invalid status code %s on response body %s" %
                  (r.status_code, r.content))
                continue

            response = json.loads(r.content)
            for message in response['messages']:
                cursor = message['_id']

                #ignore messages sent by ourselves to (try and) avoid infinite loops
                if message['user']['username'] == config.username:
                    continue

                if message['kind'] == 'message':
                    topic_id = message['topic']['id']
                    if topic_id in games:
                        p("forwarding message to topic_id %s" % topic_id)
                        games[topic_id][1].put(message)

                #if a new topic is created, launch a serving proces
                if message['kind'] == 'topic':
                    topic_id = message["id"]

                    queue = Queue()
                    proc = Process(target=Gogame(topic_id, queue).serve)
                    proc.start()

                    games[topic_id] = (proc, queue)

                    p("created a process to serve topic_id %s" % topic_id)

                #don't print login, logout, or read messages. Eventually TODO: DELETEME
                if message['kind'] not in ['login', 'logout', 'read']:
                    p(message)

        except KeyboardInterrupt:
            sys.exit(0)
Beispiel #17
0
    def attack(self, turn):
        agi = random.randint(1, 50)
        temptype = self.typ
        '''if agi > 49:
            if self.typ == 1:
                temptype = 2
            else:
                temptype = 1'''

        if temptype == 1:
            move = random.randint(1, 5)
            if self.sp >= 10 and move > 3:
                accur = random.randint(0, 256)
                utils.p("The %s attempts to strike you with a powerful blow!" %
                        self.name)
                if accur < self.accur:
                    damage = (self.atk + 1) * random.randint(
                        1, round(self.atk / 4))
                    playa.player.hp -= damage
                    utils.p("It hits you for %s damage!" % damage)
                else:
                    utils.p("It strikes the air next to you instead!")
                self.sp -= 10
                turn = 1

            else:
                accur = random.randint(0, 256)
                utils.p("The %s attempts to hit you!" % self.name)
                if accur < self.accur:
                    damage = (self.atk + 1)
                    playa.player.hp -= (self.atk + 1)
                    utils.p("It hits you for %s damage" % damage)
                else:
                    utils.p("It strikes the air next to you instead!")
                turn = 1
        '''elif temptype == 2:
Beispiel #18
0
    def get_full_balance(self, full=False, allow_zero=False):
        # read all private variables
        with open('variables.json') as f:
            variables = json.load(f)

        # get BTC and EOS price for future use
        huobi = self.all_exchanges['huobi']
        BTC_price = huobi.get_BTC_price()
        EOS_price = huobi.get_price('EOS', 'USDT')

        # get cashed out amount
        USD_out = sum(variables['usd_out'])
        out_coins = {
            'total': {
                'BTC': USD_out / BTC_price,
                'USD': USD_out,
                'num': 0
            }
        }

        # combine coins in all exchanges
        all_coins = {}
        for ex_name, exchange in self.all_exchanges.items():
            if exchange:
                coins = exchange.get_full_balance(allow_zero=allow_zero)
                # pprint(coins)
                all_coins = combine_coins(all_coins, coins)
                # p('[' + ex_name + '] => '),
                # show_coins(coins, full=True)

        # other long term coins
        tp_eos_short = variables['tp_eos_short']
        tp_eos_long = variables['tp_eos_long']
        tp_eos = tp_eos_short + tp_eos_long
        tp_usdt = tp_eos * EOS_price
        other_coins = {
            'EOS': {
                'BTC': tp_usdt / BTC_price,
                'USD': tp_usdt,
                'num': tp_eos
            },
            'total': {
                'BTC': tp_usdt / BTC_price,
                'USD': tp_usdt,
                'num': 0
            },
        }

        # print out cash out amount
        p('[Cash Out] =>'),
        show_coins(out_coins)

        # add other long term coins
        all_coins = combine_coins(all_coins, other_coins)
        fixed_coins = variables['fixed_coins']
        # if 'EOS' in fixed_coins.keys():
        #     fixed_coins['EOS'] += tp_eos_long           # long term tp_eos

        print('[Total All] =>')
        show_coins(all_coins, full=full)

        # print('[Total Long Term] =>')
        # fixed_coins_full_data = huobi.get_full_balance_with_raw_coin_data(fixed_coins, print_info=False)
        # show_coins(fixed_coins_full_data, full=full)

        # # calculate short term coins
        # print('[Total Short Term] =>')
        # show_coins(all_coins, full=full, fixed_coins=fixed_coins)

        # profit calculation
        p('Ratio: ')
        base = variables['base']
        real_total = all_coins['total']['USD'] + USD_out
        ratio = real_total / base
        print(
            "[{}/{}]".format(round(real_total / 10000, 2),
                             round(base / 10000, 2)), round(ratio, 3))
 def impOperation(self):
     p("CI2")
Beispiel #20
0
# coding=UTF-8
#!/usr/bin python

#import utils
#from utils import *
import utils as u

list1=['a','b','c',['1','2','3']]
for i in list1:
    if isinstance(i , list):
        print i
        
comment = '''1234556789'''
print comment

u.p('print it' , 3)

print '--------------------'
u.readfile('test.txt')

print 'a:b:c' .split(':',1)

print (1<2) and 3 or 4

#http://www.52sky.org/41001.html
ip =  '192.168.10.214'
for k,v in zip(ip.split('.'),[('192',0x1000000),('168',0x10000),('10',0x100),('214',1)]):
    print k,v

#首先ip.split('.')得到列表['192','168','10','214'],经过zip一组装,就变成 #接着for循环将各个元组的两项做整数乘法,最后将新列表的值用sum求和,得到结果
f = lambda ip: sum( [ int(k)*v[1] for k, v in zip(ip.split('.'),[('192',0x1000000),('168',0x10000),('10',0x100),('214',1)])])
Beispiel #21
0
    def __init__(self, risk_limit, audit_type, n_winners, max_polls,
                 random_seed, preliminary):
        super().__init__(risk_limit, audit_type, n_winners, max_polls,
                         random_seed, preliminary)
        self.required_headers.add('party')
        self.preliminary['party'] = self.preliminary['party'].fillna('')
        self.vote_count = self.preliminary.groupby(
            'party').sum()['votes'].to_dict()
        self.table_count = self.preliminary.groupby(
            'table').sum()['votes'].to_dict()
        self.candidate_count = self.preliminary.groupby(
            'candidate').sum()['votes'].to_dict()
        self.candidates = list(self.candidate_count.keys())
        self.tables = list(self.table_count.keys())
        self.parties = list(self.vote_count.keys())
        self.primary_column = 'party'
        self.party_members = {}
        members_per_party = {}
        for party in self.parties:
            p = self.preliminary[self.preliminary['party'] == party]
            candidates = p.sort_values('votes',
                                       ascending=False)['candidate'].unique()
            members_per_party[party] = list(candidates)
            for c in candidates:
                self.party_members[c] = party

        self.pseudo_vote_count = {
            (p, i): utils.p(p, self.vote_count, i)
            for p in self.parties if p
            for i in range(min(n_winners, len(members_per_party[p])))
        }

        self.W, self.L = utils.get_W_L_sets(self.pseudo_vote_count, n_winners)
        self.winning_candidates = []
        for party in self.parties:
            if any([p == party for p, i in self.W]):
                seats = max([i for p, i in self.W if p == party]) + 1
                self.winning_candidates.extend(
                    members_per_party[party][:seats])

        self.Sw = {}
        self.Sl = {}
        for party in self.parties:
            wp = list(filter(lambda x: x[0] == party, self.W))
            lp = list(filter(lambda x: x[0] == party, self.L))
            if wp:
                self.Sw[party] = max(wp, key=lambda x: x[1])[1]

            if lp:
                self.Sl[party] = min(lp, key=lambda x: x[1])[1]

        self.Wp = []
        for winner in self.W:
            if winner[0] not in self.Wp:
                self.Wp.append(winner[0])

        self.Lp = []
        for loser in self.L:
            if loser[0] not in self.Lp:
                self.Lp.append(loser[0])

        if self.is_ballot_polling():
            for winner in self.Wp:
                self.T[winner] = {
                    loser: Decimal(1)
                    for loser in self.Lp if winner != loser
                }

        self.Tp = {}
        for p in self.Wp:
            seats = max([w[1] for w in self.W if w[0] == p]) + 1
            self.Tp[p] = Plurality(
                self.risk_limit, self.audit_type, seats, self.max_polls,
                self.random_seed,
                self.preliminary[self.preliminary['party'] == p])
Beispiel #22
0
"""
Created on 2010-07-28

@author: marioosh
"""
from utils import p
import urllib

# downloading file
urllib.urlretrieve("http://old.marioosh.net/test.txt", "test2.txt")

# otwarcie zasobu sieciowego do odczytu
f = urllib.urlopen("http://onet.pl/")
end = False
w = open("out.html", "w")
while not end:
    x = f.read(1)
    if x != "":
        # wywalam taby i entery
        if x not in set(["\t", "\n"]):
            p(x)
            w.write(x)
    else:
        end = True