<commit_before>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import jinja2
import os
import webapp2

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

class BaseHandler(webapp2.RequestHandler):

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, file_name, **params):
        template = jinja_env.get_template(file_name)
        return template.render(params)

    def render(self, file_name, **kw):
        self.write(self.render_str(file_name, **kw))

class MainHandler(BaseHandler):

    def get(self):
        self.render("main.html", title = "AI Experiments")

class SearchHandler(BaseHandler):

    def get(self):
        self.render("search.html", title = "AI Experiments - Search")

html_re = r'(.html)?'
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/search' + html_re, SearchHandler)
], debug=True)
<commit_msg>removed search handler. must test first.<commit_after>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import jinja2
import os
import webapp2

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

class BaseHandler(webapp2.RequestHandler):

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, file_name, **params):
        template = jinja_env.get_template(file_name)
        return template.render(params)

    def render(self, file_name, **kw):
        self.write(self.render_str(file_name, **kw))

class MainHandler(BaseHandler):

    def get(self):
        self.render("main.html", title = "AI Experiments")

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)
<|endoftext|>


<commit_before>
import os
import sys
import datetime
import logging

logging.basicConfig(filename="scheduler.log", format='%(levelname)s:%(thread)d:%(message)s', level=logging.DEBUG)

PROJDIR = os.path.abspath(os.path.dirname(__file__))
ROOTDIR = os.path.split(PROJDIR)[0]
try:
    #
    import site
    site.addsitedir(ROOTDIR)
except ImportError:
    print('Development of keepcd')

import settings

from scheduler.hackernews import run as hackernews_run
from scheduler.producthunt_api import run as producthunt_run
from scheduler.designernews import run as designernews_run
from scheduler.rssfeed import run as rss_run

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

now = datetime.datetime.utcnow()
now = now + datetime.timedelta(seconds=10)
scheduler.add_job(hackernews_run,'interval', minutes=6,  id='hackernews', next_run_time=now)
scheduler.add_job(producthunt_run,'interval', minutes=6,  id='producthunt', next_run_time=now)
scheduler.add_job(designernews_run,'interval', minutes=6,  id='designernews', next_run_time=now)
scheduler.add_job(rss_run,'interval', minutes=6,  id='rssfeed', next_run_time=now)

scheduler.start()

# from scheduler.news import update_sites

# update_sites('hackernews')

# hackernews_run()
# producthunt_run()
# designernews_run()
<commit_msg>rm settings<commit_after>
import os
import sys
import datetime
import logging

logging.basicConfig(filename="scheduler.log", format='%(levelname)s:%(thread)d:%(message)s', level=logging.DEBUG)

PROJDIR = os.path.abspath(os.path.dirname(__file__))
ROOTDIR = os.path.split(PROJDIR)[0]
try:
    #
    import site
    site.addsitedir(ROOTDIR)
except ImportError:
    print('Development of keepcd')

from scheduler.hackernews import run as hackernews_run
from scheduler.producthunt_api import run as producthunt_run
from scheduler.designernews import run as designernews_run
from scheduler.rssfeed import run as rss_run

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

now = datetime.datetime.utcnow()
now = now + datetime.timedelta(seconds=10)
scheduler.add_job(hackernews_run,'interval', minutes=6,  id='hackernews', next_run_time=now)
scheduler.add_job(producthunt_run,'interval', minutes=6,  id='producthunt', next_run_time=now)
scheduler.add_job(designernews_run,'interval', minutes=6,  id='designernews', next_run_time=now)
scheduler.add_job(rss_run,'interval', minutes=6,  id='rssfeed', next_run_time=now)

scheduler.start()

# from scheduler.news import update_sites

# update_sites('hackernews')

# hackernews_run()
# producthunt_run()
# designernews_run()
<|endoftext|>


<commit_before>import praw
from flask import Flask
from flask import request, render_template
from prawoauth2 import PrawOAuth2Mini

from settings import (app_key, app_secret, access_token, refresh_token,
                      user_agent, scopes)

reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key=app_key,
                              app_secret=app_secret,
                              access_token=access_token,
                              refresh_token=refresh_token, scopes=scopes)

app = Flask(__name__)

@app.route('/')
def index():
    username = request.values.get('username')
    if not username:
        return render_template('index.html')
    cakeday = get_cake_day(username)
    return render_template('result.html', redditor=username, cakeday=cakeday)

if __name__ == '__main__':
    app.run(debug=True)
<commit_msg>Add `get_cake_day`<commit_after>import praw
import humanize
from datetime import datetime
from flask import Flask
from flask import request, render_template
from prawoauth2 import PrawOAuth2Mini

from settings import (app_key, app_secret, access_token, refresh_token,
                      user_agent, scopes)

reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key=app_key,
                              app_secret=app_secret,
                              access_token=access_token,
                              refresh_token=refresh_token, scopes=scopes)
app = Flask(__name__)

def get_cake_day(username):
    redditor = reddit_client.get_redditor(username)
    try:
        created_on = datetime.utcfromtimestamp(redditor.created_utc)
    except praw.errors.NotFound:
        return False
    oauth_helper.refresh()
    return(humanize.naturalday(created_on))

@app.route('/')
def index():
    username = request.values.get('username')
    if not username:
        return render_template('index.html')
    cakeday = get_cake_day(username)
    return render_template('result.html', redditor=username, cakeday=cakeday)

if __name__ == '__main__':
    app.run(debug=True)
<|endoftext|>


<commit_before>"""
Run file for PyHive
"""
import sys
import pygame
import math
import operator

class Hexagon():
    """Class for drawing a hollow hexagon"""

    def __init__(self, position, radius, color, line = 2):
        self.center = position
        self.radius = radius
        self.color = color
        self.line = line

    def hex_corner(self, i):
        """Get corner"""
        angle_deg = 60.0 * i
        angle_rad = math.pi / 180 * angle_deg
        return (self.center[0] + self.radius * math.cos(angle_rad),
                self.center[1] + self.radius * math.sin(angle_rad))

    def draw(self, surface, color = None, line = None):
        """Draw a hexagon"""
        if not color:
            color = self.color
        if not line:
            line = self.line
        points = [self.hex_corner(x) for x in range(6)]
        pygame.draw.polygon(surface, color, points, self.line)

class Chip():
    """Class for drawing a chip on the board"""

    def __init__(self):
        icon = pygame.image.load("images/Bee.png").convert_alpha()
        self.image = pygame.image.load("images/BlankChip.png").convert_alpha()
        self.image.blit(icon, (0,0))
        self.offset = (-49, -55)

    def set_grid_pos(self, hexagon):
        self.hexagon = hexagon
        if not hasattr(self, 'selection_hexagon'):
            self.selection_hexagon = Hexagon(hexagon.center, hexagon.radius, hexagon.color)
        self.selection_hexagon.center = tuple(map(operator.add, self.hexagon.center, (0, -12)))

    def draw(self, surface):
        """Draw the chip on top of the hexagon"""
        if hasattr(self, 'hexagon') and self.hexagon:
            pos = tuple(map(operator.add, self.hexagon.center, self.offset))
            surface.blit(self.image, pos)

    def draw_outline(self, surface, color = (200, 200, 0), line = 10):
        """Draw the outline of the chip if it's placed"""
        if hasattr(self, 'selection_hexagon') and self.selection_hexagon:
            self.selection_hexagon.draw(surface, color, line)

    def is_mouse_on(self, mouse_pos):
        if hasattr(self, 'hexagon') and self.hexagon:
            vector = tuple(map(operator.sub, self.hexagon.center, mouse_pos))
            magnatude = (vector[0] ** 2 + vector[1] ** 2) ** 0.5
            return magnatude < self.hexagon.radius

class PlusChip(Chip):
    """Class for drawing a chip with a plus on it"""

    def __init__(self):
        icon = pygame.image.load("images/Plus.png").convert_alpha()
        self.image = pygame.image.load("images/BlankChip.png").convert_alpha()
        self.image.blit(icon, (0,0))
        self.offset = (-49, -55)

class GridDrawer():
    """Class that draws a hexagon grid when run"""

    def __init__(self, screen_size, hex_size):
        # Bring up
        pygame.init()
        self.screen = pygame.display.set_mode(screen_size)
        self.done = False
        # create grid
        self.init_hexagons(screen_size, hex_size)
        self.font = pygame.font.Font(None, 20)
        # setup draw_gui
        self.init_gui()
        # Create chips
        self.init_chips()
        self.cursor = None

    def init_hexagons(self, screen_size, radius):
        # Find all the "centers" that will fit on the screen
        centers = self.centers_visible(screen_size, radius)
        color = (200, 200, 200)
        self.hexagons = {c: Hexagon(centers[c], radius, color) for c in centers.keys()}

    def init_chips(self):
        self.chips = []
        # put chip at 0,0
        start_chip = self.create_chip()
        start_chip.set_grid_pos(self.hexagons[(0,0)])

    def create_chip(self):
        new_chip = Chip()
        new_chip.set_grid_pos(self.add_chip.hexagon)
        self.chips.append(new_chip)
        self.selected_chip = new_chip
        return new_chip

    def init_gui(self):
        self.add_chip = (PlusChip())
        self.add_chip.set_grid_pos(Hexagon((50, 50), 50, (0,0,0)))

    def centers_visible(self, screen_size, radius):
        """Return a mapping of on screen cords from their axial coords to their surface coords"""
        width = radius * 2
        height = math.sqrt(3) / 2 * width

        self.size = radius
        self.spacing_x = width * 3 / 4
        self.spacing_y = height
        self.orig_x = screen_size[0] / 2
        self.orig_y = screen_size[1] / 2

        col_limit = self.orig_x / width + 1
        row_limit = self.orig_y * 2 / int(height)

        coords = {}

        for col in range(-col_limit, col_limit + 1):
            for row in range(-row_limit, row_limit + 1):
                screen_coords = self.axial_to_screen((col, row))
                # screen_coords = self.hex_to_pixel((col, row))
                if GridDrawer.coords_in_surface(screen_coords, screen_size):
                    coords[(col, row)] = (screen_coords)

        # print coords
        return coords

    def axial_to_screen(self, (col, row)):
        """Return the center of the axial position as a screen position"""
        x = col * self.spacing_x + self.orig_x
        y = (row * self.spacing_y + self.orig_y) + (col * self.spacing_y / 2)
        return (x, y)

    def screen_to_axial(self, (x, y)):
        """Find the nearest axial center for the given screen position"""
        col_f = (x - (self.orig_x - self.spacing_x / 2)) / self.spacing_x
        row = round ( (y - (col_f * self.spacing_y / 2) - self.orig_y) / self.spacing_y )
        col = round (col_f)
        return (int(col), int(row))

    def clicked_chip(self, mouse_pos):
        for chip in self.chips:
            if chip.is_mouse_on(mouse_pos):
                return chip

    def chip_at_hexagon(self, pos):
        hexagon = self.hexagons[pos]
        if not hexagon:
            return None
        for chip in self.chips:
            if chip.hexagon == hexagon:
                return chip
        return None

    @staticmethod
    def coords_in_surface((x, y), (width, height)):
        return x >= 0 and x <= width and y >= 0 and y <= height

    def draw_hexagons(self):
        for hex in self.hexagons.keys():
            self.hexagons[hex].draw(self.screen)
            coord_str = "{}".format(hex)
            coord_text = self.font.render(coord_str, 0, (220, 220, 220))
            font_mid = map(operator.div, self.font.size(coord_str), (2, 2))
            text_pos = tuple(map(operator.sub, self.hexagons[hex].center, font_mid))
            self.screen.blit(coord_text, text_pos)

    def draw_chips(self):
        # Sort chips from top of screen down before drawing
        draw_chips = {}
        for chip in self.chips:
            if hasattr(chip, "hexagon"):
                # Sort by z, y then x
                draw_chips["{},{},{}".format("0", chip.hexagon.center[1], chip.hexagon.center[0])] = chip
        # Draw chips in sorted order
        for chip_key in sorted(draw_chips.keys()):
            draw_chips[chip_key].draw(self.screen)

    def draw_gui(self, mouse_hex):
        # Draw the "Add Chip" Icon
        self.add_chip.draw(self.screen)

        # Draw the selected chip, if one is selected
        if self.selected_chip:
            self.selected_chip.draw_outline(self.screen)

        # Draw hexagon outlines for mouse overs
        if self.hexagons.has_key(mouse_hex):
            chip = self.chip_at_hexagon(mouse_hex)
            if chip:
                chip.draw_outline(self.screen, (255, 150, 150), 10)
            else:
                self.hexagons[mouse_hex].draw(self.screen, (255, 150, 150))

    def run(self):
        """Draw the screen with a hexagon grid"""
        # Create a mouse over event
        mouse_hex = None

        # Loop
        while not self.done:
            # Clear Events
            click = None
            selected = None

            # Events
            for event in pygame.event.get():
                pos = pygame.mouse.get_pos()
                if event.type == pygame.QUIT:
                    self.done = True
                if event.type == pygame.MOUSEBUTTONUP:
                    # Check if we're on the gui first
                    if self.add_chip.is_mouse_on(pos):
                        selected = self.add_chip
                    # Then check if we're on an existing chip
                    if not selected:
                        selected = self.clicked_chip(pos)
                    # Otherwise check the grid pos
                    if not selected:
                        click = self.screen_to_axial(pos)
                if event.type == pygame.MOUSEMOTION:
                    mouse_hex = self.screen_to_axial(pos)

            # Update
            if selected:
                if selected == self.add_chip:
                    self.create_chip()
                else:
                    self.selected_chip = selected
            if self.selected_chip and click and self.hexagons.has_key(click):
                self.selected_chip.set_grid_pos(self.hexagons[click])
                self.selected_chip = None

            # Draw
            self.screen.fill((255,255,255))
            self.draw_hexagons()
            self.draw_chips()
            self.draw_gui(mouse_hex)

            pygame.display.update()

        # Tear down
        pygame.quit()
        sys.exit()

drawer = GridDrawer((800, 600), 50)
drawer.run()<commit_msg>Chips can now be stacked and unstacked.<commit_after>"""
Run file for PyHive
"""
import sys
import pygame
import math
import operator

class Hexagon(object):
    """Class for drawing a hollow hexagon"""

    def __init__(self, position, radius, color, line = 2, col = None, row = None):
        self.center = position
        self.radius = radius
        self.color = color
        self.line = line
        self.col = col
        self.row = row

    def hex_corner(self, i):
        """Get corner"""
        angle_deg = 60.0 * i
        angle_rad = math.pi / 180 * angle_deg
        return (self.center[0] + self.radius * math.cos(angle_rad),
                self.center[1] + self.radius * math.sin(angle_rad))

    def draw(self, surface, color = None, line = None):
        """Draw a hexagon"""
        if not color:
            color = self.color
        if not line:
            line = self.line
        points = [self.hex_corner(x) for x in range(6)]
        pygame.draw.polygon(surface, color, points, self.line)

    def __str__(self):
        return "Grid: ({col}, {row}), Pos: {pos}".format(col=self.col, row=self.row, pos=self.center)

class Chip(object):
    """Base class for drawing a chip on the board"""

    def __init__(self):
        self.offset = (-49, -55)
        self.stacked_chip = None
        self.covered_chip = None
        self.hexagon = None
        self.selection_hexagon = None

    def set_grid_pos(self, hexagon):
        self.unstack_chip()
        self.hexagon = hexagon
        if not self.selection_hexagon:
            self.selection_hexagon = Hexagon(hexagon.center, hexagon.radius, hexagon.color)
        self.selection_hexagon.center = tuple(map(operator.add, self.hexagon.center, (0, -12)))

    def draw(self, surface):
        """Draw the chip on top of the hexagon"""
        if self.hexagon:
            pos = tuple(map(operator.add, self.hexagon.center, self.offset))
            surface.blit(self.image, pos)

    def draw_outline(self, surface, color = (200, 200, 0), line = 10):
        """Draw the outline of the chip if it's placed"""
        if self.selection_hexagon:
            self.selection_hexagon.draw(surface, color, line)

    def is_mouse_on(self, mouse_pos):
        if self.hexagon:
            vector = tuple(map(operator.sub, self.hexagon.center, mouse_pos))
            magnatude = (vector[0] ** 2 + vector[1] ** 2) ** 0.5
            return magnatude < self.hexagon.radius

    def stack_on_chip(self, other_chip):
        if self != other_chip:
            # Set the grid position of the chip being stacked
            self.set_grid_pos(other_chip.selection_hexagon)
            # Not trying to stack a chip on itself
            other_chip.stacked_chip = self
            self.covered_chip = other_chip

    def unstack_chip(self):
        # Don't unstack a chip with another on top
        if self.stacked_chip:
            raise ValueError("Can't unstack a covered chip")
        if self.covered_chip:
            # Disassociate chips
            self.covered_chip.stacked_chip = None
            self.covered_chip = None
        self.stacked_chip = None
        self.selection_hexagon = None

    def top_of_stack(self):
        if self.stacked_chip:
            return self.stacked_chip.top_of_stack()
        else:
            return self

    def __str__(self):
        _type = type(self).__name__
        return "{type} - {pos}, on: {on}".format(type=_type, pos=self.hexagon, on=self.covered_chip)

class PlusChip(Chip):
    """Class for drawing a chip with a plus on it"""

    def __init__(self):
        super(PlusChip, self).__init__()
        icon = pygame.image.load("images/Plus.png").convert_alpha()
        self.image = pygame.image.load("images/BlankChip.png").convert_alpha()
        self.image.blit(icon, (0,0))

class BeeChip(Chip):
    """Class for drawing a chip with a bee on it"""

    def __init__(self):
        super(BeeChip, self).__init__()
        icon = pygame.image.load("images/Bee.png").convert_alpha()
        self.image = pygame.image.load("images/BlankChip.png").convert_alpha()
        self.image.blit(icon, (0,0))

class GridDrawer(object):
    """Class that draws a hexagon grid when run"""

    def __init__(self, screen_size, hex_size):
        # Bring up
        pygame.init()
        self.screen = pygame.display.set_mode(screen_size)
        self.done = False
        # create grid
        self.init_hexagons(screen_size, hex_size)
        self.font = pygame.font.Font(None, 20)
        # setup draw_gui
        self.init_gui()
        # Create chips
        self.init_chips()
        self.cursor = None

    def init_hexagons(self, screen_size, radius):
        # Find all the "centers" that will fit on the screen
        centers = self.centers_visible(screen_size, radius)
        color = (200, 200, 200)
        self.hexagons = {c: Hexagon(centers[c], radius, color, line = 1, col = c[0], row = c[1]) for c in centers.keys()}

    def init_chips(self):
        self.chips = []
        # put chip at 0,0
        start_chip = self.create_chip()
        start_chip.set_grid_pos(self.hexagons[(0,0)])

    def create_chip(self):
        new_chip = BeeChip()
        new_chip.set_grid_pos(self.add_chip.hexagon)
        self.chips.append(new_chip)
        self.selected_chip = new_chip
        return new_chip

    def init_gui(self):
        self.add_chip = (PlusChip())
        self.add_chip.set_grid_pos(Hexagon((50, 50), 50, (0,0,0)))

    def centers_visible(self, screen_size, radius):
        """Return a mapping of on screen cords from their axial coords to their surface coords"""
        width = radius * 2
        height = math.sqrt(3) / 2 * width

        self.size = radius
        self.spacing_x = width * 3 / 4
        self.spacing_y = height
        self.orig_x = screen_size[0] / 2
        self.orig_y = screen_size[1] / 2

        col_limit = self.orig_x / width + 1
        row_limit = self.orig_y * 2 / int(height)

        coords = {}

        for col in range(-col_limit, col_limit + 1):
            for row in range(-row_limit, row_limit + 1):
                screen_coords = self.axial_to_screen((col, row))
                # screen_coords = self.hex_to_pixel((col, row))
                if GridDrawer.coords_in_surface(screen_coords, screen_size):
                    coords[(col, row)] = (screen_coords)

        # print coords
        return coords

    def axial_to_screen(self, (col, row)):
        """Return the center of the axial position as a screen position"""
        x = col * self.spacing_x + self.orig_x
        y = (row * self.spacing_y + self.orig_y) + (col * self.spacing_y / 2)
        return (x, y)

    def screen_to_axial(self, (x, y)):
        """Find the nearest axial center for the given screen position"""
        col_f = (x - (self.orig_x - self.spacing_x / 2)) / self.spacing_x
        row = round ( (y - (col_f * self.spacing_y / 2) - self.orig_y) / self.spacing_y )
        col = round (col_f)
        return (int(col), int(row))

    def clicked_chip(self, mouse_pos):
        for chip in self.chips:
            if chip.is_mouse_on(mouse_pos):
                return chip.top_of_stack()

    def chip_at_hexagon(self, pos):
        hexagon = self.hexagons[pos]
        if not hexagon:
            return None
        for chip in self.chips:
            if chip.hexagon == hexagon:
                return chip
        return None

    @staticmethod
    def coords_in_surface((x, y), (width, height)):
        return x >= 0 and x <= width and y >= 0 and y <= height

    def draw_hexagons(self):
        for hex in self.hexagons.keys():
            self.hexagons[hex].draw(self.screen)
            coord_str = "{}".format(hex)
            coord_text = self.font.render(coord_str, 0, (220, 220, 220))
            font_mid = map(operator.div, self.font.size(coord_str), (2, 2))
            text_pos = tuple(map(operator.sub, self.hexagons[hex].center, font_mid))
            self.screen.blit(coord_text, text_pos)

    def draw_chips(self):
        # Sort chips from top of screen down before drawing
        draw_chips = {}
        for chip in self.chips:
            z_pos = 0
            while chip and chip.hexagon:
                # Sort by z, y then x
                draw_chips["{},{},{}".format(z_pos, chip.hexagon.center[1], chip.hexagon.center[0])] = chip
                # Move up a layer
                chip = chip.stacked_chip
                z_pos += 1

        # Draw chips in sorted order
        for chip_key in sorted(draw_chips.keys()):
            draw_chips[chip_key].draw(self.screen)

    def print_chip_debug(self):
        print "----------\nChip debug\n=========="
        for chip in self.chips:
            print str(chip)

    def draw_gui(self, mouse_hex):
        # Draw the "Add Chip" Icon
        self.add_chip.draw(self.screen)

        # Draw the selected chip, if one is selected
        if self.selected_chip:
            self.selected_chip.draw_outline(self.screen)

        # Draw hexagon outlines for mouse overs
        if self.hexagons.has_key(mouse_hex):
            chip = self.chip_at_hexagon(mouse_hex)
            if chip:
                chip.top_of_stack().draw_outline(self.screen, (255, 150, 150), 10)
            else:
                self.hexagons[mouse_hex].draw(self.screen, (255, 150, 150))

    def run(self):
        """Draw the screen with a hexagon grid"""
        # Constants
        LEFT = 1
        RIGHT = 3

        # Create a mouse over event
        mouse_hex = None

        # Loop
        while not self.done:
            # Clear Events
            click = None
            selected = None

            # Events
            for event in pygame.event.get():
                pos = pygame.mouse.get_pos()
                if event.type == pygame.QUIT:
                    self.done = True
                if event.type == pygame.MOUSEBUTTONUP:
                    if event.button == LEFT:
                        # Check if we're on the gui first
                        if self.add_chip.is_mouse_on(pos):
                            selected = self.add_chip
                        # Then check if we're on an existing chip
                        if not selected:
                            selected = self.clicked_chip(pos)
                        # Otherwise check the grid pos
                        if not selected:
                            click = self.screen_to_axial(pos)
                    if event.button == RIGHT:
                        if self.add_chip.is_mouse_on(pos):
                            self.print_chip_debug()
                if event.type == pygame.MOUSEMOTION:
                    mouse_hex = self.screen_to_axial(pos)

            # Update
            if selected:
                # A chip has been click with the mouse
                if selected == self.add_chip:
                    # It was the "Add a chip" chip
                    self.create_chip()
                else:
                    # It was a game chip, check if we're selecting or moving
                    if self.selected_chip:
                        # Stack the selected chip onto this on
                        self.selected_chip.stack_on_chip(selected)
                        # Unselect the selected chip now
                        self.selected_chip = None
                    else:
                        # Set the chip at the top of the selected stack to be the currently selected
                        self.selected_chip = selected.top_of_stack()
            if self.selected_chip and click and self.hexagons.has_key(click):
                self.selected_chip.set_grid_pos(self.hexagons[click])
                self.selected_chip = None

            # Draw
            self.screen.fill((255,255,255))
            self.draw_hexagons()
            self.draw_chips()
            self.draw_gui(mouse_hex)

            pygame.display.update()

        # Tear down
        pygame.quit()
        sys.exit()

drawer = GridDrawer((800, 600), 50)
drawer.run()<|endoftext|>


<commit_before>#!/usr/bin/env python3

import numpy as np
import torch

import matplotlib
import matplotlib.pyplot as plt
from torch.autograd import Variable

from itertools import chain
import copy
import atexit
import sys
import argparse

class PhnSpkGenerator():
    def __init__(self, mu, cov, phn, spk):
        self._mu = mu
        self._cov = cov
        self._phn = phn
        self._spk = spk

    def generate(self, N):
        X = np.random.multivariate_normal(self._mu, self._cov, size=N)
        phn = torch.ones(N) * self._phn
        spk = torch.ones(N) * self._spk
        return torch.from_numpy(X).float(), phn, spk

class Plotter():
    def __init__(self):
        atexit.register(plt.show)
        self._cmap = matplotlib.colors.ListedColormap([
            (1, 0, 0),
            (0, 1, 0),
            (0, 0, 1)
        ])

    def plot(self, X, phn, spk, name="fig", transform = lambda x:x):
        plt.figure(name)

        for i, m in enumerate(['o', '+', 'x']):
            mask = (spk.numpy() == i)
            spk_set = X.numpy()[mask]
            spk_set = Variable(torch.from_numpy(spk_set).float())
            spk_set = transform(spk_set).data.numpy()
            plt.scatter(spk_set[:,0], spk_set[:,1],
                        c=t_phn.numpy()[mask], cmap=self._cmap, marker=m)
        plt.show(block=False)

def epoch(fwd, params, X, target, batch_size=16, shuffle=True, train=True):
    N = X.size()[0]
    assert target.size()[0] == N

    train_X = X
    train_t = target
    if shuffle:
        p = np.random.permutation(N)
        train_X = X.numpy()[p]
        train_t = target.numpy()[p]

    train_X = torch.from_numpy(train_X)
    train_t = torch.from_numpy(train_t)

    nb_batches = N // batch_size
    total = nb_batches * batch_size
    total_loss = 0.0
    correct = 0

    criterion = torch.nn.NLLLoss()
    optim = torch.optim.SGD(params, lr=1e-3)

    for i in range(nb_batches):
        batch_X = Variable(train_X[i*batch_size:(i+1)*batch_size])
        batch_t = Variable(train_t[i*batch_size:(i+1)*batch_size])

        y = fwd(batch_X)
        loss = criterion(y, batch_t)
        _, preds = y.max(dim=1)
        correct += (preds == batch_t).sum().data[0]

        total_loss += loss.data[0]

        if train:
            optim.zero_grad()
            loss.backward()
            optim.step()

    return total_loss/nb_batches, correct/total

def dual_target_epoch(common, decoders, params, X, targets, batch_size=16, shuffle=True):
    assert len(decoders) == len(targets)
    N = X.size()[0]
    for t in targets:
        assert t.size()[0] == N

    # TODO: clone?
    train_X = X
    train_targets = targets
    if shuffle:
        p = np.random.permutation(N)
        train_X = X.numpy()[p]
        train_X = torch.from_numpy(train_X)
        for i, t in enumerate(train_targets):
            train_targets[i] = torch.from_numpy(t.numpy()[p])

    nb_batches = N // batch_size
    total = nb_batches * batch_size
    cum_losses = []
    nb_correct = []
    for i in range(len(decoders)):
        cum_losses.append(0.0)
        nb_correct.append(0)

    criterion = torch.nn.NLLLoss()
    optim = torch.optim.SGD(params, lr=1e-3)

    for i in range(nb_batches):
        batch_X = Variable(train_X[i*batch_size:(i+1)*batch_size])
        batch_ts = []
        for t in train_targets:
            batch_ts.append(Variable(t[i*batch_size:(i+1)*batch_size]))

        repre = common(batch_X)

        losses = []
        for i, (dec, t) in enumerate(zip(decoders, batch_ts)):
            y = dec(repre)
            loss = criterion(y, t)
            losses.append(loss)
            _, preds = y.max(dim=1)
            nb_correct[i] += (preds == t).sum().data[0]
            cum_losses[i] += loss.data[0]

        complete_loss = sum(losses)

        optim.zero_grad()
        complete_loss.backward()
        optim.step()

    return cum_losses[0]/nb_batches, nb_correct[0]/total, cum_losses[1]/nb_batches, nb_correct[1]/total

def instantiate_generators():
    phn_mus = []
    phn_mus.append(np.asarray([1,1]))
    phn_mus.append(np.asarray([3.5,2]))
    phn_mus.append(np.asarray([2,4]))

    phn_covs = []
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))

    spk_mus = []
    spk_mus.append(np.asarray([-0.7, 0.7]))
    spk_mus.append(np.asarray([1, 0]))
    spk_mus.append(np.asarray([-0.7, -0.7]))

    gens = []
    for phn, (phn_mu, phn_cov) in enumerate(zip(phn_mus, phn_covs)):
        for spk, spk_mu in enumerate(spk_mus):
            gens.append(PhnSpkGenerator(phn_mu+spk_mu, phn_cov, phn, spk))

    return gens

def generate(gens, N_per_cluster):
    X = torch.zeros((0, 2))
    t_phn = torch.zeros((0,))
    t_spk = torch.zeros((0,))

    for g in gens:
        X_g, phn_g, spk_g = g.generate(100)
        X = torch.cat([X, X_g], 0)
        t_phn = torch.cat([t_phn, phn_g], 0)
        t_spk = torch.cat([t_spk, spk_g], 0)
    t_phn = t_phn.long()
    t_spk = t_spk.long()

    return X, t_phn, t_spk

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--nb-epochs", type=int, default=200,
                        help="number of training epochs")
    args = parser.parse_args()

    gens = instantiate_generators()

    X, t_phn, t_spk = generate(gens, 100)
    X_val, t_phn_val, t_spk_val = generate(gens, 100)

    plotter = Plotter()
    #plotter.plot(X, t_phn, t_spk, name="Raw data")

    bn_extractor = torch.nn.Sequential(
        torch.nn.Linear(2, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 2),
    )

    bn_backup = copy.deepcopy(bn_extractor)

    plotter.plot(X, t_phn, t_spk, name="BN features, random init", transform=bn_extractor)

    phn_decoder = torch.nn.Sequential(
        torch.nn.Linear(2,10),
        torch.nn.ReLU(),
        torch.nn.Linear(10,3),
        torch.nn.LogSoftmax()
    )
    phn_backup = copy.deepcopy(phn_decoder)

    print("Training PHN network")
    for i in range(args.nb_epochs):
        ce, acc = epoch(lambda x: phn_decoder(bn_extractor(x)),
                        chain(bn_extractor.parameters(), phn_decoder.parameters()),
                        X, t_phn)
        val_ce, val_acc = epoch(lambda x: phn_decoder(bn_extractor(x)),
                        chain(bn_extractor.parameters(), phn_decoder.parameters()),
                        X, t_phn, train=False)
        if i % 25 == 24:
            string = "{:>3} phn CE: {:.3f}, phn Acc: {:2.2f} | Valid: CE {:.3f} Acc {:.3f}".format(
                i, ce, 100.0*acc, val_ce, 100.0*val_acc
            )
            print(string)

    plotter.plot(X, t_phn, t_spk, name="BN features, PHN optimized", transform=bn_extractor)

    spk_decoder = torch.nn.Sequential(
        torch.nn.Linear(2,10),
        torch.nn.ReLU(),
        torch.nn.Linear(10,3),
        torch.nn.LogSoftmax()
    )
    spk_backup = copy.deepcopy(spk_decoder)

    print("Training SPK decoder")
    for i in range(args.nb_epochs):
        ce, acc = epoch(lambda x: spk_decoder(bn_extractor(x)),
                        spk_decoder.parameters(), X, t_spk)
        val_ce, val_acc = epoch(lambda x: spk_decoder(bn_extractor(x)),
                        spk_decoder.parameters(), X, t_spk)
        if i % 25 == 24:
            string = "{:>3} spk CE: {:.3f}, spk Acc: {:2.2f} | Valid: CE {:.3f} Acc {:.3f}".format(
                i, ce, 100.0*acc, val_ce, 100.0*val_acc
            )
            print(string)

    print("Training jointly, from same init:")
    for i in range(args.nb_epochs):
        phn_ce, phn_acc, spk_ce, spk_acc = dual_target_epoch(
            bn_backup, [phn_backup, spk_backup],
            chain(bn_backup.parameters(), phn_backup.parameters(), spk_backup.parameters()),
            X, [t_phn, t_spk]
        )
        if i % 25 == 24:
            string = "{:>3} phn CE: {:.3f}, phn Acc: {:2.2f}, spk CE: {:.3f}, spk Acc: {:2.2f}".format(
                i, phn_ce, 100.0*phn_acc, spk_ce, 100.0*spk_acc
            )
            print(string)
    plotter.plot(X, t_phn, t_spk, name="BN features, PHN+SPK optimized", transform=bn_backup)
<commit_msg>train(): factor it out of the main()<commit_after>#!/usr/bin/env python3

import numpy as np
import torch

import matplotlib
import matplotlib.pyplot as plt
from torch.autograd import Variable

from itertools import chain
import copy
import atexit
import sys
import argparse

class PhnSpkGenerator():
    def __init__(self, mu, cov, phn, spk):
        self._mu = mu
        self._cov = cov
        self._phn = phn
        self._spk = spk

    def generate(self, N):
        X = np.random.multivariate_normal(self._mu, self._cov, size=N)
        phn = torch.ones(N) * self._phn
        spk = torch.ones(N) * self._spk
        return torch.from_numpy(X).float(), phn, spk

class Plotter():
    def __init__(self):
        atexit.register(plt.show)
        self._cmap = matplotlib.colors.ListedColormap([
            (1, 0, 0),
            (0, 1, 0),
            (0, 0, 1)
        ])

    def plot(self, X, phn, spk, name="fig", transform = lambda x:x):
        plt.figure(name)

        for i, m in enumerate(['o', '+', 'x']):
            mask = (spk.numpy() == i)
            spk_set = X.numpy()[mask]
            spk_set = Variable(torch.from_numpy(spk_set).float())
            spk_set = transform(spk_set).data.numpy()
            plt.scatter(spk_set[:,0], spk_set[:,1],
                        c=t_phn.numpy()[mask], cmap=self._cmap, marker=m)
        plt.show(block=False)

def epoch(fwd, params, X, target, batch_size=16, shuffle=True, train=True):
    N = X.size()[0]
    assert target.size()[0] == N

    train_X = X
    train_t = target
    if shuffle:
        p = np.random.permutation(N)
        train_X = X.numpy()[p]
        train_t = target.numpy()[p]

    train_X = torch.from_numpy(train_X)
    train_t = torch.from_numpy(train_t)

    nb_batches = N // batch_size
    total = nb_batches * batch_size
    total_loss = 0.0
    correct = 0

    criterion = torch.nn.NLLLoss()
    optim = torch.optim.SGD(params, lr=1e-3)

    for i in range(nb_batches):
        batch_X = Variable(train_X[i*batch_size:(i+1)*batch_size])
        batch_t = Variable(train_t[i*batch_size:(i+1)*batch_size])

        y = fwd(batch_X)
        loss = criterion(y, batch_t)
        _, preds = y.max(dim=1)
        correct += (preds == batch_t).sum().data[0]

        total_loss += loss.data[0]

        if train:
            optim.zero_grad()
            loss.backward()
            optim.step()

    return total_loss/nb_batches, correct/total

def dual_target_epoch(common, decoders, params, X, targets, batch_size=16, shuffle=True):
    assert len(decoders) == len(targets)
    N = X.size()[0]
    for t in targets:
        assert t.size()[0] == N

    # TODO: clone?
    train_X = X
    train_targets = targets
    if shuffle:
        p = np.random.permutation(N)
        train_X = X.numpy()[p]
        train_X = torch.from_numpy(train_X)
        for i, t in enumerate(train_targets):
            train_targets[i] = torch.from_numpy(t.numpy()[p])

    nb_batches = N // batch_size
    total = nb_batches * batch_size
    cum_losses = []
    nb_correct = []
    for i in range(len(decoders)):
        cum_losses.append(0.0)
        nb_correct.append(0)

    criterion = torch.nn.NLLLoss()
    optim = torch.optim.SGD(params, lr=1e-3)

    for i in range(nb_batches):
        batch_X = Variable(train_X[i*batch_size:(i+1)*batch_size])
        batch_ts = []
        for t in train_targets:
            batch_ts.append(Variable(t[i*batch_size:(i+1)*batch_size]))

        repre = common(batch_X)

        losses = []
        for i, (dec, t) in enumerate(zip(decoders, batch_ts)):
            y = dec(repre)
            loss = criterion(y, t)
            losses.append(loss)
            _, preds = y.max(dim=1)
            nb_correct[i] += (preds == t).sum().data[0]
            cum_losses[i] += loss.data[0]

        complete_loss = sum(losses)

        optim.zero_grad()
        complete_loss.backward()
        optim.step()

    return cum_losses[0]/nb_batches, nb_correct[0]/total, cum_losses[1]/nb_batches, nb_correct[1]/total

def instantiate_generators():
    phn_mus = []
    phn_mus.append(np.asarray([1,1]))
    phn_mus.append(np.asarray([3.5,2]))
    phn_mus.append(np.asarray([2,4]))

    phn_covs = []
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))
    phn_covs.append(np.asarray([[0.2,0], [0,0.2]]))

    spk_mus = []
    spk_mus.append(np.asarray([-0.7, 0.7]))
    spk_mus.append(np.asarray([1, 0]))
    spk_mus.append(np.asarray([-0.7, -0.7]))

    gens = []
    for phn, (phn_mu, phn_cov) in enumerate(zip(phn_mus, phn_covs)):
        for spk, spk_mu in enumerate(spk_mus):
            gens.append(PhnSpkGenerator(phn_mu+spk_mu, phn_cov, phn, spk))

    return gens

def generate(gens, N_per_cluster):
    X = torch.zeros((0, 2))
    t_phn = torch.zeros((0,))
    t_spk = torch.zeros((0,))

    for g in gens:
        X_g, phn_g, spk_g = g.generate(100)
        X = torch.cat([X, X_g], 0)
        t_phn = torch.cat([t_phn, phn_g], 0)
        t_spk = torch.cat([t_spk, spk_g], 0)
    t_phn = t_phn.long()
    t_spk = t_spk.long()

    return X, t_phn, t_spk

def train(fwd, params, X, t, nb_epochs, report_interval=25):
    params = list(params)
    for i in range(nb_epochs):
        ce, acc = epoch(fwd, params, X, t)
        val_ce, val_acc = epoch(fwd, params, X, t, train=False)

        if i % report_interval == report_interval - 1:
            string = "{:>3} phn CE: {:.3f}, phn Acc: {:2.2f} | Valid: CE {:.3f} Acc {:.3f}".format(
                i, ce, 100.0*acc, val_ce, 100.0*val_acc
            )
            print(string)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--nb-epochs", type=int, default=200,
                        help="number of training epochs")
    args = parser.parse_args()

    gens = instantiate_generators()

    X, t_phn, t_spk = generate(gens, 100)
    X_val, t_phn_val, t_spk_val = generate(gens, 100)

    plotter = Plotter()
    #plotter.plot(X, t_phn, t_spk, name="Raw data")

    bn_extractor = torch.nn.Sequential(
        torch.nn.Linear(2, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 2),
    )

    bn_backup = copy.deepcopy(bn_extractor)

    plotter.plot(X, t_phn, t_spk, name="BN features, random init", transform=bn_extractor)

    phn_decoder = torch.nn.Sequential(
        torch.nn.Linear(2,10),
        torch.nn.ReLU(),
        torch.nn.Linear(10,3),
        torch.nn.LogSoftmax()
    )
    phn_backup = copy.deepcopy(phn_decoder)

    print("Training PHN network")
    train(lambda x: phn_decoder(bn_extractor(x)),
          chain(bn_extractor.parameters(), phn_decoder.parameters()),
          X, t_phn, args.nb_epochs)

    plotter.plot(X, t_phn, t_spk, name="BN features, PHN optimized", transform=bn_extractor)

    spk_decoder = torch.nn.Sequential(
        torch.nn.Linear(2,10),
        torch.nn.ReLU(),
        torch.nn.Linear(10,3),
        torch.nn.LogSoftmax()
    )
    spk_backup = copy.deepcopy(spk_decoder)

    print("Training SPK decoder")
    train(lambda x: spk_decoder(bn_extractor(x)),
          spk_decoder.parameters(), X, t_spk, args.nb_epochs)

    print("Training jointly, from same init:")
    for i in range(args.nb_epochs):
        phn_ce, phn_acc, spk_ce, spk_acc = dual_target_epoch(
            bn_backup, [phn_backup, spk_backup],
            chain(bn_backup.parameters(), phn_backup.parameters(), spk_backup.parameters()),
            X, [t_phn, t_spk]
        )
        if i % 25 == 24:
            string = "{:>3} phn CE: {:.3f}, phn Acc: {:2.2f}, spk CE: {:.3f}, spk Acc: {:2.2f}".format(
                i, phn_ce, 100.0*phn_acc, spk_ce, 100.0*spk_acc
            )
            print(string)
    plotter.plot(X, t_phn, t_spk, name="BN features, PHN+SPK optimized", transform=bn_backup)
<|endoftext|>


<commit_before>#! /usr/bin/env python3
"""
Runs counterpartyd or the counterpartyd test suite via the python interpreter in its virtualenv on both Linux and Windows
"""
import os
import sys
import subprocess

assert os.name in ("nt", "posix")

#under *nix, script must NOT be run as root
if os.name == "posix" and os.geteuid() == 0:
    print("Please run this script as a non-root user.")
    sys.exit(1)

run = None
if len(sys.argv) >= 2 and sys.argv[1] == 'tests':
    args = sys.argv[2:]
    run = 'tests'
elif len(sys.argv) >= 2 and sys.argv[1] == 'counterblockd':
    args = sys.argv[2:]
    run = 'counterblockd'
elif len(sys.argv) >= 2 and sys.argv[1] == 'armory_utxsvr':
    args = sys.argv[2:]
    run = 'armory_utxsvr'
else:
    args = sys.argv[1:]
    run = 'counterpartyd'

base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
env_path = os.path.join(base_path, "env")
dist_path = os.path.join(base_path, "dist")
python_path = os.path.join(env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")

def delete_lockfile(component):
    import appdirs #installed earlier
    import glob
    running_testnet = "--testnet" in args
    data_dir = appdirs.user_data_dir(appauthor='Counterparty',
        appname="%s%s" % (component, "-testnet" if running_testnet else ''), roaming=True)
    lockfile_paths = glob.glob(os.path.join("%s%scounterpartyd.*.db.lock" % (data_dir, os.sep)))
    for p in lockfile_paths:
        print("Removing stale lock file at '%s'" % p)
        os.remove(p)

if run == 'tests':
    pytest_path = os.path.join(env_path, "Scripts" if os.name == "nt" else "bin", "py.test.exe" if os.name == "nt" else "py.test")
    counterpartyd_tests_path = os.path.join(dist_path, "counterpartyd", "test", "test_.py")
    command = "%s %s %s" % (pytest_path, counterpartyd_tests_path, ' '.join(args))
elif run == 'counterblockd':
    delete_lockfile("counterblockd")
    counterblockd_env_path = os.path.join(base_path, "env.counterblockd")
    counterblockd_python_path = os.path.join(counterblockd_env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")
    counterblockd_path = os.path.join(dist_path, "counterblockd", "counterblockd.py")
    command = "%s %s %s" % (counterblockd_python_path, counterblockd_path, ' '.join(args))
elif run == 'armory_utxsvr':
    armory_utxsvr_env_path = os.path.join(base_path, "env.counterblockd") #use the counterblock venv
    armory_utxsvr_python_path = os.path.join(armory_utxsvr_env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")
    armory_utxsvr_path = os.path.join(dist_path, "counterblockd", "armory_utxsvr.py")
    command = "DISPLAY=localhost:1.0 xvfb-run --auto-servernum %s %s %s" % (armory_utxsvr_python_path, armory_utxsvr_path, ' '.join(args))
else:
    assert run == 'counterpartyd'
    delete_lockfile("counterpartyd")
    counterpartyd_path = os.path.join(dist_path, "counterpartyd", "counterpartyd.py")
    command = "%s %s %s" % (python_path, counterpartyd_path, ' '.join(args))

status = subprocess.call(command, shell=True)
sys.exit(status)
<commit_msg>fix up run.py a bit....<commit_after>#! /usr/bin/env python3
"""
Runs counterpartyd or the counterpartyd test suite via the python interpreter in its virtualenv on both Linux and Windows
"""
import os
import sys
import subprocess

assert os.name in ("nt", "posix")

#under *nix, script must NOT be run as root
if os.name == "posix" and os.geteuid() == 0:
    print("Please run this script as a non-root user.")
    sys.exit(1)

run = None
if len(sys.argv) >= 2 and sys.argv[1] == 'tests':
    args = sys.argv[2:]
    run = 'tests'
elif len(sys.argv) >= 2 and sys.argv[1] == 'counterblockd':
    args = sys.argv[2:]
    run = 'counterblockd'
elif len(sys.argv) >= 2 and sys.argv[1] == 'armory_utxsvr':
    args = sys.argv[2:]
    run = 'armory_utxsvr'
else:
    args = sys.argv[1:]
    run = 'counterpartyd'

base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
env_path = os.path.join(base_path, "env")
dist_path = os.path.join(base_path, "dist")
python_path = os.path.join(env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")

def delete_counterpartyd_lockfile():
    import appdirs #installed earlier
    import glob
    running_testnet = "--testnet" in args
    data_dir = appdirs.user_data_dir(appauthor='Counterparty',
        appname="counterpartyd%s" % ("-testnet" if running_testnet else '',), roaming=True)
    lockfile_paths = glob.glob(os.path.join("%s%scounterpartyd.*.db.lock" % (data_dir, os.sep)))
    for p in lockfile_paths:
        print("Removing stale lock file at '%s'" % p)
        os.remove(p)

if run == 'tests':
    pytest_path = os.path.join(env_path, "Scripts" if os.name == "nt" else "bin", "py.test.exe" if os.name == "nt" else "py.test")
    counterpartyd_tests_path = os.path.join(dist_path, "counterpartyd", "test", "test_.py")
    command = "%s %s %s" % (pytest_path, counterpartyd_tests_path, ' '.join(args))
elif run == 'counterblockd':
    counterblockd_env_path = os.path.join(base_path, "env.counterblockd")
    counterblockd_python_path = os.path.join(counterblockd_env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")
    counterblockd_path = os.path.join(dist_path, "counterblockd", "counterblockd.py")
    command = "%s %s %s" % (counterblockd_python_path, counterblockd_path, ' '.join(args))
elif run == 'armory_utxsvr':
    armory_utxsvr_env_path = os.path.join(base_path, "env.counterblockd") #use the counterblock venv
    armory_utxsvr_python_path = os.path.join(armory_utxsvr_env_path, "Scripts" if os.name == "nt" else "bin", "python.exe" if os.name == "nt" else "python")
    armory_utxsvr_path = os.path.join(dist_path, "counterblockd", "armory_utxsvr.py")
    command = "DISPLAY=localhost:1.0 xvfb-run --auto-servernum %s %s %s" % (armory_utxsvr_python_path, armory_utxsvr_path, ' '.join(args))
else:
    assert run == 'counterpartyd'
    delete_counterpartyd_lockfile()
    counterpartyd_path = os.path.join(dist_path, "counterpartyd", "counterpartyd.py")
    command = "%s %s %s" % (python_path, counterpartyd_path, ' '.join(args))

status = subprocess.call(command, stderr=subprocess.STDOUT, shell=True)
sys.exit(status)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

from app import app
app.run(debug=True)
<commit_msg>添加命令行选项<commit_after>#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

from app import app
from flask.ext.script import Manager
manager = Manager(app)

if __name__ == '__main__':
    manager.run()
<|endoftext|>


<commit_before>import game

import Tkinter as tk
def keypress(event):
    if event.keysym == 'Return':
        root.destroy()
root = tk.Tk()
print "Press Enter to start:"
root.bind_all('<Key>', keypress)
# don't show the tk window
root.withdraw()
root.mainloop()

stop = False
while not stop:
	game = reload(game)
	stop = game.run()

<commit_msg>modify main.py<commit_after>import game

import Tkinter as tk
def keypress(event):
    if event.keysym == 'Return':
        root.destroy()
root = tk.Tk()
print "Press Enter to start:"
root.bind_all('<Key>', keypress)
# don't show the tk window
root.withdraw()
root.mainloop()

stop = False

##############################
#         main loop          #
##############################
while not stop:

	#generate() here

	game = reload(game)
	stop = game.run()

<|endoftext|>


<commit_before>from __future__ import print_function
from satella.unix import hang_until_sig
from eunike.config import load_config
from eunike.routing import RoutingLayer
from eunike.instrumentation import InstrumentationSaverThread
from satella.instrumentation import CounterCollection
import sys

# Load configuration
cnf = load_config()

# Check whether all modules are present

# By doing that annotate OXMs with "module" field containing
# relevant OXMInterface object
for oxmcnf in cnf['oxms']:
    try:
        oxmcnf['__module'] = __import__('eunike.oxm.%s' % (oxmcnf['type'], ),
                             (), (), 'OXMInterface', 0).OXMInterface
    except ImportError:
        print('OXM %s not installed' % (oxmcnf['type'], ))
        sys.exit()
    except:
        print('Error loading OXM %s' % (oxmcnf['type'], ))
        sys.exit()

# By doing that annotate OAMs with "module" field containing
# relevant OAMInterface object
for oamcnf in cnf['oams']:
    try:
        oamcnf['__module'] = __import__('eunike.oam.%s' % (oamcnf['type'], ),
                             (), (), 'OAMInterface', 0).OAMInterface
    except ImportError:
        print('OAM %s not installed' % (oamcnf['type'], ))
        sys.exit()
    except:
        print('Error loading OAM %s' % (oamcnf['type'], ))
        sys.exit()

# Transpose OAM and OXM's to an array of (handle, class)
oams = [(x['handle'], x['__module']) for x in cnf['oams']]
oxms = [(x['handle'], x['__module']) for x in cnf['oxms']]

# Prepare OSM
try:
    osm = __import__('eunike.osm.%s' % (cnf['osm']['type'], ),
                     (), (), 'OSMInterface', 0).OSMInterface(
                     cnf['osm'])
    osm.i_start()
except ImportError:
    print('Failed to load OSM')
    sys.exit()

# Prepare insmgr
insmgr = CounterCollection('counters')

# Prepare saver thread (if necessary)
if 'instrumentation' in cnf:
    if cnf['instrumentation']['enabled']:
        saver = InstrumentationSaverThread(insmgr, cnf['instrumentation'])
        saver.start()

# Prepare RL
rl = RoutingLayer(cnf, dict(oams), dict(oxms), insmgr, osm).start()

from satella.contrib.bhtipi import BHTIPI

bt = BHTIPI('127.0.0.1', 8000, insmgr).start()

hang_until_sig()

try:
    saver.terminate()
except:
    pass
bt.terminate()
rl.terminate()
osm.i_stop()
rl.join()
bt.join()
osm.i_join()
try:
    saver.join()
except:
    pass
<commit_msg>BHTIPI reference removed<commit_after>from __future__ import print_function
from satella.unix import hang_until_sig
from eunike.config import load_config
from eunike.routing import RoutingLayer
from eunike.instrumentation import InstrumentationSaverThread
from satella.instrumentation import CounterCollection
import sys

# Load configuration
cnf = load_config()

# Check whether all modules are present

# By doing that annotate OXMs with "module" field containing
# relevant OXMInterface object
for oxmcnf in cnf['oxms']:
    try:
        oxmcnf['__module'] = __import__('eunike.oxm.%s' % (oxmcnf['type'], ),
                             (), (), 'OXMInterface', 0).OXMInterface
    except ImportError:
        print('OXM %s not installed' % (oxmcnf['type'], ))
        sys.exit()
    except:
        print('Error loading OXM %s' % (oxmcnf['type'], ))
        sys.exit()

# By doing that annotate OAMs with "module" field containing
# relevant OAMInterface object
for oamcnf in cnf['oams']:
    try:
        oamcnf['__module'] = __import__('eunike.oam.%s' % (oamcnf['type'], ),
                             (), (), 'OAMInterface', 0).OAMInterface
    except ImportError:
        print('OAM %s not installed' % (oamcnf['type'], ))
        sys.exit()
    except:
        print('Error loading OAM %s' % (oamcnf['type'], ))
        sys.exit()

# Transpose OAM and OXM's to an array of (handle, class)
oams = [(x['handle'], x['__module']) for x in cnf['oams']]
oxms = [(x['handle'], x['__module']) for x in cnf['oxms']]

# Prepare OSM
try:
    osm = __import__('eunike.osm.%s' % (cnf['osm']['type'], ),
                     (), (), 'OSMInterface', 0).OSMInterface(
                     cnf['osm'])
    osm.i_start()
except ImportError:
    print('Failed to load OSM')
    sys.exit()

# Prepare insmgr
insmgr = CounterCollection('counters')

# Prepare saver thread (if necessary)
if 'instrumentation' in cnf:
    if cnf['instrumentation']['enabled']:
        saver = InstrumentationSaverThread(insmgr, cnf['instrumentation'])
        saver.start()

# Prepare RL
rl = RoutingLayer(cnf, dict(oams), dict(oxms), insmgr, osm).start()

hang_until_sig()

try:
    saver.terminate()
except:
    pass
rl.terminate()
osm.i_stop()
rl.join()
osm.i_join()
try:
    saver.join()
except:
    pass
<|endoftext|>


<commit_before>#!/usr/bin/python

import os, sys, getopt
import itertools as it
sys.path.append(os.path.dirname(__file__) + "/src")
from pandocLatex import *

latexEngine="lualatex"
highlightstyle='"tango"' #pygments, kate, monochrome, espresso, zenburn, haddock, tango
template="template/document.latex"
beamer="template/beamer.latex"

docFormat = [
    "template/format_howto.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/titlepage.yaml",
    "template/typography_sans.yaml"
    ]

docOptions = [
        "-t latex",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--filter pandoc-csv2table",
        "--filter pandoc-crossref",
# 	"--filter diagrams-pandoc",
#       "--filter pandoc-placetable", # compiled with inlinemarkdown
        "--filter pandoc-citeproc",
        "--template={template}".format(template=template),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
        "--number-sections",
        "--chapter",
        "-M synctex:yes"
	]

beamerFormat = [
    "template/format_beamer.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/typography_lmodern.yaml"
    ]

beamerOptions = [
        "-t beamer",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--filter pandoc-csv2table",
        "--filter pandoc-crossref",
# 	"--filter diagrams-pandoc",
#       "--filter pandoc-placetable", # compiled with inlinemarkdown
        "--filter pandoc-citeproc",
        "--template={template}".format(template=beamer),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
        "--number-sections",
        "-M synctex:yes"
	]

tikzFormat = [
    "template/format_tikz.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/titlepage.yaml",
    "template/typography_sans.yaml"
    ]

tikzOptions= [
        "-t latex",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--template={template}".format(template=template),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
	]

# Convert Markdown to Latex, using a latex template and YAML configuration
def genPandocCmd(out, src, format, options):
        return cmdObj(
            " ".join(["pandoc"] +
            		 format +
            		    src +
                ["-o {out}".format(out=out)] +
            		options),
            True,
            before=[(print,("-----\t","Pandoc\t{out}\t".format(out=out),"-----"),{})],
            # Adjust appearance of tables and figures
            #after =[(applyOnFile, ([adjustLongtableFilter,centerFigureFilter],texFile) ,{})]
            after =[(applyOnFile, ([adjustLongtableFilter,adjustBeamerFootnote],out) ,{})]
    	)

########### Commands ##########
# Run latex
def genLatexCmd(src, options):
        return cmdObj(
            " ".join([latexEngine] + options +[src]),
            True,
            before=[(print,("-----\t","Latex\t{out}\t".format(out=src),"-----"),{})],
            after =[]
	)

# Run bibtex
def genBibtexCmd(src, options):
    	return cmdObj(
            " ".join(["bibtex"] + options + [texFile]),
            True,
            before=[(print,("-----\t","BibTex\t{out}\t".format(out=src),"-----"),{})],
            after =[]
	)

######### Documents .... ##########
docs = {
	 "mydoc": [
	 	 genPandocCmd(
	 	 	**{
                	 	"out" : "mydoc.tex",
                	 	"src" :  [
                            		"doc/mydoc.md"
                            		],
                        	"format": docFormat,
                        	"options": docOptions
                    	}),
	 	 genLatexCmd(
	 	 	**{
                	 	"src" : "mydoc.tex",
                        	"options": ["-synctex=1"],
                        	#"options": ["--interaction=batchmode","-synctex=1"],
                    	}),
		],
	 "mypres": [
	 	 genPandocCmd(
	 	 	**{
                	 	"out" : "mypres.tex",
                	 	"src" :  [
                            		"pres/mypres.md"
                            		],
                        	"format": beamerFormat,
                        	"options": beamerOptions
                    	}),
	 	 genLatexCmd(
	 	 	**{
                	 	"src" : "mypres.tex",
                        	"options": ["-synctex=1"],
                        	#"options": ["--interaction=batchmode","-synctex=1"],
                    	}),
		],
	"example": [
		 genPandocCmd(
		 	**{
                	 	"out": "tikz/example.tex",
                	 	"src": [
                                        "doc/tikz/example.md"
                                	],
                        	"format": tikzFormat,
                            	"options": tikzOptions
                    	}),
		 genLatexCmd(
		 	**{
                	 	"src": "tikz/example.tex",
                        	"options": ["--interaction=batchmode","--output-directory=./tikz/","-synctex=1"],
                    	}),
		]
	}

docGroups={}
docGroups["all"] = it.chain(*(docs[k] for k in docs.keys()))

def printUsage():
	print("Usage:\n")
	print("\trun.py [DocKey] [-g GroupKey]\n")
	print("Documets:")
	for k in docs.keys():
            print("\t{k}".format(k=k))

	print("Groups:")
	for k in docGroups.keys():
	    print("\t{k}".format(k=k))

def printKeysNotFound(keys):
    print("Keys not found:")
    for k in keys:
        print("\t{k}".format(k=k))
    print("")
    print("".join(it.repeat("-",40)))
    print("")
    printUsage()

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        opts, args = getopt.getopt(argv[1:], "hg:", ["help","group="])
    except getopt.GetoptError as msg:
        printUsage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ['-h','--help']:
            printUsage()
            sys.exit()
        if opt in ['-g','--group']:
            if arg in docGroups.keys():
                processCommands(docGroups[arg])
            else:
                printKeysNotFound([arg])
            sys.exit()

    notfound = list(filter(lambda k: not(k in docs.keys()), args))
    if len(notfound)>0:
        printKeysNotFound(notfound)
        sys.exit()
    processCommands(it.chain(*(docs[k] for k in args)))

if __name__== "__main__":
    sys.exit(main())

# Run pandoc and latex
#processCommands([pandocCmd,latexCmd])
<commit_msg>Run script was not modified, still contained format_howto instead of format_simple<commit_after>#!/usr/bin/python

import os, sys, getopt
import itertools as it
sys.path.append(os.path.dirname(__file__) + "/src")
from pandocLatex import *

latexEngine="lualatex"
highlightstyle='"tango"' #pygments, kate, monochrome, espresso, zenburn, haddock, tango
template="template/document.latex"
beamer="template/beamer.latex"

docFormat = [
    "template/format_simple.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/titlepage.yaml",
    "template/typography_sans.yaml"
    ]

docOptions = [
        "-t latex",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--filter pandoc-csv2table",
        "--filter pandoc-crossref",
# 	"--filter diagrams-pandoc",
#       "--filter pandoc-placetable", # compiled with inlinemarkdown
        "--filter pandoc-citeproc",
        "--template={template}".format(template=template),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
        "--number-sections",
        "--chapter",
        "-M synctex:yes"
	]

beamerFormat = [
    "template/format_beamer.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/typography_lmodern.yaml"
    ]

beamerOptions = [
        "-t beamer",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--filter pandoc-csv2table",
        "--filter pandoc-crossref",
# 	"--filter diagrams-pandoc",
#       "--filter pandoc-placetable", # compiled with inlinemarkdown
        "--filter pandoc-citeproc",
        "--template={template}".format(template=beamer),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
        "--number-sections",
        "-M synctex:yes"
	]

tikzFormat = [
    "template/format_tikz.yaml",
    "template/color_unihd.yaml",
    "template/objects.yaml",
    "template/titlepage.yaml",
    "template/typography_sans.yaml"
    ]

tikzOptions= [
        "-t latex",
        "-s ",
#        "-o {out}".format(out=texFile),
#       "--columns 1",
        "--template={template}".format(template=template),
        "--highlight-style={hls}".format(hls=highlightstyle),
        "--latex-engine={le}".format(le=latexEngine),
	]

# Convert Markdown to Latex, using a latex template and YAML configuration
def genPandocCmd(out, src, format, options):
        return cmdObj(
            " ".join(["pandoc"] +
            		 format +
            		    src +
                ["-o {out}".format(out=out)] +
            		options),
            True,
            before=[(print,("-----\t","Pandoc\t{out}\t".format(out=out),"-----"),{})],
            # Adjust appearance of tables and figures
            #after =[(applyOnFile, ([adjustLongtableFilter,centerFigureFilter],texFile) ,{})]
            after =[(applyOnFile, ([adjustLongtableFilter,adjustBeamerFootnote],out) ,{})]
    	)

########### Commands ##########
# Run latex
def genLatexCmd(src, options):
        return cmdObj(
            " ".join([latexEngine] + options +[src]),
            True,
            before=[(print,("-----\t","Latex\t{out}\t".format(out=src),"-----"),{})],
            after =[]
	)

# Run bibtex
def genBibtexCmd(src, options):
    	return cmdObj(
            " ".join(["bibtex"] + options + [texFile]),
            True,
            before=[(print,("-----\t","BibTex\t{out}\t".format(out=src),"-----"),{})],
            after =[]
	)

######### Documents .... ##########
docs = {
	 "mydoc": [
	 	 genPandocCmd(
	 	 	**{
                	 	"out" : "mydoc.tex",
                	 	"src" :  [
                            		"doc/mydoc.md"
                            		],
                        	"format": docFormat,
                        	"options": docOptions
                    	}),
	 	 genLatexCmd(
	 	 	**{
                	 	"src" : "mydoc.tex",
                        	"options": ["-synctex=1"],
                        	#"options": ["--interaction=batchmode","-synctex=1"],
                    	}),
		],
	 "mypres": [
	 	 genPandocCmd(
	 	 	**{
                	 	"out" : "mypres.tex",
                	 	"src" :  [
                            		"pres/mypres.md"
                            		],
                        	"format": beamerFormat,
                        	"options": beamerOptions
                    	}),
	 	 genLatexCmd(
	 	 	**{
                	 	"src" : "mypres.tex",
                        	"options": ["-synctex=1"],
                        	#"options": ["--interaction=batchmode","-synctex=1"],
                    	}),
		],
	"example": [
		 genPandocCmd(
		 	**{
                	 	"out": "tikz/example.tex",
                	 	"src": [
                                        "doc/tikz/example.md"
                                	],
                        	"format": tikzFormat,
                            	"options": tikzOptions
                    	}),
		 genLatexCmd(
		 	**{
                	 	"src": "tikz/example.tex",
                        	"options": ["--interaction=batchmode","--output-directory=./tikz/","-synctex=1"],
                    	}),
		]
	}

docGroups={}
docGroups["all"] = it.chain(*(docs[k] for k in docs.keys()))

def printUsage():
	print("Usage:\n")
	print("\trun.py [DocKey] [-g GroupKey]\n")
	print("Documets:")
	for k in docs.keys():
            print("\t{k}".format(k=k))

	print("Groups:")
	for k in docGroups.keys():
	    print("\t{k}".format(k=k))

def printKeysNotFound(keys):
    print("Keys not found:")
    for k in keys:
        print("\t{k}".format(k=k))
    print("")
    print("".join(it.repeat("-",40)))
    print("")
    printUsage()

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        opts, args = getopt.getopt(argv[1:], "hg:", ["help","group="])
    except getopt.GetoptError as msg:
        printUsage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ['-h','--help']:
            printUsage()
            sys.exit()
        if opt in ['-g','--group']:
            if arg in docGroups.keys():
                processCommands(docGroups[arg])
            else:
                printKeysNotFound([arg])
            sys.exit()

    notfound = list(filter(lambda k: not(k in docs.keys()), args))
    if len(notfound)>0:
        printKeysNotFound(notfound)
        sys.exit()
    processCommands(it.chain(*(docs[k] for k in args)))

if __name__== "__main__":
    sys.exit(main())

# Run pandoc and latex
#processCommands([pandocCmd,latexCmd])
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.

from traceback import extract_tb
from twisted.internet import reactor

import webwallet

# TODO: Clean this up
from qrlcore import chain, block, apiprotocol, merkle, transaction, ntp, wallet, walletprotocol, state, helper, node, \
    fork, logger
from qrlcore.chain import Chain

from qrlcore.node import NodeState

# Initializing function to log console output
from qrlcore.state import State

def log_traceback(exctype, value, tb):  # Function to log error's traceback
    logger.info('*** Error ***')
    logger.info(str(exctype))
    logger.info(str(value))
    tb_info = extract_tb(tb)
    for line in tb_info:
        logger.info(tb_info)

# sys.excepthook = log_traceback

if __name__ == "__main__":
    logger.initialize_default(force_console_output=True)

    # TODO: Decide when to log to a file
    # TODO: Add command line arguments to apply configuration changes
    # logger.log_to_file()

    nodeState = NodeState()     # FIXME: purpose?
    ntp.setDrift()

    stateObj = State()
    logger.info('Initializing chain..')
    chainObj = Chain(state=stateObj)

    logger.info('Reading chain..')
    chainObj.m_load_chain()
    logger.info(str(len(chainObj.m_blockchain)) + ' blocks')
    logger.info('Verifying chain')
    logger.info('Building state leveldb')

    logger.info('Loading node list..')  # load the peers for connection based upon previous history..
    chainObj.state.state_load_peers()
    logger.info(chainObj.state.state_get_peers())

    stuff = 'QRL node connection established. Try starting with "help"' + '\r\n'
    logger.info('>>>Listening..')

    p2pFactory = node.P2PFactory(chain=chainObj, nodeState=nodeState)
    pos = node.POS(chain=chainObj, p2pFactory=p2pFactory, nodeState=nodeState, ntp=ntp)
    p2pFactory.setPOS(pos)

    apiFactory = apiprotocol.ApiFactory(pos, chainObj, stateObj, p2pFactory.peers)

    stuff = 'QRL node connection established. Try starting with "help"' + '\r\n'
    walletFactory = walletprotocol.WalletFactory(stuff, chainObj, stateObj, p2pFactory)

    logger.info('Reading chain..')
    reactor.listenTCP(2000, walletFactory, interface='127.0.0.1')
    reactor.listenTCP(9000, p2pFactory)
    reactor.listenTCP(8080, apiFactory)

    # Load web wallet HERE??
    webWallet = webwallet.WebWallet(chainObj, stateObj, p2pFactory)

    pos.restart_monitor_bk(80)

    logger.info('Connect to the node via telnet session on port 2000: i.e "telnet localhost 2000"')
    logger.info('<<<Connecting to nodes in peer.dat')

    p2pFactory.connect_peers()
    reactor.callLater(20, pos.unsynced_logic)

    reactor.run()
<commit_msg>Logging<commit_after>#!/usr/bin/env python

# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import argparse
from traceback import extract_tb
from twisted.internet import reactor

import webwallet

# TODO: Clean this up
from qrlcore import chain, block, apiprotocol, merkle, transaction, ntp, wallet, walletprotocol, state, helper, node, \
    fork, logger
from qrlcore.chain import Chain

from qrlcore.node import NodeState

# Initializing function to log console output
from qrlcore.state import State

def log_traceback(exctype, value, tb):  # Function to log error's traceback
    logger.info('*** Error ***')
    logger.info(str(exctype))
    logger.info(str(value))
    tb_info = extract_tb(tb)
    for line in tb_info:
        logger.info(tb_info)

# sys.excepthook = log_traceback

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='QRL node')
    parser.add_argument('--quiet', '-q', dest='quiet', action='store_true', required=False, default=False)

    args = parser.parse_args()

    logger.initialize_default(force_console_output=not args.quiet)
    logger.log_to_file()

    nodeState = NodeState()     # FIXME: purpose?
    ntp.setDrift()

    stateObj = State()
    logger.info('Initializing chain..')
    chainObj = Chain(state=stateObj)

    logger.info('Reading chain..')
    chainObj.m_load_chain()
    logger.info(str(len(chainObj.m_blockchain)) + ' blocks')
    logger.info('Verifying chain')
    logger.info('Building state leveldb')

    logger.info('Loading node list..')  # load the peers for connection based upon previous history..
    chainObj.state.state_load_peers()
    logger.info(chainObj.state.state_get_peers())

    stuff = 'QRL node connection established. Try starting with "help"' + '\r\n'
    logger.info('>>>Listening..')

    p2pFactory = node.P2PFactory(chain=chainObj, nodeState=nodeState)
    pos = node.POS(chain=chainObj, p2pFactory=p2pFactory, nodeState=nodeState, ntp=ntp)
    p2pFactory.setPOS(pos)

    apiFactory = apiprotocol.ApiFactory(pos, chainObj, stateObj, p2pFactory.peers)

    stuff = 'QRL node connection established. Try starting with "help"' + '\r\n'
    walletFactory = walletprotocol.WalletFactory(stuff, chainObj, stateObj, p2pFactory)

    logger.info('Reading chain..')
    reactor.listenTCP(2000, walletFactory, interface='127.0.0.1')
    reactor.listenTCP(9000, p2pFactory)
    reactor.listenTCP(8080, apiFactory)

    # Load web wallet HERE??
    webWallet = webwallet.WebWallet(chainObj, stateObj, p2pFactory)

    pos.restart_monitor_bk(80)

    logger.info('Connect to the node via telnet session on port 2000: i.e "telnet localhost 2000"')
    logger.info('<<<Connecting to nodes in peer.dat')

    p2pFactory.connect_peers()
    reactor.callLater(20, pos.unsynced_logic)

    reactor.run()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import os, sys, cgi
from StringIO import StringIO
from subprocess import call
from tempfile import *
from shutil import *
from zipfile import *

import xym
import pyang
from bottle import route, run, template, request, static_file, error

# requests.packages.urllib3.disable_warnings()

__author__ = 'camoberg@tail-f.com'
__copyright__ = "Copyright (c) 2015, Carl Moberg, camoberg@cisco.com"
__license__ = "New-style BSD"
__email__ = "camoberg@cisco.com"
__version__ = "0.2"

pyangcmd = '/usr/local/bin/pyang'
yang_import_dir = '/opt/local/share/yang'

versions = { "pyang_version": pyang.__version__, "xym_version": xym.__version__ }

def create_output(url):
	workdir = mkdtemp()
	results = {}

	result = StringIO()

	# Trickery to capture stderr from the xym tools for later use
	stderr_ = sys.stderr
	sys.stderr = result
	extracted_models = xym.xym(source_id = url, dstdir = workdir, srcdir = "", strict = True, debug_level = 0)
	sys.stderr = stderr_
	xym_stderr = result.getvalue()

	for em in extracted_models:
		pyang_stderr, pyang_output = validate_yangfile(em, workdir)
		results[em] = { "pyang_stderr": cgi.escape(pyang_stderr),
						"pyang_output": cgi.escape(pyang_output),
						"xym_stderr": cgi.escape(xym_stderr) }

	rmtree(workdir)

	return results

def validate_yangfile(infilename, workdir):
	pyang_stderr = pyang_output = ""
	infile = os.path.join(workdir, infilename)
	pyang_outfile = str(os.path.join(workdir, infilename) + '.out')
	pyang_resfile = str(os.path.join(workdir, infilename) + '.res')

	resfp = open(pyang_resfile, 'w+')
	status = call([pyangcmd, '-p', yang_import_dir, '-p', workdir, '--ietf', '-f', 'tree', infile, '-o', pyang_outfile], stderr = resfp)

	if os.path.isfile(pyang_outfile):
		outfp = open(pyang_outfile, 'r')
		pyang_output = str(outfp.read())
	else:
		pass

	resfp.seek(0)

	for line in resfp.readlines():
		pyang_stderr += os.path.basename(line)

	return pyang_stderr, pyang_output

@route('/')
@route('/validator')
def validator():
	return template('main', results = {}, versions = versions)

@route('/draft-validator', method="POST")
def upload_draft():
	results = {}
	savedfiles = []
	savedir = mkdtemp()

	uploaded_file = request.files.get("data")
	filepath = os.path.join(savedir, uploaded_file.raw_filename)
	uploaded_file.save(filepath)
	results = create_output(filepath)

	rmtree(savedir)

	print "RESULTS", results

	return template('main', results = results, versions = versions)

@route('/validator', method="POST")
def upload_file():
	results = {}
	savedfiles = []
	savedir = mkdtemp()

	uploaded_files = request.files.getlist("data")

	for file in uploaded_files:
		name, ext = os.path.splitext(file.filename)

		if ext == ".yang":
			file.save(os.path.join(savedir, file.raw_filename))
			savedfiles.append(file.raw_filename)

		if ext == ".zip":
			zipfilename = os.path.join(savedir, file.filename)
			file.save(zipfilename)
			zf = ZipFile(zipfilename, "r")
			zf.extractall(savedir)
			for filename in zf.namelist():
				savedfiles.append(filename)

	for file in savedfiles:
		pyang_stderr, pyang_output = validate_yangfile(file, savedir)
		results[file] = { "pyang_stderr": pyang_stderr, "pyang_output": pyang_output }

 	rmtree(savedir)

	print "RESULTS", results

	return template('main', results = results, versions = versions)

@route('/api/rfc/<rfc>')
def json_validate_rfc(rfc):
	response = []
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	return results

@route('/api/draft/<draft>')
def json_validate_draft(draft):
	response = []
	url = 'http://tools.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	return results

@route('/rfc', method='GET')
def validate_rfc_param():
	rfc = request.query['number']
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	return template('result', results = results)

@route('/draft', method='GET')
def validate_rfc_param():
	draft = request.query['name']
	url = 'http://tools.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	return template('result', results = results)

@route('/rfc/<rfc>')
def validate_rfc(rfc):
	response = []
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	print "RESULTS", results
	return template('result', results = results)

@route('/draft/<draft>')
def validate_draft(draft):
	response = []
	url = 'http://www.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	print "RESULTS", results
	return template('result', results = results)

@route('/static/:path#.+#', name='static')
def static(path):
	return static_file(path, root='static')

@route('/rest')
def rest():
	return(template('rest'))

@route('/about')
def rest():
	return(template('about'))

@error(404)
def error404(error):
	return 'Nothing here, sorry.'

if __name__ == '__main__':
	run(host='0.0.0.0', port=8080)
<commit_msg>Switch to cherrypy<commit_after>#!/usr/bin/env python

import os, sys, cgi
from StringIO import StringIO
from subprocess import call
from tempfile import *
from shutil import *
from zipfile import *

import xym
import pyang
from bottle import route, run, template, request, static_file, error

# requests.packages.urllib3.disable_warnings()

__author__ = 'camoberg@tail-f.com'
__copyright__ = "Copyright (c) 2015, Carl Moberg, camoberg@cisco.com"
__license__ = "New-style BSD"
__email__ = "camoberg@cisco.com"
__version__ = "0.2"

pyangcmd = '/usr/local/bin/pyang'
yang_import_dir = '/opt/local/share/yang'

versions = { "pyang_version": pyang.__version__, "xym_version": xym.__version__ }

def create_output(url):
	workdir = mkdtemp()
	results = {}

	result = StringIO()

	# Trickery to capture stderr from the xym tools for later use
	stderr_ = sys.stderr
	sys.stderr = result
	extracted_models = xym.xym(source_id = url, dstdir = workdir, srcdir = "", strict = True, debug_level = 0)
	sys.stderr = stderr_
	xym_stderr = result.getvalue()

	for em in extracted_models:
		pyang_stderr, pyang_output = validate_yangfile(em, workdir)
		results[em] = { "pyang_stderr": cgi.escape(pyang_stderr),
						"pyang_output": cgi.escape(pyang_output),
						"xym_stderr": cgi.escape(xym_stderr) }

	rmtree(workdir)

	return results

def validate_yangfile(infilename, workdir):
	pyang_stderr = pyang_output = ""
	infile = os.path.join(workdir, infilename)
	pyang_outfile = str(os.path.join(workdir, infilename) + '.out')
	pyang_resfile = str(os.path.join(workdir, infilename) + '.res')

	resfp = open(pyang_resfile, 'w+')
	status = call([pyangcmd, '-p', yang_import_dir, '-p', workdir, '--ietf', '-f', 'tree', infile, '-o', pyang_outfile], stderr = resfp)

	if os.path.isfile(pyang_outfile):
		outfp = open(pyang_outfile, 'r')
		pyang_output = str(outfp.read())
	else:
		pass

	resfp.seek(0)

	for line in resfp.readlines():
		pyang_stderr += os.path.basename(line)

	return pyang_stderr, pyang_output

@route('/')
@route('/validator')
def validator():
	return template('main', results = {}, versions = versions)

@route('/draft-validator', method="POST")
def upload_draft():
	results = {}
	savedfiles = []
	savedir = mkdtemp()

	uploaded_file = request.files.get("data")
	filepath = os.path.join(savedir, uploaded_file.raw_filename)
	uploaded_file.save(filepath)
	results = create_output(filepath)

	rmtree(savedir)

	print "RESULTS", results

	return template('main', results = results, versions = versions)

@route('/validator', method="POST")
def upload_file():
	results = {}
	savedfiles = []
	savedir = mkdtemp()

	uploaded_files = request.files.getlist("data")

	for file in uploaded_files:
		name, ext = os.path.splitext(file.filename)

		if ext == ".yang":
			file.save(os.path.join(savedir, file.raw_filename))
			savedfiles.append(file.raw_filename)

		if ext == ".zip":
			zipfilename = os.path.join(savedir, file.filename)
			file.save(zipfilename)
			zf = ZipFile(zipfilename, "r")
			zf.extractall(savedir)
			for filename in zf.namelist():
				savedfiles.append(filename)

	for file in savedfiles:
		pyang_stderr, pyang_output = validate_yangfile(file, savedir)
		results[file] = { "pyang_stderr": pyang_stderr, "pyang_output": pyang_output }

 	rmtree(savedir)

	print "RESULTS", results

	return template('main', results = results, versions = versions)

@route('/api/rfc/<rfc>')
def json_validate_rfc(rfc):
	response = []
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	return results

@route('/api/draft/<draft>')
def json_validate_draft(draft):
	response = []
	url = 'http://tools.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	return results

@route('/rfc', method='GET')
def validate_rfc_param():
	rfc = request.query['number']
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	return template('result', results = results)

@route('/draft', method='GET')
def validate_rfc_param():
	draft = request.query['name']
	url = 'http://tools.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	return template('result', results = results)

@route('/rfc/<rfc>')
def validate_rfc(rfc):
	response = []
	url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
	results = create_output(url)
	print "RESULTS", results
	return template('result', results = results)

@route('/draft/<draft>')
def validate_draft(draft):
	response = []
	url = 'http://www.ietf.org/id/{!s}'.format(draft)
	results = create_output(url)
	print "RESULTS", results
	return template('result', results = results)

@route('/static/:path#.+#', name='static')
def static(path):
	return static_file(path, root='static')

@route('/rest')
def rest():
	return(template('rest'))

@route('/about')
def rest():
	return(template('about'))

@error(404)
def error404(error):
	return 'Nothing here, sorry.'

if __name__ == '__main__':
	run(server="cherrypy", host='0.0.0.0', port=80)
<|endoftext|>


<commit_before>import argparse
import os

from app import app

if os.geteuid() != 0:
    raise OSError("Must be run as root")

parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False)
parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=int)
params = parser.parse_args()

app.run(debug=params.debug, port=params.port, host='0.0.0.0')<commit_msg>Remove non-root warning<commit_after>import argparse
import os

from app import app

parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False)
parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=int)
params = parser.parse_args()

app.run(debug=params.debug, port=params.port, host='0.0.0.0')<|endoftext|>