<commit_before>#!/usr/bin/env python
"""
Creates a SVG tile image from a Mapbox Vector Tile.
"""
from __future__ import print_function
import os
import math
import argparse
import mapbox_vector_tile
from enum import Enum
from lxml import etree
from tempfile import NamedTemporaryFile
from django.contrib.gis.geos import LineString, Polygon
from svgutils.transform import SVG, SVGFigure, FigureElement, LineElement
# `mapbox-vector-tile` has a hardcoded tile extent of 4096 units.
MVT_EXTENT = 4096
TILE_SIZE = 256
fig = SVGFigure(width=TILE_SIZE, height=TILE_SIZE)

class CustomLineElement(LineElement):
    """
    Inherits from LineElement, gives access to style attribute.
    """
    def __init__(self, points, width=1, color='black', style=''):
        linedata = "M{} {} ".format(*points[0])
        linedata += " ".join(map(lambda x: "L{} {}".format(*x), points[1:]))
        line = etree.Element(SVG+"path",
                             {"d": linedata,
                              "stroke-width": str(width),
                              "stroke": color,
                              "style": style})
        FigureElement.__init__(self, line)

class GeometryType(Enum):
    """
    See:
    https://github.com/mapbox/vector-tile-spec/tree/master/2.1
    4.3.4. Geometry Types
    """
    UNKNOWN = 0
    POINT = 1
    LINESTRING = 2
    POLYGON = 3

def draw_polyline(points, prop_type):
    """
    https://github.com/btel/svg_utils
    """
    # the Linestring seems to be a multi-linestring
    stroke = 'black'
    if prop_type == 'ferry':
        stroke = 'blue'
    style = "fill:none;stroke:%s" % (stroke)
    polyline = CustomLineElement(points, style=style)
    fig.append(polyline)

def deg2num(lat_deg, lon_deg, zoom):
    """
    lat, lon, zoom to tile numbers
    https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
    http://gis.stackexchange.com/a/133535
    """
    lat_rad = math.radians(lat_deg)
    n = 2.0 ** zoom
    xtile = int((lon_deg + 180.0) / 360.0 * n)
    ytile = int(
            (1.0 -
                math.log(
                    math.tan(lat_rad) + (1 / math.cos(lat_rad))) /
                math.pi) /
            2.0 * n)
    return (xtile, ytile)

def shrink(xy_pairs):
    """
    Linear shrinking before drawing
    """
    ratio = (MVT_EXTENT / TILE_SIZE)
    for xy_pair in xy_pairs:
        xy_pair[0] /= ratio
        xy_pair[1] /= ratio

def in_extent(pairs):
    """
    Returns False if none of the points are in the extent.
    """
    for x, y in pairs:
        if x >= 0 and x <= MVT_EXTENT:
            return True
        if y >= 0 and y <= MVT_EXTENT:
            return True
    return False

def clipping(pairs):
    """
    Returns the pairs clipped, so it fits in the extent.
    """
    for point in pairs:
        # makes sure it's above or equal to 0
        point[0] = max(point[0], 0)
        point[1] = max(point[1], 0)
        # makes sure it's below or equal to MVT_EXTENT
        point[0] = min(point[0], MVT_EXTENT)
        point[1] = min(point[1], MVT_EXTENT)

def convert2pixel(linestring):
    """
    Converts x, y to pixels coordinates.
    """
    def xy_pairs():
        for x_merc, y_merc in linestring:
            x = x_merc
            y = MVT_EXTENT - y_merc
            yield [x, y]
    return [p for p in xy_pairs()]

def process_linestring(linestring, prop_type):
    xy_pairs = convert2pixel(linestring)
    if not in_extent(linestring):
        # print("Not in extent")
        return
    clipping(xy_pairs)
    shrink(xy_pairs)
    # draw_line(xy_pairs[0], xy_pairs[1], prop_type)
    draw_polyline(xy_pairs, prop_type)

def process_polygon(polygon, prop_type):
    linestring = polygon[0]
    process_linestring(linestring, prop_type)

def is_multilinestring(geometry):
    return type(geometry[0][0]) == list

def is_multipolygon(geometry):
    return is_multilinestring(geometry)

def process_feature(layer_type, feature):
    geometry = feature['geometry']
    properties = feature['properties']
    prop_type = layer_type
    try:
        prop_type = properties['type']
    except KeyError:
        pass
    geometry_type_id = feature['type']
    geometry_type = GeometryType(geometry_type_id)
    if geometry_type == GeometryType.LINESTRING:
        if is_multilinestring(geometry):
            # MultiLineString processing
            for subgeometry in geometry:
                linestring = LineString(subgeometry)
                process_linestring(linestring, prop_type)
        else:
            linestring = LineString(geometry)
            process_linestring(linestring, prop_type)
    elif geometry_type == GeometryType.POLYGON:
            for subgeometry in geometry:
                if is_multipolygon(subgeometry):
                    for subsubgeometry in subgeometry:
                        polygon = Polygon(subsubgeometry)
                        process_polygon(polygon, prop_type)
                else:
                    polygon = Polygon(subgeometry)
                    process_polygon(polygon, prop_type)
    else:
        # print("Not supported geometry type:", geometry_type)
        pass

def process_features(layer_key, features):
    for feature in features:
        # looks like it's in Spherical/Web Mercator (EPSG:3857)
        process_feature(layer_key, feature)

def decode_pbf(pbf_data):
    """
    Decodes the PBF tile as a layers dictionary.
    For instance decodes 12-1143-1497.vector.pbf, downloaded from:
    https://github.com/mapbox/vector-tile-js/tree/master/test/fixtures/
    Can also download some from:
    http://download.geofabrik.de/
    """
    layers_dict = mapbox_vector_tile.decode(pbf_data)
    return layers_dict

def process_layer(layer_key, layer_value):
    features = layer_value['features']
    process_features(layer_key, features)

def process_layers(layers_dict):
    for layer_key, layer_value in layers_dict.iteritems():
        process_layer(layer_key, layer_value)

def argument_parser():
    """
    Argument parser helper.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mvt_file", help="Mapbox Vector Tile file to load",
        type=argparse.FileType('r'))
    args = parser.parse_args()
    return args

def run(mvt_content):
    """
    Process the MVT content and return the generated SVG content.
    """
    layers_dict = decode_pbf(mvt_content)
    process_layers(layers_dict)
    svg_image_file = NamedTemporaryFile(delete=False, suffix=".svg")
    svg_image_file.close()
    fig.save(svg_image_file.name)
    svg_image_file = open(svg_image_file.name)
    svg_content = svg_image_file.read()
    svg_image_file.close()
    os.unlink(svg_image_file.name)
    return svg_content

def main():
    """
    Parses args and prints SVG content.
    Usage example:
    mvt2svg.py 6160.mvt > 6160.svg
    """
    args = argument_parser()
    mvt_content = args.mvt_file.read()
    args.mvt_file.close()
    svg_content = run(mvt_content)
    print(svg_content, end='')

if __name__ == "__main__":
    main()
<commit_msg>mvt2svg.py Python3 fix<commit_after>#!/usr/bin/env python
"""
Creates a SVG tile image from a Mapbox Vector Tile.
"""
from __future__ import print_function
import os
import math
import argparse
import mapbox_vector_tile
from enum import Enum
from lxml import etree
from tempfile import NamedTemporaryFile
from django.contrib.gis.geos import LineString, Polygon
from svgutils.transform import SVG, SVGFigure, FigureElement, LineElement
# `mapbox-vector-tile` has a hardcoded tile extent of 4096 units.
MVT_EXTENT = 4096
TILE_SIZE = 256
fig = SVGFigure(width=TILE_SIZE, height=TILE_SIZE)

class CustomLineElement(LineElement):
    """
    Inherits from LineElement, gives access to style attribute.
    """
    def __init__(self, points, width=1, color='black', style=''):
        linedata = "M{} {} ".format(*points[0])
        linedata += " ".join(map(lambda x: "L{} {}".format(*x), points[1:]))
        line = etree.Element(SVG+"path",
                             {"d": linedata,
                              "stroke-width": str(width),
                              "stroke": color,
                              "style": style})
        FigureElement.__init__(self, line)

class GeometryType(Enum):
    """
    See:
    https://github.com/mapbox/vector-tile-spec/tree/master/2.1
    4.3.4. Geometry Types
    """
    UNKNOWN = 0
    POINT = 1
    LINESTRING = 2
    POLYGON = 3

def draw_polyline(points, prop_type):
    """
    https://github.com/btel/svg_utils
    """
    # the Linestring seems to be a multi-linestring
    stroke = 'black'
    if prop_type == 'ferry':
        stroke = 'blue'
    style = "fill:none;stroke:%s" % (stroke)
    polyline = CustomLineElement(points, style=style)
    fig.append(polyline)

def deg2num(lat_deg, lon_deg, zoom):
    """
    lat, lon, zoom to tile numbers
    https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
    http://gis.stackexchange.com/a/133535
    """
    lat_rad = math.radians(lat_deg)
    n = 2.0 ** zoom
    xtile = int((lon_deg + 180.0) / 360.0 * n)
    ytile = int(
            (1.0 -
                math.log(
                    math.tan(lat_rad) + (1 / math.cos(lat_rad))) /
                math.pi) /
            2.0 * n)
    return (xtile, ytile)

def shrink(xy_pairs):
    """
    Linear shrinking before drawing
    """
    ratio = (MVT_EXTENT / TILE_SIZE)
    for xy_pair in xy_pairs:
        xy_pair[0] /= ratio
        xy_pair[1] /= ratio

def in_extent(pairs):
    """
    Returns False if none of the points are in the extent.
    """
    for x, y in pairs:
        if x >= 0 and x <= MVT_EXTENT:
            return True
        if y >= 0 and y <= MVT_EXTENT:
            return True
    return False

def clipping(pairs):
    """
    Returns the pairs clipped, so it fits in the extent.
    """
    for point in pairs:
        # makes sure it's above or equal to 0
        point[0] = max(point[0], 0)
        point[1] = max(point[1], 0)
        # makes sure it's below or equal to MVT_EXTENT
        point[0] = min(point[0], MVT_EXTENT)
        point[1] = min(point[1], MVT_EXTENT)

def convert2pixel(linestring):
    """
    Converts x, y to pixels coordinates.
    """
    def xy_pairs():
        for x_merc, y_merc in linestring:
            x = x_merc
            y = MVT_EXTENT - y_merc
            yield [x, y]
    return [p for p in xy_pairs()]

def process_linestring(linestring, prop_type):
    xy_pairs = convert2pixel(linestring)
    if not in_extent(linestring):
        # print("Not in extent")
        return
    clipping(xy_pairs)
    shrink(xy_pairs)
    # draw_line(xy_pairs[0], xy_pairs[1], prop_type)
    draw_polyline(xy_pairs, prop_type)

def process_polygon(polygon, prop_type):
    linestring = polygon[0]
    process_linestring(linestring, prop_type)

def is_multilinestring(geometry):
    return type(geometry[0][0]) == list

def is_multipolygon(geometry):
    return is_multilinestring(geometry)

def process_feature(layer_type, feature):
    geometry = feature['geometry']
    properties = feature['properties']
    prop_type = layer_type
    try:
        prop_type = properties['type']
    except KeyError:
        pass
    geometry_type_id = feature['type']
    geometry_type = GeometryType(geometry_type_id)
    if geometry_type == GeometryType.LINESTRING:
        if is_multilinestring(geometry):
            # MultiLineString processing
            for subgeometry in geometry:
                linestring = LineString(subgeometry)
                process_linestring(linestring, prop_type)
        else:
            linestring = LineString(geometry)
            process_linestring(linestring, prop_type)
    elif geometry_type == GeometryType.POLYGON:
            for subgeometry in geometry:
                if is_multipolygon(subgeometry):
                    for subsubgeometry in subgeometry:
                        polygon = Polygon(subsubgeometry)
                        process_polygon(polygon, prop_type)
                else:
                    polygon = Polygon(subgeometry)
                    process_polygon(polygon, prop_type)
    else:
        # print("Not supported geometry type:", geometry_type)
        pass

def process_features(layer_key, features):
    for feature in features:
        # looks like it's in Spherical/Web Mercator (EPSG:3857)
        process_feature(layer_key, feature)

def decode_pbf(pbf_data):
    """
    Decodes the PBF tile as a layers dictionary.
    For instance decodes 12-1143-1497.vector.pbf, downloaded from:
    https://github.com/mapbox/vector-tile-js/tree/master/test/fixtures/
    Can also download some from:
    http://download.geofabrik.de/
    """
    layers_dict = mapbox_vector_tile.decode(pbf_data)
    return layers_dict

def process_layer(layer_key, layer_value):
    features = layer_value['features']
    process_features(layer_key, features)

def process_layers(layers_dict):
    for layer_key, layer_value in layers_dict.items():
        process_layer(layer_key, layer_value)

def argument_parser():
    """
    Argument parser helper.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mvt_file", help="Mapbox Vector Tile file to load",
        type=argparse.FileType('r'))
    args = parser.parse_args()
    return args

def run(mvt_content):
    """
    Process the MVT content and return the generated SVG content.
    """
    layers_dict = decode_pbf(mvt_content)
    process_layers(layers_dict)
    svg_image_file = NamedTemporaryFile(delete=False, suffix=".svg")
    svg_image_file.close()
    fig.save(svg_image_file.name)
    svg_image_file = open(svg_image_file.name)
    svg_content = svg_image_file.read()
    svg_image_file.close()
    os.unlink(svg_image_file.name)
    return svg_content

def main():
    """
    Parses args and prints SVG content.
    Usage example:
    mvt2svg.py 6160.mvt > 6160.svg
    """
    args = argument_parser()
    mvt_content = args.mvt_file.read()
    args.mvt_file.close()
    svg_content = run(mvt_content)
    print(svg_content, end='')

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri May  2 01:17:09 2014

@author: jrcapriles
"""

import pygame, Buttons
from pygame.locals import *
import ode
from math import atan2, acos
from numpy import *
from Point import *
import matplotlib.pyplot as plt

class armSimulator( object ):
    def __init__( self, width, lenght, links):
        self.width, self.lenght, self.links = width, lenght, links
        self.L = ones((1,self.links))
        # Initialize pygame
        pygame.init()
        # Open a display
        self.srf = pygame.display.set_mode((self.width,self.lenght))
        pygame.display.set_caption(str(links) + "-link pendulum")
        self.fps = 50
        self.dt = 1.0/self.fps
        self.loopFlag = True
        #Parameters
        self.g= -9.81
        self.maxF = 20*ones((1,links))
        self.thetad = zeros((1,links))
        self.goal_button = Buttons.Button(self.srf, color = (200,0,0), x = 10, y = 10, length =  50, height = 25, width = 0, text = "Goal", text_color = (255,255,255), font_size = 20, fade_on = False)

    def createIC(self):
        rest = []
        left = []
        right = []
        up =[]
        #First loop to create all different combinations of IC
        for i in range(0,self.links+1):
            rest.append(Point(0,-i,0))
            left.append(Point(i,0,0))
            right.append(Point(-i,0,0))
            up.append(Point(0,i,0))

        #Create the dicionary
        self.ICList = {"Rest":rest,
                       "Left":left,
                       "Right":right,
                       "Up":up}

    def setTarget(self,target):
        self.thetad = target

    def getTarget(self, i):
        return self.thetad[i]

    def getTargetRange(self, i,j):
        return self.thetad[i:j]

    def setIC(self, case):
        self.IC = self.ICList[case]

    def getIC(self,i):
        return self.IC[i].getPoint()

    def setMaxF(self, F):
        if F is None:
            self.maxF = [10 for i in range(self.links)]
        else:
            self.maxF = F

    def getMaxF(self,i):
        return self.maxF[i]

    def getWidth(self):
        return self.width

    def getLenght(self):
            return self.leght

    def world2screen(self,x,y):
        return int(self.width/2 + 128*x), int(self.lenght/2 - 128*y)

    def screen2world(self,x,y):
        return float((x - self.width/2)/128), float((-y + self.lenght/2)/128)

    def surf(self, x,y):
        return (pow(x-pi/2,2) + pow(0.9*pi*y,2) - pow(pi/2,2))

    def phi(self, y):
        return -y -(2*self.a/sqrt(pow(self.a,2)-1))*arctan(sqrt((self.a-1)/(self.a+1))*tan(y/2))

    def runSimulation(self, case, targets):

        self.createIC()
        self.createArm(case)
        self.setTarget(targets)

        # Simulation loop.
        self.clk = pygame.time.Clock()

        while self.loopFlag:
            events = pygame.event.get()
            for e in events:
                if e.type==QUIT:
                    self.loopFlag=False
                if e.type==KEYDOWN:
                    if e.type==KEYDOWN:
                        if e.key == K_g:
                            print "New Goals: please click the new goal over the red circle"
                            self.setNewGoal()
                    else:
                        self.loopFlag=False
                elif e.type == MOUSEBUTTONDOWN:
                    if self.goal_button.pressed(pygame.mouse.get_pos()):
                        print "New Goals: please click the new goal over the red circle"
                        self.setNewGoal()

            # Clear the screen
            self.srf.fill((255,255,255))

            x = []
            xd = []
            y = []
            yd = []
            z = []
            vx = []
            vy = []
            vz = []
            theta = []
            #thetad = []
            errTheta = []
            thetaDot = []
            errThetaDot = []
            T = []

            #self.setTarget(-0.8*pi*ones((1,self.links)))

            for i in range(0,self.links):
                x1,y1,z1 = self.body[i].getPosition()
                x.append(x1)
                y.append(y1)
                z.append(z1)
                vx1,vy1,vz1 = self.body[i].getAngularVel()
                vx.append(vx1)
                vy.append(vy1)
                vz.append(vz1)
                theta.append(self.j[i].getAngle())
                #thetad.append(-0.5*pi)
                errTheta.append(theta[i]- self.getTarget(i))

                thetaDot.append(sum(vz))
                #thetaDotd.append(0.0)
                errThetaDot.append(self.getTarget(i)+thetaDot[i])

                if i == 0: #Kinematics
                    xd.append(-self.L[0,0]*sin(-self.getTarget(0)))
                    yd.append(-self.L[0,0]*cos(-self.getTarget(0)))
                else:
                    xd.append(xd[i-1]+self.L[0,i]*sin(-sum(self.getTargetRange(0,i))+self.getTarget(i)))
                    yd.append(yd[i-1]-self.L[0,i]*cos(-sum(self.getTargetRange(0,i))+self.getTarget(i)))

                T.append(-errTheta[i])

                #Set servo values
                self.j[i].setParam(ode.ParamVel, T[i])
                self.j[i].setParam(ode.ParamFMax, self.getMaxF(i))

           #Drawings
            for i in range(0,self.links):
                pygame.draw.circle(self.srf, (55,0,200), self.world2screen(x[i],y[i]), 10, 0)     #(Motors)
                pygame.draw.circle(self.srf, (55,0,100), self.world2screen(xd[i],yd[i]), 10, 0)   #(Targets)

                if i==0:
                    pygame.draw.line(self.srf, (55,0,200), self.world2screen(self.IC[0].getPointX(),self.IC[0].getPointY()), self.world2screen(x[i],y[i]), 2)
                    pygame.draw.circle(self.srf, (255,0,0), self.world2screen(self.IC[i].getPointX(),self.IC[i].getPointY()), 5, 0) #(origin)
                else:
                    pygame.draw.line(self.srf, (55,0,200), self.world2screen(x[i-1],y[i-1]), self.world2screen(x[i],y[i]), 2)

            self.drawBackLines()

            self.goal_button.update() #create_button(self.srf, (200,0,0), 10, 10, 50, 25, 0, "Goal", (255,255,255))

            pygame.display.flip()

            # Next simulation step
            self.world.step(self.dt)

            # Try to keep the specified framerate
            self.clk.tick(self.fps)

    def drawBackLines(self):
        #Draw the back lines of the screen
        pygame.draw.line(self.srf, (0,0,0), self.world2screen(0,-self.lenght/2), self.world2screen(0,self.lenght/2), 1)
        pygame.draw.line(self.srf, (0,0,0), self.world2screen(-self.width/2,0), self.world2screen(self.width/2,0), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(1,-self.lenght/2),self.world2screen(1,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(2,-self.lenght/2),self.world2screen(2,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-1,-self.lenght/2),self.world2screen(-1,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-2,-self.lenght/2),self.world2screen(-2,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,1),self.world2screen(self.width/2,1), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,2),self.world2screen(self.width/2,2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-1),self.world2screen(self.width/2,-1), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-2),self.world2screen(self.width/2,-2), 1)

    def createArm(self,case):
        #This routine create the arm and set the initial condition accordingly.
        self.setIC(case)
        # Create a world object
        self.world = ode.World()
        self.world.setGravity((0,self.g,0))

        # Create the bodies
        self.body = []
        self.M = []
        self.j = []
        for i in range(0,self.links):
            self.body.append(ode.Body(self.world))
            self.M.append(ode.Mass())
            self.M[i].setSphere(2500, 0.025)
            self.body[i].setMass(self.M[i])
            self.body[i].setPosition(self.getIC(i+1))

            self.j.append(ode.HingeJoint(self.world))
            if i==0:
                self.j[i].attach(self.body[0], ode.environment)
                self.j[i].setAnchor(self.getIC(0))
            else:
                self.j[i].attach(self.body[i-1], self.body[i])
                self.j[i].setAnchor(self.body[i-1].getPosition())

            self.j[i].setAxis( (0,0,1) )
            self.j[i].setParam(ode.ParamLoStop, -5.0)
            self.j[i].setParam(ode.ParamHiStop,5.0)
            self.j[i].MaxForce = 10

    #def invKinematics(self)
    # TODO

    def clean_cos(self,cos_angle):
        return min(1,max(cos_angle,-1))

    def setNewGoal(self):
        self.go = (0,0)
        self.newGoal = zeros(self.links)
        i = 0

        self.red_circle = (self.width/2,self.lenght/2)
        self.white_circle = (self.width/2,self.lenght/2)
        self.newGoalFlag =True

        while self.newGoalFlag:
            # Draw the current circle in red and erase previous
            pygame.draw.circle(self.srf, (255,255,255), (self.white_circle[0],self.white_circle[1]), 130, 1)
            pygame.draw.circle(self.srf, (255,0,0), (self.red_circle[0],self.red_circle[1]), 130, 1)
            pygame.draw.circle(self.srf, (255,0,0), (self.red_circle[0],self.red_circle[1]), 10, 1)

            pygame.display.flip()
            events = pygame.event.get()

            for e in events:
                if e.type==QUIT:
                    self.loopFlag=False
                    self.newGoalFlag = False
                if e.type==KEYDOWN:
                    self.loopFlag=False
                    self.newGoalFlag = False
                if e.type == MOUSEBUTTONDOWN:
                    self.go = pygame.mouse.get_pos()

                    self.white_circle = self.red_circle
                    self.red_circle = self.go

                    if i==0:
                        x01 = self.red_circle[0] - self.white_circle[0]
                        y01 = self.red_circle[1] - self.white_circle[1]
                        self.newGoal[i] = atan2(x01,y01)
                        print self.newGoal[i]
                    elif i==1:
                        x,y = self.screen2world(self.red_circle[0],self.red_circle[1])
                        print x,y
                        self.newGoal[i] = sign(x)* acos(self.clean_cos((pow(x,2)+pow(y,2)-pow(self.L[0,0],2) - pow(self.L[0,1],2))/(2*self.L[0,0]*self.L[0,1])))
                        print self.newGoal[i]
                    else:
                        self.newGoal[i] = 0

                    i +=1
                    if i == self.links:
                        self.setTarget(self.newGoal)
                        self.newGoalFlag = False
<commit_msg>Fixed IK for 1st link. Added IK function and world2screen (x,y)<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri May  2 01:17:09 2014

@author: jrcapriles
"""

import pygame, Buttons
from pygame.locals import *
import ode
from math import atan2, acos
from numpy import *
from Point import *
import matplotlib.pyplot as plt

class armSimulator( object ):
    def __init__( self, width, lenght, links):
        self.width, self.lenght, self.links = width, lenght, links
        self.L = ones((1,self.links))
        # Initialize pygame
        pygame.init()
        # Open a display
        self.srf = pygame.display.set_mode((self.width,self.lenght))
        pygame.display.set_caption(str(links) + "-link pendulum")
        self.fps = 50
        self.dt = 1.0/self.fps
        self.loopFlag = True
        #Parameters
        self.g= -9.81
        self.maxF = 20*ones((1,links))
        self.thetad = zeros((1,links))
        self.goal_button = Buttons.Button(self.srf, color = (200,0,0), x = 10, y = 10, length =  50, height = 25, width = 0, text = "Goal", text_color = (255,255,255), font_size = 20, fade_on = False)

    def createIC(self):
        rest = []
        left = []
        right = []
        up =[]
        #First loop to create all different combinations of IC
        for i in range(0,self.links+1):
            rest.append(Point(0,-i,0))
            left.append(Point(i,0,0))
            right.append(Point(-i,0,0))
            up.append(Point(0,i,0))

        #Create the dicionary
        self.ICList = {"Rest":rest,
                       "Left":left,
                       "Right":right,
                       "Up":up}

    def setTarget(self,target):
        self.thetad = target

    def getTarget(self, i):
        return self.thetad[i]

    def getTargetRange(self, i,j):
        return self.thetad[i:j]

    def setIC(self, case):
        self.IC = self.ICList[case]

    def getIC(self,i):
        return self.IC[i].getPoint()

    def setMaxF(self, F):
        if F is None:
            self.maxF = [10 for i in range(self.links)]
        else:
            self.maxF = F

    def getMaxF(self,i):
        return self.maxF[i]

    def getWidth(self):
        return self.width

    def getLenght(self):
            return self.leght

    def world2screen(self,x,y):
        return int(self.width/2 + 128*x), int(self.lenght/2 - 128*y)

    def world2screenX(self,x):
        return int(self.width/2 + 128*x)

    def world2screenY(self,y):
        return int(self.lenght/2 - 128*y)

    def screen2world(self,x,y):
        return float((x - self.width/2)/128), float((-y + self.lenght/2)/128)

    def surf(self, x,y):
        return (pow(x-pi/2,2) + pow(0.9*pi*y,2) - pow(pi/2,2))

    def phi(self, y):
        return -y -(2*self.a/sqrt(pow(self.a,2)-1))*arctan(sqrt((self.a-1)/(self.a+1))*tan(y/2))

    def runSimulation(self, case, targets):

        self.createIC()
        self.createArm(case)
        self.setTarget(targets)

        # Simulation loop.
        self.clk = pygame.time.Clock()

        while self.loopFlag:
            events = pygame.event.get()
            for e in events:
                if e.type==QUIT:
                    self.loopFlag=False
                if e.type==KEYDOWN:
                    if e.type==KEYDOWN:
                        if e.key == K_g:
                            print "New Goals: please click the new goal over the red circle"
                            self.setNewGoal()
                    else:
                        self.loopFlag=False
                elif e.type == MOUSEBUTTONDOWN:
                    if self.goal_button.pressed(pygame.mouse.get_pos()):
                        print "New Goals: please click the new goal over the red circle"
                        self.setNewGoal()

            # Clear the screen
            self.srf.fill((255,255,255))

            x = []
            xd = []
            y = []
            yd = []
            z = []
            vx = []
            vy = []
            vz = []
            theta = []
            #thetad = []
            errTheta = []
            thetaDot = []
            errThetaDot = []
            T = []

            #self.setTarget(-0.8*pi*ones((1,self.links)))

            for i in range(0,self.links):
                x1,y1,z1 = self.body[i].getPosition()
                x.append(x1)
                y.append(y1)
                z.append(z1)
                vx1,vy1,vz1 = self.body[i].getAngularVel()
                vx.append(vx1)
                vy.append(vy1)
                vz.append(vz1)
                theta.append(self.j[i].getAngle())
                #thetad.append(-0.5*pi)
                errTheta.append(theta[i]- self.getTarget(i))

                thetaDot.append(sum(vz))
                #thetaDotd.append(0.0)
                errThetaDot.append(self.getTarget(i)+thetaDot[i])

                if i == 0: #Kinematics
                    xd.append(-self.L[0,0]*sin(-self.getTarget(0)))
                    yd.append(-self.L[0,0]*cos(-self.getTarget(0)))
                else:
                    xd.append(xd[i-1]+self.L[0,i]*sin(-sum(self.getTargetRange(0,i))+self.getTarget(i)))
                    yd.append(yd[i-1]-self.L[0,i]*cos(-sum(self.getTargetRange(0,i))+self.getTarget(i)))

                T.append(-errTheta[i])

                #Set servo values
                self.j[i].setParam(ode.ParamVel, T[i])
                self.j[i].setParam(ode.ParamFMax, self.getMaxF(i))

           #Drawings
            for i in range(0,self.links):
                pygame.draw.circle(self.srf, (55,0,200), self.world2screen(x[i],y[i]), 10, 0)     #(Motors)
                pygame.draw.circle(self.srf, (55,0,100), self.world2screen(xd[i],yd[i]), 10, 0)   #(Targets)

                if i==0:
                    pygame.draw.line(self.srf, (55,0,200), self.world2screen(self.IC[0].getPointX(),self.IC[0].getPointY()), self.world2screen(x[i],y[i]), 2)
                    pygame.draw.circle(self.srf, (255,0,0), self.world2screen(self.IC[i].getPointX(),self.IC[i].getPointY()), 5, 0) #(origin)
                else:
                    pygame.draw.line(self.srf, (55,0,200), self.world2screen(x[i-1],y[i-1]), self.world2screen(x[i],y[i]), 2)

            self.drawBackLines()

            self.goal_button.update() #create_button(self.srf, (200,0,0), 10, 10, 50, 25, 0, "Goal", (255,255,255))

            pygame.display.flip()

            # Next simulation step
            self.world.step(self.dt)

            # Try to keep the specified framerate
            self.clk.tick(self.fps)

    def drawBackLines(self):
        #Draw the back lines of the screen
        pygame.draw.line(self.srf, (0,0,0), self.world2screen(0,-self.lenght/2), self.world2screen(0,self.lenght/2), 1)
        pygame.draw.line(self.srf, (0,0,0), self.world2screen(-self.width/2,0), self.world2screen(self.width/2,0), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(1,-self.lenght/2),self.world2screen(1,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(2,-self.lenght/2),self.world2screen(2,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-1,-self.lenght/2),self.world2screen(-1,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-2,-self.lenght/2),self.world2screen(-2,self.lenght/2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,1),self.world2screen(self.width/2,1), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,2),self.world2screen(self.width/2,2), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-1),self.world2screen(self.width/2,-1), 1)
        pygame.draw.line(self.srf, (192,192,192), self.world2screen(-self.width/2,-2),self.world2screen(self.width/2,-2), 1)

    def createArm(self,case):
        #This routine create the arm and set the initial condition accordingly.
        self.setIC(case)
        # Create a world object
        self.world = ode.World()
        self.world.setGravity((0,self.g,0))

        # Create the bodies
        self.body = []
        self.M = []
        self.j = []
        for i in range(0,self.links):
            self.body.append(ode.Body(self.world))
            self.M.append(ode.Mass())
            self.M[i].setSphere(2500, 0.025)
            self.body[i].setMass(self.M[i])
            self.body[i].setPosition(self.getIC(i+1))

            self.j.append(ode.HingeJoint(self.world))
            if i==0:
                self.j[i].attach(self.body[0], ode.environment)
                self.j[i].setAnchor(self.getIC(0))
            else:
                self.j[i].attach(self.body[i-1], self.body[i])
                self.j[i].setAnchor(self.body[i-1].getPosition())

            self.j[i].setAxis( (0,0,1) )
            self.j[i].setParam(ode.ParamLoStop, -5.0)
            self.j[i].setParam(ode.ParamHiStop,5.0)
            self.j[i].MaxForce = 10

    def IK(self, x_des, y_des):
        cos2= (pow(x_des,2) + pow(y_des,2) - pow(self.L[0,0],2) - pow(self.L[0,1],2))/(2*self.L[0,0]*self.L[0,1])
        c2 = self.clean_cos(cos2)
        theta2 = acos(c2)
        sin2 = sin(theta2)
        theta1 = ((-self.L[0,1]*sin2*x_des)+(self.L[0,0]+(self.L[0,1]*c2))*y_des)/((self.L[0,1]*sin2*y_des)+(self.L[0,0]+(self.L[0,1]*c2))*x_des)
        return theta1, theta2

    def clean_cos(self,cos_angle):
        return min(1,max(cos_angle,-1))

    def setNewGoal(self):
        self.go = (0,0)
        self.newGoal = zeros(self.links)
        i = 0

        self.red_circle = (self.width/2,self.lenght/2)
        self.white_circle = (self.width/2,self.lenght/2)
        self.newGoalFlag =True

        while self.newGoalFlag:
            # Draw the current circle in red and erase previous
            pygame.draw.circle(self.srf, (255,255,255), (self.white_circle[0],self.white_circle[1]), 130, 1)
            pygame.draw.circle(self.srf, (255,0,0), (self.red_circle[0],self.red_circle[1]), 130, 1)
            pygame.draw.circle(self.srf, (255,0,0), (self.red_circle[0],self.red_circle[1]), 10, 1)

            pygame.display.flip()
            events = pygame.event.get()

            for e in events:
                if e.type==QUIT:
                    self.loopFlag=False
                    self.newGoalFlag = False
                if e.type==KEYDOWN:
                    self.loopFlag=False
                    self.newGoalFlag = False
                if e.type == MOUSEBUTTONDOWN:
                    self.go = pygame.mouse.get_pos()
                    self.white_circle = self.red_circle
                    self.red_circle = self.go

                    if i==0:
                        x01 = self.red_circle[0] - self.white_circle[0]
                        y01 = self.red_circle[1] - self.white_circle[1]
                        self.newGoal[i] = atan2(x01,y01)
                        self.red_circle = self.world2screenX(self.L[0,0]*sin(self.newGoal[i])),self.world2screenY(-self.L[0,0]*cos(self.newGoal[i]))
#                    elif i==1:
#                        rx,ry = self.screen2world(self.red_circle[0],self.red_circle[1])
#                        wx,wy = self.screen2world(self.white_circle[0],self.white_circle[1])
#                        cos2 = (pow(rx,2)+pow(ry,2) - pow(self.L[0,0],2) - pow(self.L[0,1],2))/(2*self.L[0,0]*self.L[0,1])
#                        cos2 = self.clean_cos(cos2)
#
#
#                        ang1, ang2 = self.IK(rx,ry)
#                        self.newGoal[i] = ang2
#
#                        self.red_circle = self.world2screenX(self.L[0,0]*sin(self.newGoal[i])+self.L[0,1]*sin(self.newGoal[i-1]+self.newGoal[i])),self.world2screenY(-self.L[0,0]*cos(self.newGoal[i])+self.L[0,1]*cos(self.newGoal[i-1]+self.newGoal[i]))
#
#                        print self.newGoal[i]
                    else:
                        self.newGoal[i] = 0

                    i +=1
                    if i == self.links:
                        self.setTarget(self.newGoal)
                        self.newGoalFlag = False
<|endoftext|>


<commit_before>from mongoengine.common import _import_class
from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
from mongoengine.queryset import QuerySet

__all__ = ("switch_db", "switch_collection", "no_dereference",
           "no_sub_classes", "query_counter")

class switch_db(object):
    """ switch_db alias context manager.

    Example ::

        # Register connections
        register_connection('default', 'mongoenginetest')
        register_connection('testdb-1', 'mongoenginetest2')

        class Group(Document):
            name = StringField()

        Group(name="test").save()  # Saves in the default db

        with switch_db(Group, 'testdb-1') as Group:
            Group(name="hello testdb!").save()  # Saves in testdb-1

    """

    def __init__(self, cls, db_alias):
        """ Construct the switch_db context manager

        :param cls: the class to change the registered db
        :param db_alias: the name of the specific database to use
        """
        self.cls = cls
        self.collection = cls._get_collection()
        self.db_alias = db_alias
        self.ori_db_alias = cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)

    def __enter__(self):
        """ change the db_alias and clear the cached collection """
        self.cls._meta["db_alias"] = self.db_alias
        self.cls._collection = None
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the db_alias and collection """
        self.cls._meta["db_alias"] = self.ori_db_alias
        self.cls._collection = self.collection

class switch_collection(object):
    """ switch_collection alias context manager.

    Example ::

        class Group(Document):
            name = StringField()

        Group(name="test").save()  # Saves in the default db

        with switch_collection(Group, 'group1') as Group:
            Group(name="hello testdb!").save()  # Saves in group1 collection

    """

    def __init__(self, cls, collection_name):
        """ Construct the switch_collection context manager

        :param cls: the class to change the registered db
        :param collection_name: the name of the collection to use
        """
        self.cls = cls
        self.ori_collection = cls._get_collection()
        self.ori_get_collection_name = cls._get_collection_name
        self.collection_name = collection_name

    def __enter__(self):
        """ change the _get_collection_name and clear the cached collection """

        @classmethod
        def _get_collection_name(cls):
            return self.collection_name

        self.cls._get_collection_name = _get_collection_name
        self.cls._collection = None
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the collection """
        self.cls._collection = self.ori_collection
        self.cls._get_collection_name = self.ori_get_collection_name

class no_dereference(object):
    """ no_dereference context manager.

    Turns off all dereferencing in Documents for the duration of the context
    manager::

        with no_dereference(Group) as Group:
            Group.objects.find()

    """

    def __init__(self, cls):
        """ Construct the no_dereference context manager.

        :param cls: the class to turn dereferencing off on
        """
        self.cls = cls

        ReferenceField = _import_class('ReferenceField')
        GenericReferenceField = _import_class('GenericReferenceField')
        ComplexBaseField = _import_class('ComplexBaseField')

        self.deref_fields = [k for k, v in self.cls._fields.iteritems()
                             if isinstance(v, (ReferenceField,
                                               GenericReferenceField,
                                               ComplexBaseField))]

    def __enter__(self):
        """ change the objects default and _auto_dereference values"""
        for field in self.deref_fields:
            self.cls._fields[field]._auto_dereference = False
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the default and _auto_dereference values"""
        for field in self.deref_fields:
            self.cls._fields[field]._auto_dereference = True
        return self.cls

class no_sub_classes(object):
    """ no_sub_classes context manager.

    Only returns instances of this class and no sub (inherited) classes::

        with no_sub_classes(Group) as Group:
            Group.objects.find()

    """

    def __init__(self, cls):
        """ Construct the no_sub_classes context manager.

        :param cls: the class to turn querying sub classes on
        """
        self.cls = cls

    def __enter__(self):
        """ change the objects default and _auto_dereference values"""
        self.cls._all_subclasses = self.cls._subclasses
        self.cls._subclasses = (self.cls,)
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the default and _auto_dereference values"""
        self.cls._subclasses = self.cls._all_subclasses
        delattr(self.cls, '_all_subclasses')
        return self.cls

class QuerySetNoDeRef(QuerySet):
    """Special no_dereference QuerySet"""
    def __dereference(items, max_depth=1, instance=None, name=None):
            return items

class query_counter(object):
    """ Query_counter context manager to get the number of queries. """

    def __init__(self):
        """ Construct the query_counter. """
        self.counter = 0
        self.db = get_db()

    def __enter__(self):
        """ On every with block we need to drop the profile collection. """
        self.db.set_profiling_level(0)
        self.db.system.profile.drop()
        self.db.set_profiling_level(2)
        return self

    def __exit__(self, t, value, traceback):
        """ Reset the profiling level. """
        self.db.set_profiling_level(0)

    def __eq__(self, value):
        """ == Compare querycounter. """
        counter = self._get_count()
        if value != counter:
            print [x for x in self.db.system.profile.find()]
        return value == counter

    def __ne__(self, value):
        """ != Compare querycounter. """
        return not self.__eq__(value)

    def __lt__(self, value):
        """ < Compare querycounter. """
        return self._get_count() < value

    def __le__(self, value):
        """ <= Compare querycounter. """
        return self._get_count() <= value

    def __gt__(self, value):
        """ > Compare querycounter. """
        return self._get_count() > value

    def __ge__(self, value):
        """ >= Compare querycounter. """
        return self._get_count() >= value

    def __int__(self):
        """ int representation. """
        return self._get_count()

    def __repr__(self):
        """ repr query_counter as the number of queries. """
        return u"%s" % self._get_count()

    def _get_count(self):
        """ Get the number of queries. """
        count = self.db.system.profile.find().count() - self.counter
        self.counter += 1
        return count
<commit_msg>Added comment about why temp debugging exists<commit_after>from mongoengine.common import _import_class
from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
from mongoengine.queryset import QuerySet

__all__ = ("switch_db", "switch_collection", "no_dereference",
           "no_sub_classes", "query_counter")

class switch_db(object):
    """ switch_db alias context manager.

    Example ::

        # Register connections
        register_connection('default', 'mongoenginetest')
        register_connection('testdb-1', 'mongoenginetest2')

        class Group(Document):
            name = StringField()

        Group(name="test").save()  # Saves in the default db

        with switch_db(Group, 'testdb-1') as Group:
            Group(name="hello testdb!").save()  # Saves in testdb-1

    """

    def __init__(self, cls, db_alias):
        """ Construct the switch_db context manager

        :param cls: the class to change the registered db
        :param db_alias: the name of the specific database to use
        """
        self.cls = cls
        self.collection = cls._get_collection()
        self.db_alias = db_alias
        self.ori_db_alias = cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)

    def __enter__(self):
        """ change the db_alias and clear the cached collection """
        self.cls._meta["db_alias"] = self.db_alias
        self.cls._collection = None
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the db_alias and collection """
        self.cls._meta["db_alias"] = self.ori_db_alias
        self.cls._collection = self.collection

class switch_collection(object):
    """ switch_collection alias context manager.

    Example ::

        class Group(Document):
            name = StringField()

        Group(name="test").save()  # Saves in the default db

        with switch_collection(Group, 'group1') as Group:
            Group(name="hello testdb!").save()  # Saves in group1 collection

    """

    def __init__(self, cls, collection_name):
        """ Construct the switch_collection context manager

        :param cls: the class to change the registered db
        :param collection_name: the name of the collection to use
        """
        self.cls = cls
        self.ori_collection = cls._get_collection()
        self.ori_get_collection_name = cls._get_collection_name
        self.collection_name = collection_name

    def __enter__(self):
        """ change the _get_collection_name and clear the cached collection """

        @classmethod
        def _get_collection_name(cls):
            return self.collection_name

        self.cls._get_collection_name = _get_collection_name
        self.cls._collection = None
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the collection """
        self.cls._collection = self.ori_collection
        self.cls._get_collection_name = self.ori_get_collection_name

class no_dereference(object):
    """ no_dereference context manager.

    Turns off all dereferencing in Documents for the duration of the context
    manager::

        with no_dereference(Group) as Group:
            Group.objects.find()

    """

    def __init__(self, cls):
        """ Construct the no_dereference context manager.

        :param cls: the class to turn dereferencing off on
        """
        self.cls = cls

        ReferenceField = _import_class('ReferenceField')
        GenericReferenceField = _import_class('GenericReferenceField')
        ComplexBaseField = _import_class('ComplexBaseField')

        self.deref_fields = [k for k, v in self.cls._fields.iteritems()
                             if isinstance(v, (ReferenceField,
                                               GenericReferenceField,
                                               ComplexBaseField))]

    def __enter__(self):
        """ change the objects default and _auto_dereference values"""
        for field in self.deref_fields:
            self.cls._fields[field]._auto_dereference = False
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the default and _auto_dereference values"""
        for field in self.deref_fields:
            self.cls._fields[field]._auto_dereference = True
        return self.cls

class no_sub_classes(object):
    """ no_sub_classes context manager.

    Only returns instances of this class and no sub (inherited) classes::

        with no_sub_classes(Group) as Group:
            Group.objects.find()

    """

    def __init__(self, cls):
        """ Construct the no_sub_classes context manager.

        :param cls: the class to turn querying sub classes on
        """
        self.cls = cls

    def __enter__(self):
        """ change the objects default and _auto_dereference values"""
        self.cls._all_subclasses = self.cls._subclasses
        self.cls._subclasses = (self.cls,)
        return self.cls

    def __exit__(self, t, value, traceback):
        """ Reset the default and _auto_dereference values"""
        self.cls._subclasses = self.cls._all_subclasses
        delattr(self.cls, '_all_subclasses')
        return self.cls

class QuerySetNoDeRef(QuerySet):
    """Special no_dereference QuerySet"""
    def __dereference(items, max_depth=1, instance=None, name=None):
            return items

class query_counter(object):
    """ Query_counter context manager to get the number of queries. """

    def __init__(self):
        """ Construct the query_counter. """
        self.counter = 0
        self.db = get_db()

    def __enter__(self):
        """ On every with block we need to drop the profile collection. """
        self.db.set_profiling_level(0)
        self.db.system.profile.drop()
        self.db.set_profiling_level(2)
        return self

    def __exit__(self, t, value, traceback):
        """ Reset the profiling level. """
        self.db.set_profiling_level(0)

    def __eq__(self, value):
        """ == Compare querycounter. """
        counter = self._get_count()
        # Temp debugging to try and understand intermittent travis-ci failures
        if value != counter:
            print [x for x in self.db.system.profile.find()]
        return value == counter

    def __ne__(self, value):
        """ != Compare querycounter. """
        return not self.__eq__(value)

    def __lt__(self, value):
        """ < Compare querycounter. """
        return self._get_count() < value

    def __le__(self, value):
        """ <= Compare querycounter. """
        return self._get_count() <= value

    def __gt__(self, value):
        """ > Compare querycounter. """
        return self._get_count() > value

    def __ge__(self, value):
        """ >= Compare querycounter. """
        return self._get_count() >= value

    def __int__(self):
        """ int representation. """
        return self._get_count()

    def __repr__(self):
        """ repr query_counter as the number of queries. """
        return u"%s" % self._get_count()

    def _get_count(self):
        """ Get the number of queries. """
        count = self.db.system.profile.find().count() - self.counter
        self.counter += 1
        return count
<|endoftext|>


<commit_before>import discord
import os
from datetime import datetime
from discord.ext import commands

from .utils.dataIO import dataIO
from .utils import checks

try: # check if BeautifulSoup4 is installed
    from bs4 import BeautifulSoup
    soupAvailable = True
except:
    soupAvailable = False

class hangman:
    def __init__(self, bot):
        self.bot = bot
        self.path = "data/Fox-Cogs/hangman"
        self.file_path = "data/Fox-Cogs/hangman/hangman.json"
        self.the_data = dataIO.load_json(self.file_path)
        self.hangman = ( "","H","HA","HAN","HANG","HANGM","HANGMA","HANGMAN")

    def save_data(self):
        dataIO.save_json(self.file_path, self.the_data)

    @commands.command(aliases=['h'], pass_context=True)
    async def hangman(self, ctx, guess : str=None):
        """Play a game of hangman against the bot!"""
        if guess is None:
            if self.the_data["running"] == True:
                await self.bot.say("Game of hangman is already running!\nEnter your guess!")
                """await self.bot.send_cmd_help(ctx)"""
            else:
                raise RuntimeError("starting error")
                await self.bot.say("Starting a game of hangman!")
                await self._startgame()
                await self._printgame()

        else:
            raise RuntimeError("stopping error")
            await self.bot.say("A game of hangman is now stopping!")
            await self._stopgame()
        """
        #self.the_data["WOAH"]["knarly"] = "Biiiiiitch"
        if "Yeah dude" not in self.the_data:
            self.the_data["Yeah dude"]={}
        self.the_data["Yeah dude"]["knarly"]= {"ur lyin" : True,
                                               "kick-ass" : { "no way!!!" : "Biiiiiitch" },
                                               "created_at" : datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                               }

        #self.the_data["Yeah dude"]["knarly"] = "ur lyin"
        #self.the_data["Yeah dude"]["knarly"]["kick-ass"]["no way!!!"] = "Biiiiiitch"
        self.save_data()
        """

    async def _startgame(self):
        self.the_data["running"] = True
        self.the_data["hangman"] = 0
        await self.save_data()
        #self._getphrase()
        #self._printgame()

    async def _stopgame(self):
        self.the_data["running"] = False
        await self.save_data()

    async def _getphrase(self):
        '''Get a new phrase for the game'''
        '''url = "https://www.playstationtrophies.org/forum/wheel-of-fortune-2012-/176009-wheel-fortune-answer-list.html"
        async with aiohttp.get(url) as response:
            soupObject = BeautifulSoup(await response.text(), "html.parser")
        try:
            online = soupObject.find(class_='home-stats').find('li').find('strong').get_text()
            await self.bot.say(online + ' players are playing this game at the moment')
        except:
            await self.bot.say("Couldn't load amount of players. No one is playing this game anymore or there's an error.")
        '''
    async def _guessletter(self):
        '''Checks the guess on a letter'''

    async def _printgame(self):
        '''Print the current state of game'''
        raise RuntimeError("print error")
        #await self.bot.say(self.hangman[the_data["hangman"]])
        #self.the_data["hangman"] += 1
        #await self.save_data()

def check_folders():
    if not os.path.exists("data/Fox-Cogs"):
        print("Creating data/Fox-Cogs folder...")
        os.makedirs("data/Fox-Cogs")

    if not os.path.exists("data/Fox-Cogs/hangman"):
        print("Creating data/Fox-Cogs/hangman folder...")
        os.makedirs("data/Fox-Cogs/hangman")

def check_files():
    if not dataIO.is_valid_json("data/Fox-Cogs/hangman/hangman.json"):
        dataIO.save_json("data/Fox-Cogs/hangman/hangman.json" ,{"running" : False, "hangman" : 0 })

def setup(bot):
    check_folders()
    check_files()
    if soupAvailable:
        bot.add_cog(hangman(bot))
    else:
        raise RuntimeError("You need to run `pip3 install beautifulsoup4`")

<commit_msg>WAAAAIT<commit_after>import discord
import os
from datetime import datetime
from discord.ext import commands

from .utils.dataIO import dataIO
from .utils import checks

try: # check if BeautifulSoup4 is installed
    from bs4 import BeautifulSoup
    soupAvailable = True
except:
    soupAvailable = False

class hangman:
    def __init__(self, bot):
        self.bot = bot
        self.path = "data/Fox-Cogs/hangman"
        self.file_path = "data/Fox-Cogs/hangman/hangman.json"
        self.the_data = dataIO.load_json(self.file_path)
        self.hangman = ( "","H","HA","HAN","HANG","HANGM","HANGMA","HANGMAN")

    def save_data(self):
        dataIO.save_json(self.file_path, self.the_data)

    @commands.command(aliases=['h'], pass_context=True)
    async def hangman(self, ctx, guess : str=None):
        """Play a game of hangman against the bot!"""
        if guess is None:
            if self.the_data["running"] == True:
                await self.bot.say("Game of hangman is already running!\nEnter your guess!")
                """await self.bot.send_cmd_help(ctx)"""
            else:
                raise RuntimeError("starting error")
                await self.bot.say("Starting a game of hangman!")
                self._startgame()
                await self._printgame()

        else:
            raise RuntimeError("stopping error")
            await self.bot.say("A game of hangman is now stopping!")
            self._stopgame()
        """
        #self.the_data["WOAH"]["knarly"] = "Biiiiiitch"
        if "Yeah dude" not in self.the_data:
            self.the_data["Yeah dude"]={}
        self.the_data["Yeah dude"]["knarly"]= {"ur lyin" : True,
                                               "kick-ass" : { "no way!!!" : "Biiiiiitch" },
                                               "created_at" : datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                               }

        #self.the_data["Yeah dude"]["knarly"] = "ur lyin"
        #self.the_data["Yeah dude"]["knarly"]["kick-ass"]["no way!!!"] = "Biiiiiitch"
        self.save_data()
        """

    def _startgame(self):
        self.the_data["running"] = True
        self.the_data["hangman"] = 0
        self.save_data()
        #self._getphrase()
        #self._printgame()

    def _stopgame(self):
        self.the_data["running"] = False
        self.save_data()

    async def _getphrase(self):
        '''Get a new phrase for the game'''
        '''url = "https://www.playstationtrophies.org/forum/wheel-of-fortune-2012-/176009-wheel-fortune-answer-list.html"
        async with aiohttp.get(url) as response:
            soupObject = BeautifulSoup(await response.text(), "html.parser")
        try:
            online = soupObject.find(class_='home-stats').find('li').find('strong').get_text()
            await self.bot.say(online + ' players are playing this game at the moment')
        except:
            await self.bot.say("Couldn't load amount of players. No one is playing this game anymore or there's an error.")
        '''
    async def _guessletter(self):
        '''Checks the guess on a letter'''

    async def _printgame(self):
        '''Print the current state of game'''
        raise RuntimeError("print error")
        #await self.bot.say(self.hangman[the_data["hangman"]])
        #self.the_data["hangman"] += 1
        #await self.save_data()

def check_folders():
    if not os.path.exists("data/Fox-Cogs"):
        print("Creating data/Fox-Cogs folder...")
        os.makedirs("data/Fox-Cogs")

    if not os.path.exists("data/Fox-Cogs/hangman"):
        print("Creating data/Fox-Cogs/hangman folder...")
        os.makedirs("data/Fox-Cogs/hangman")

def check_files():
    if not dataIO.is_valid_json("data/Fox-Cogs/hangman/hangman.json"):
        dataIO.save_json("data/Fox-Cogs/hangman/hangman.json" ,{"running" : False, "hangman" : 0 })

def setup(bot):
    check_folders()
    check_files()
    if soupAvailable:
        bot.add_cog(hangman(bot))
    else:
        raise RuntimeError("You need to run `pip3 install beautifulsoup4`")

<|endoftext|>


<commit_before>"""Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run
import libardrone

drone = libardrone.ARDrone()

@post('/do/<command>')
def do(command):
    """Execute the given command from the route."""
    try:
        getattr(drone, command)()
        return 'Command executed'
    except AttributeError:
        return 'Bad Command'

run(host='localhost', port=8080)
<commit_msg>Added more readable printout and receive messages from command route.<commit_after>"""Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run
import libardrone

drone = libardrone.ARDrone()

@post('/do/<command>')
def do(command):
    """Execute the given command from the route."""
    try:
        print('Command received: {}'.format(command))
        getattr(drone, command)()
        print('Command executed: {}'.format(command))
        return 'Command executed: {}'.format(command)
    except AttributeError:
        print('Bad Command: {}'.format(command))
        return 'Bad Command: {}'.format(command)

run(host='localhost', port=8080)
<|endoftext|>


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

"""."""

import os
import sqlite3 as s3
import sys

import matplotlib.pyplot as plt

import kam41

DATABASE = os.environ['HOME'] + "/.sqlite3/electriciteit.sqlite3"

def get_cli_params(expected_amount):
    """Check for presence of a CLI parameter."""
    if len(sys.argv) != (expected_amount + 1):
        print(f"{expected_amount} arguments expected, {len(sys.argv) - 1} received.")
        sys.exit(0)
    return sys.argv[1]

def get_historic_data(grouping, period, timeframe, telwerk, from_start_of_year=False):
    """
    Fetch import data LO
    """
    ret_data = []
    ret_lbls = []
    if from_start_of_year:
        interval = f"datetime(datetime(\'now\', \'-{period} {timeframe}\'), \'start of year\')"
    else:
        interval = f"datetime(\'now\', \'-{period} {timeframe}\')"
    db_con = s3.connect(DATABASE)
    with db_con:
        db_cur = db_con.cursor()
        db_cur.execute(f"SELECT strftime('{grouping}',sample_time) as grouped, \
                     MAX({telwerk})-MIN({telwerk}), \
                     MIN(sample_epoch) as t \
                     FROM kamstrup \
                     WHERE (sample_time >= {interval}) \
                     GROUP BY grouped \
                     ORDER BY t ASC \
                     ;"
                    )
        db_data = db_cur.fetchall()

    for row in db_data:
        ret_data.append(row[1]/1000) # convert Wh to kWh
        ret_lbls.append(row[0])

    return ret_data[-period*12:], ret_lbls[-period*12:]

def get_opwekking(period, timeframe, from_start_of_year=False):
    """
    Fetch production data
    """
    if from_start_of_year: #bogus code
        timeframe+=1
    ret_data = [0] * period*12
    return ret_data

def fetch_last_months():
    """
    ...
    """
    import_lo, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T1in', from_start_of_year=True)
    import_hi, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T2in', from_start_of_year=True)
    export_lo, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T1out', from_start_of_year=True)
    export_hi, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T2out', from_start_of_year=True)
    opwekking = get_opwekking(5, 'year')
    return data_lbls, import_lo, import_hi, opwekking, export_lo, export_hi

def plot_graph(output_file, data_tuple, plot_title):
    """
    ...
    """
    data_lbls = data_tuple[0]
    # import_lo = data_tuple[1]
    # import_hi = data_tuple[2]
    # opwekking = data_tuple[3]
    # export_lo = data_tuple[4]
    # export_hi = data_tuple[5]
    own_usage = [sum(x) for x in zip(data_tuple[3], data_tuple[5], data_tuple[4])]
    total_use = [sum(x) for x in zip(own_usage, data_tuple[1], data_tuple[2])]
    total_out = [sum(x) for x in zip(data_tuple[4], data_tuple[5])]
    data_lbls, total_use, total_out = kam41.build_arrays44(data_lbls, total_use, total_out)

    # Set the bar width
    bar_width = 0.75
    # Set the color alpha
    ahpla = 0.7
    # positions of the left bar-boundaries
    tick_pos = list(range(1, len(data_lbls[1])+1))

    #Create the general plot and the bar
    plt.rc('font', size=13)
    dummy, ax1 = plt.subplots(1, figsize=(20, 7))

    # Create a bar plot usage
    for idx in range(0,len(data_lbls[1])):
        ax1.bar(tick_pos, total_use[idx],
                width=bar_width,
                label=data_lbls[0][idx],
                alpha=ahpla,
                color='b',
                align='center'
                )
        # Create a bar plot of production
        ax1.bar(tick_pos, [-1*i for i in total_out[idx]],
                width=bar_width,
                label=data_lbls[0][idx],
                alpha=ahpla,
                color='g',
                align='center'
                )

    # Set Axes stuff
    ax1.set_ylabel("[kWh]")
    ax1.set_xlabel("Datetime")
    ax1.grid(which='major', axis='y', color='k', linestyle='--', linewidth=0.5)
    ax1.axhline(y=0, color='k')
    ax1.axvline(x=0, color='k')
    # Set plot stuff
    plt.xticks(tick_pos, data_lbls, rotation=-60)
    plt.title(f'{plot_title}')
    plt.legend(loc='upper left', ncol=5, framealpha=0.2)
    # Fit every nicely
    plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
    plt.tight_layout()
    plt.savefig(fname=f'{output_file}', format='png')

def main():
    """
    This is the main loop
    """
    OPTION = get_cli_params(1)

    if OPTION in ['-m', '-M', '-y', '-Y', '-a', '-A']:
        plot_graph('/tmp/kamstrupd/site/img/kam_vs_month_p.png',
                   fetch_last_months(),
                   "Verbruik per maand afgelopen jaren"
                  )

if __name__ == "__main__":
    main()
<commit_msg>introduction of numpy<commit_after>#!/usr/bin/env python3

"""."""

import os
import sqlite3 as s3
import sys

import matplotlib.pyplot as plt
import numpy as np

import kam41

DATABASE = os.environ['HOME'] + "/.sqlite3/electriciteit.sqlite3"

def get_cli_params(expected_amount):
    """Check for presence of a CLI parameter."""
    if len(sys.argv) != (expected_amount + 1):
        print(f"{expected_amount} arguments expected, {len(sys.argv) - 1} received.")
        sys.exit(0)
    return sys.argv[1]

def get_historic_data(grouping, period, timeframe, telwerk, from_start_of_year=False):
    """
    Fetch import data LO
    """
    ret_data = []
    ret_lbls = []
    if from_start_of_year:
        interval = f"datetime(datetime(\'now\', \'-{period} {timeframe}\'), \'start of year\')"
    else:
        interval = f"datetime(\'now\', \'-{period} {timeframe}\')"
    db_con = s3.connect(DATABASE)
    with db_con:
        db_cur = db_con.cursor()
        db_cur.execute(f"SELECT strftime('{grouping}',sample_time) as grouped, \
                     MAX({telwerk})-MIN({telwerk}), \
                     MIN(sample_epoch) as t \
                     FROM kamstrup \
                     WHERE (sample_time >= {interval}) \
                     GROUP BY grouped \
                     ORDER BY t ASC \
                     ;"
                    )
        db_data = db_cur.fetchall()

    for row in db_data:
        ret_data.append(row[1]/1000) # convert Wh to kWh
        ret_lbls.append(row[0])

    return np.array(ret_data[-period*12:]), np.array(ret_lbls[-period*12:])

def get_opwekking(period, timeframe, from_start_of_year=False):
    """
    Fetch production data
    """
    if from_start_of_year: #bogus code
        timeframe+=1
    ret_data = np.zeros(period*12)
    # return np.array(ret_data)
    return ret_data

def fetch_last_months():
    """
    ...
    """
    import_lo, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T1in', from_start_of_year=True)
    import_hi, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T2in', from_start_of_year=True)
    export_lo, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T1out', from_start_of_year=True)
    export_hi, data_lbls = get_historic_data('%Y-%m', 5, 'year', 'T2out', from_start_of_year=True)
    opwekking = get_opwekking(5, 'year')
    return data_lbls, import_lo, import_hi, opwekking, export_lo, export_hi

def plot_graph(output_file, data_tuple, plot_title):
    """
    ...
    """
    data_lbls = data_tuple[0]
    # import_lo = data_tuple[1]
    # import_hi = data_tuple[2]
    # opwekking = data_tuple[3]
    # export_lo = data_tuple[4]
    # export_hi = data_tuple[5]
    own_usage = [sum(x) for x in zip(data_tuple[3], data_tuple[5], data_tuple[4])]
    total_use = [sum(x) for x in zip(own_usage, data_tuple[1], data_tuple[2])]
    total_out = [sum(x) for x in zip(data_tuple[4], data_tuple[5])]
    data_lbls, total_use, total_out = kam41.build_arrays44(data_lbls, total_use, total_out)

    # Set the bar width
    bar_width = 0.75
    # Set the color alpha
    ahpla = 0.7
    # positions of the left bar-boundaries
    tick_pos = list(range(1, len(data_lbls[1])+1))

    #Create the general plot and the bar
    plt.rc('font', size=13)
    dummy, ax1 = plt.subplots(1, figsize=(20, 7))

    # Create a bar plot usage
    for idx in range(0,len(data_lbls[1])):
        ax1.bar(tick_pos, total_use[idx],
                width=bar_width,
                label=data_lbls[0][idx],
                alpha=ahpla,
                color='b',
                align='center'
                )
        # Create a bar plot of production
        ax1.bar(tick_pos, [-1*i for i in total_out[idx]],
                width=bar_width,
                label=data_lbls[0][idx],
                alpha=ahpla,
                color='g',
                align='center'
                )

    # Set Axes stuff
    ax1.set_ylabel("[kWh]")
    ax1.set_xlabel("Datetime")
    ax1.grid(which='major', axis='y', color='k', linestyle='--', linewidth=0.5)
    ax1.axhline(y=0, color='k')
    ax1.axvline(x=0, color='k')
    # Set plot stuff
    plt.xticks(tick_pos, data_lbls, rotation=-60)
    plt.title(f'{plot_title}')
    plt.legend(loc='upper left', ncol=5, framealpha=0.2)
    # Fit every nicely
    plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
    plt.tight_layout()
    plt.savefig(fname=f'{output_file}', format='png')

def main():
    """
    This is the main loop
    """
    OPTION = get_cli_params(1)

    if OPTION in ['-m', '-M', '-y', '-Y', '-a', '-A']:
        plot_graph('/tmp/kamstrupd/site/img/kam_vs_month_p.png',
                   fetch_last_months(),
                   "Verbruik per maand afgelopen jaren"
                  )

if __name__ == "__main__":
    main()
<|endoftext|>


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

"""

Allows sampling and hyper-parameter search from outside of Python.

Note: ROPT_NPROC is currently unsupported, until I find a way to cleanly kill all
      sub-processes.

Example:
    ROPT_NSEARCH=16 ROPT_NPROC=4 ropt.py python example.py run --lr='Choice([0.1,0.2,0.3])' --wd='uniform(0,10)'

    Runs 16 searches with up to 4 processes in parallel (these are ropt.py parameters)
    of the command 'python example.py run --lr X --wd Y' where X is sampled from  the given
    Choice distribution and Y is sampled from Uniform(0, 10).

Another example using Search wrappers is

    ROPT_TYPE=GridSearch ROPT_NAME=newton-2_experiment ropt.py CUDA_VISIBLE_DEVICES=0 python experiments.py main newton --lr="Choice([0.01,0.1])"

The convention is to always pass sampled arguments to ropt with an = sign, to wrap the sampler in quotes (required by most shells), and avoid spaces within these quotes. The choice of quotes and the casing for samplers is irrelevant.
"""

import os
import sys
import subprocess
import multiprocessing as mp
import randopt as ro

ROPT_TYPE = 'ROPT_TYPE'
ROPT_NAME = 'ROPT_NAME'
ROPT_DIR = 'ROPT_DIR'
ROPT_NSEARCH = 'ROPT_NSEARCH'
ROPT_NPROC = 'ROPT_NPROC'

class CommandGenerator(object):
    def __init__(self, command, parameters, samplers):
        self.command = command
        self.parameters = parameters
        self.samplers = samplers

    def __iter__(self):
        return self

    def __next__(self):
        values = [s.sample() for s in self.samplers]
        return self.command.format(*values)

    next = __next__

class ExperimentSampler(object):

    def __init__(self, command, parameters, experiment):
        self.experiment = experiment
        self.command = command
        self.parameters = parameters

    def __iter__(self):
        return self

    def __next__(self):
        self.experiment.sample_all_params()
        values = [current[p] for p in self.parameters]
        return self.command.format(*values)

    next = __next__

def is_number(s):
    """
    Copy-pasted from:
    https://www.pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/
    """
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

def parse_sampler(param):
    values = param[param.index('(') + 1:param.index(')')]
    if '[' in values or '(' in values:
        values = values[1:-1].split(',')
        values = [float(v) if is_number(v) else v for v in values]
        values = [values, ]
    else:
        values = values.split(',')
        values = [float(v) if is_number(v) else v for v in values]
    sampler = param[:param.index('(')].lower()
    samplers = {
        'uniform': ro.Uniform,
        'gaussian': ro.Gaussian,
        'normal': ro.Normal,
        'choice': ro.Choice,
        'constant': ro.Constant,
        'lognormvariate': ro.LognormVariate,
        'betavariate': ro.BetaVariate,
        'expovariate': ro.ExpoVariate,
        'weibullvariate': ro.WeibullVariate,
        'paretovariate': ro.ParetoVariate,
    }
    if sampler not in samplers:
        msg = 'The requested distribution is not implemented, yet.'
        raise NotImplementedError(msg)
    return samplers[sampler](*values)

def parse_experiment(param):
    if 'evo' in param.lower():
        return ro.Evolutionary
    elif 'grid' in param.lower():
        return ro.GridSearch
    else:
        msg = 'Experiment class not implemented in ropt.py yet.'
        raise NotImplementedError(msg)

if __name__ == '__main__':
    experiment = None
    if ROPT_TYPE in os.environ:
        experiment = os.environ[ROPT_TYPE]
        experiment = parse_experiment(experiment)
    experiment_name = None
    if ROPT_NAME in os.environ:
        experiment_name = os.environ[ROPT_NAME]
    experiment_dir = 'randopt_results'
    if ROPT_DIR in os.environ:
        experiment_dir = os.environ[ROPT_DIR]
    n_searches = -1
    if ROPT_NSEARCH in os.environ:
        n_searches = int(os.environ[ROPT_NSEARCH])
    n_processes = 1
    if ROPT_NPROC in os.environ:
        experiment_name = int(os.environ[ROPT_NPROC])

    arguments = sys.argv[1:]
    args_idx = 0

    command = ""
    parameters = []
    samplers = []
    for arg in arguments:
        if '=' in arg and '(' in arg and ')' in arg:
            # parse argument and sampler
            param, sampler = arg.split('=')
            command = command + ' ' + param + ' {' + str(len(samplers)) + ':10f}'
            sampler = parse_sampler(sampler)
            param = param.replace('-', '')
            parameters.append(param)
            samplers.append(sampler)
        else:
            command = command + ' ' + arg

    # Generate the right number of commands
    if experiment is not None and experiment_name is not None:
        print('Using ', experiment.__name__)
        print('sys: ', sys.argv)
        params = {p: s for p, s in zip(parameters, samplers)}
        experiment = experiment(ro.Experiment(name=experiment_name,
                                              params=params,
                                              directory=experiment_dir))
        command_generator = ExperimentSampler(command, parameters, experiment)
    else:
        command_generator = CommandGenerator(command, parameters, samplers)

    if n_searches == -1:
        n_searches = float('inf')
        commands = command_generator
    else:
        commands = (next(command_generator) for _ in range(n_searches))

    # Run until search finishes
    for i, command in enumerate(commands):
        print(i, ':', command)
        subprocess.call(command, shell=True)
<commit_msg>Restore wrongly deleted line.<commit_after>#!/usr/bin/env python3

"""

Allows sampling and hyper-parameter search from outside of Python.

Note: ROPT_NPROC is currently unsupported, until I find a way to cleanly kill all
      sub-processes.

Example:
    ROPT_NSEARCH=16 ROPT_NPROC=4 ropt.py python example.py run --lr='Choice([0.1,0.2,0.3])' --wd='uniform(0,10)'

    Runs 16 searches with up to 4 processes in parallel (these are ropt.py parameters)
    of the command 'python example.py run --lr X --wd Y' where X is sampled from  the given
    Choice distribution and Y is sampled from Uniform(0, 10).

Another example using Search wrappers is

    ROPT_TYPE=GridSearch ROPT_NAME=newton-2_experiment ropt.py CUDA_VISIBLE_DEVICES=0 python experiments.py main newton --lr="Choice([0.01,0.1])"

The convention is to always pass sampled arguments to ropt with an = sign, to wrap the sampler in quotes (required by most shells), and avoid spaces within these quotes. The choice of quotes and the casing for samplers is irrelevant.
"""

import os
import sys
import subprocess
import multiprocessing as mp
import randopt as ro

ROPT_TYPE = 'ROPT_TYPE'
ROPT_NAME = 'ROPT_NAME'
ROPT_DIR = 'ROPT_DIR'
ROPT_NSEARCH = 'ROPT_NSEARCH'
ROPT_NPROC = 'ROPT_NPROC'

class CommandGenerator(object):
    def __init__(self, command, parameters, samplers):
        self.command = command
        self.parameters = parameters
        self.samplers = samplers

    def __iter__(self):
        return self

    def __next__(self):
        values = [s.sample() for s in self.samplers]
        return self.command.format(*values)

    next = __next__

class ExperimentSampler(object):

    def __init__(self, command, parameters, experiment):
        self.experiment = experiment
        self.command = command
        self.parameters = parameters

    def __iter__(self):
        return self

    def __next__(self):
        self.experiment.sample_all_params()
        current = self.experiment.current
        values = [current[p] for p in self.parameters]
        return self.command.format(*values)

    next = __next__

def is_number(s):
    """
    Copy-pasted from:
    https://www.pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/
    """
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

def parse_sampler(param):
    values = param[param.index('(') + 1:param.index(')')]
    if '[' in values or '(' in values:
        values = values[1:-1].split(',')
        values = [float(v) if is_number(v) else v for v in values]
        values = [values, ]
    else:
        values = values.split(',')
        values = [float(v) if is_number(v) else v for v in values]
    sampler = param[:param.index('(')].lower()
    samplers = {
        'uniform': ro.Uniform,
        'gaussian': ro.Gaussian,
        'normal': ro.Normal,
        'choice': ro.Choice,
        'constant': ro.Constant,
        'lognormvariate': ro.LognormVariate,
        'betavariate': ro.BetaVariate,
        'expovariate': ro.ExpoVariate,
        'weibullvariate': ro.WeibullVariate,
        'paretovariate': ro.ParetoVariate,
    }
    if sampler not in samplers:
        msg = 'The requested distribution is not implemented, yet.'
        raise NotImplementedError(msg)
    return samplers[sampler](*values)

def parse_experiment(param):
    if 'evo' in param.lower():
        return ro.Evolutionary
    elif 'grid' in param.lower():
        return ro.GridSearch
    else:
        msg = 'Experiment class not implemented in ropt.py yet.'
        raise NotImplementedError(msg)

if __name__ == '__main__':
    experiment = None
    if ROPT_TYPE in os.environ:
        experiment = os.environ[ROPT_TYPE]
        experiment = parse_experiment(experiment)
    experiment_name = None
    if ROPT_NAME in os.environ:
        experiment_name = os.environ[ROPT_NAME]
    experiment_dir = 'randopt_results'
    if ROPT_DIR in os.environ:
        experiment_dir = os.environ[ROPT_DIR]
    n_searches = -1
    if ROPT_NSEARCH in os.environ:
        n_searches = int(os.environ[ROPT_NSEARCH])
    n_processes = 1
    if ROPT_NPROC in os.environ:
        experiment_name = int(os.environ[ROPT_NPROC])

    arguments = sys.argv[1:]
    args_idx = 0

    command = ""
    parameters = []
    samplers = []
    for arg in arguments:
        if '=' in arg and '(' in arg and ')' in arg:
            # parse argument and sampler
            param, sampler = arg.split('=')
            command = command + ' ' + param + ' {' + str(len(samplers)) + ':10f}'
            sampler = parse_sampler(sampler)
            param = param.replace('-', '')
            parameters.append(param)
            samplers.append(sampler)
        else:
            command = command + ' ' + arg

    # Generate the right number of commands
    if experiment is not None and experiment_name is not None:
        print('Using ', experiment.__name__)
        print('sys: ', sys.argv)
        params = {p: s for p, s in zip(parameters, samplers)}
        experiment = experiment(ro.Experiment(name=experiment_name,
                                              params=params,
                                              directory=experiment_dir))
        command_generator = ExperimentSampler(command, parameters, experiment)
    else:
        command_generator = CommandGenerator(command, parameters, samplers)

    if n_searches == -1:
        n_searches = float('inf')
        commands = command_generator
    else:
        commands = (next(command_generator) for _ in range(n_searches))

    # Run until search finishes
    for i, command in enumerate(commands):
        print(i, ':', command)
        subprocess.call(command, shell=True)
<|endoftext|>


<commit_before>import discord
import os
from datetime import datetime
from discord.ext import commands

from .utils.dataIO import dataIO
from .utils import checks

try: # check if BeautifulSoup4 is installed
    from bs4 import BeautifulSoup
    soupAvailable = True
except:
    soupAvailable = False

class hangman:
    def __init__(self, bot):
        self.bot = bot
        self.path = "data/Fox-Cogs/hangman"
        self.file_path = "data/Fox-Cogs/hangman/hangman.json"
        self.the_data = dataIO.load_json(self.file_path)
        #self.hanglist = ("_","H","HA","HAN","HANG","HANGM","HANGMA","HANGMAN")
        self.hanglist = (
        """>
           \_________
            |/
            |
            |
            |
            |
            |
            |\___
            """,

        """>
           \_________
            |/   |
            |
            |
            |
            |
            |
            |\___
            H""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |
            |
            |
            |
            |\___
            HA""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |    |
            |    |
            |
            |
            |\___
            HAN""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |   /|
            |     |
            |
            |
            |\___
            HANG""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |
            |
            |\___
            HANGM""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |   /
            |
            |\___
            HANGMA""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |   / \
            |
            |\___
            HANGMAN""")
    def save_data(self):
        dataIO.save_json(self.file_path, self.the_data)

    @commands.command(aliases=['h'], pass_context=True)
    async def hangman(self, ctx, guess : char=None):
        """Play a game of hangman against the bot!"""
        if guess is None:
            if self.the_data["running"] == True:
                await self.bot.say("Game of hangman is already running!\nEnter your guess!")
                self._printgame()
                """await self.bot.send_cmd_help(ctx)"""
            else:
                await self.bot.say("Starting a game of hangman!")
                self._startgame()
                await self._printgame()
        else:
            await self._guessletter(guess)
            if self.the_data["hangman"] >= 7:
                await self.bot.say("You Lose!")
                self._stopgame()

        """
        #self.the_data["WOAH"]["knarly"] = "Biiiiiitch"
        if "Yeah dude" not in self.the_data:
            self.the_data["Yeah dude"]={}
        self.the_data["Yeah dude"]["knarly"]= {"ur lyin" : True,
                                               "kick-ass" : { "no way!!!" : "Biiiiiitch" },
                                               "created_at" : datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                               }

        #self.the_data["Yeah dude"]["knarly"] = "ur lyin"
        #self.the_data["Yeah dude"]["knarly"]["kick-ass"]["no way!!!"] = "Biiiiiitch"
        self.save_data()
        """

    def _startgame(self):
        self.the_data["running"] = True
        self.the_data["hangman"] = 0
        self.the_data["answer"] = self._getphrase()
        self.the_data["guesses"] = []
        self.save_data()

    def _stopgame(self):
        self.the_data["running"] = False
        self.save_data()

    def _getphrase(self):
        '''Get a new phrase for the game and returns it'''
        return "SPACE" #For now

    def _hideanswer(self):
        '''Returns the obscured answer'''
        out_str = ""
        for i in self.the_data["answer"]:
            if i in self.the_data["guesses"]:
                out_str += i
            else:
                out_str += "*"

        return out_str

    def _guesses(self):
        '''Returns the current letter list'''
        out_str = ""
        for i in self.the_data["guesses"]:
            out_str += str(i) + ","
        out_str = out_str[:-1]

        return out_str

    async def _guessletter(self, guess : char = None):
        '''Checks the guess on a letter and prints game'''
        #if guess

        if guess.upper() in self.the_data["guesses"]:
            await self.bot.say("Already guessed that! Try again")
            return

        if not guess.upper() in self.the_data["answer"]:
            self.the_data["hangman"] += 1

        self.the_data["guesses"].append(guess.upper())
        self.save_data()
        await self._printgame()

    async def _printgame(self):
        '''Print the current state of game'''
        cSay = ("Guess this: "+str(self._hideanswer())+"\n"
                +"Used Letters: "+str(self._guesses)+"\n"
                +self.hanglist[self.the_data["hangman"]])
        await self.bot.say(cSay)

def check_folders():
    if not os.path.exists("data/Fox-Cogs"):
        print("Creating data/Fox-Cogs folder...")
        os.makedirs("data/Fox-Cogs")

    if not os.path.exists("data/Fox-Cogs/hangman"):
        print("Creating data/Fox-Cogs/hangman folder...")
        os.makedirs("data/Fox-Cogs/hangman")

def check_files():
    if not dataIO.is_valid_json("data/Fox-Cogs/hangman/hangman.json"):
        dataIO.save_json("data/Fox-Cogs/hangman/hangman.json" ,{"running" : False, "hangman" : 0 })

def setup(bot):
    check_folders()
    check_files()
    if soupAvailable:
        bot.add_cog(hangman(bot))
    else:
        raise RuntimeError("You need to run `pip3 install beautifulsoup4`")<commit_msg>nevermind<commit_after>import discord
import os
from datetime import datetime
from discord.ext import commands

from .utils.dataIO import dataIO
from .utils import checks

try: # check if BeautifulSoup4 is installed
    from bs4 import BeautifulSoup
    soupAvailable = True
except:
    soupAvailable = False

class hangman:
    def __init__(self, bot):
        self.bot = bot
        self.path = "data/Fox-Cogs/hangman"
        self.file_path = "data/Fox-Cogs/hangman/hangman.json"
        self.the_data = dataIO.load_json(self.file_path)
        #self.hanglist = ("_","H","HA","HAN","HANG","HANGM","HANGMA","HANGMAN")
        self.hanglist = (
        """>
           \_________
            |/
            |
            |
            |
            |
            |
            |\___
            """,

        """>
           \_________
            |/   |
            |
            |
            |
            |
            |
            |\___
            H""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |
            |
            |
            |
            |\___
            HA""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |    |
            |    |
            |
            |
            |\___
            HAN""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |   /|
            |     |
            |
            |
            |\___
            HANG""",

        """>
           \_________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |
            |
            |\___
            HANGM""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |   /
            |
            |\___
            HANGMA""",

        """>
           \________
            |/   |
            |   <:never:336861463446814720>
            |   /|\
            |     |
            |   / \
            |
            |\___
            HANGMAN""")
    def save_data(self):
        dataIO.save_json(self.file_path, self.the_data)

    @commands.command(aliases=['h'], pass_context=True)
    async def hangman(self, ctx, guess : string=None):
        """Play a game of hangman against the bot!"""
        if guess is None:
            if self.the_data["running"] == True:
                await self.bot.say("Game of hangman is already running!\nEnter your guess!")
                self._printgame()
                """await self.bot.send_cmd_help(ctx)"""
            else:
                await self.bot.say("Starting a game of hangman!")
                self._startgame()
                await self._printgame()
        else:
            await self._guessletter(guess)
            if self.the_data["hangman"] >= 7:
                await self.bot.say("You Lose!")
                self._stopgame()

        """
        #self.the_data["WOAH"]["knarly"] = "Biiiiiitch"
        if "Yeah dude" not in self.the_data:
            self.the_data["Yeah dude"]={}
        self.the_data["Yeah dude"]["knarly"]= {"ur lyin" : True,
                                               "kick-ass" : { "no way!!!" : "Biiiiiitch" },
                                               "created_at" : datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                               }

        #self.the_data["Yeah dude"]["knarly"] = "ur lyin"
        #self.the_data["Yeah dude"]["knarly"]["kick-ass"]["no way!!!"] = "Biiiiiitch"
        self.save_data()
        """

    def _startgame(self):
        self.the_data["running"] = True
        self.the_data["hangman"] = 0
        self.the_data["answer"] = self._getphrase()
        self.the_data["guesses"] = []
        self.save_data()

    def _stopgame(self):
        self.the_data["running"] = False
        self.save_data()

    def _getphrase(self):
        '''Get a new phrase for the game and returns it'''
        return "SPACE" #For now

    def _hideanswer(self):
        '''Returns the obscured answer'''
        out_str = ""
        for i in self.the_data["answer"]:
            if i in self.the_data["guesses"]:
                out_str += i
            else:
                out_str += "*"

        return out_str

    def _guesses(self):
        '''Returns the current letter list'''
        out_str = ""
        for i in self.the_data["guesses"]:
            out_str += str(i) + ","
        out_str = out_str[:-1]

        return out_str

    async def _guessletter(self, guess : chr = None):
        '''Checks the guess on a letter and prints game'''
        #if guess

        if guess.upper() in self.the_data["guesses"]:
            await self.bot.say("Already guessed that! Try again")
            return

        if not guess.upper() in self.the_data["answer"]:
            self.the_data["hangman"] += 1

        self.the_data["guesses"].append(guess.upper())
        self.save_data()
        await self._printgame()

    async def _printgame(self):
        '''Print the current state of game'''
        cSay = ("Guess this: "+str(self._hideanswer())+"\n"
                +"Used Letters: "+str(self._guesses)+"\n"
                +self.hanglist[self.the_data["hangman"]])
        await self.bot.say(cSay)

def check_folders():
    if not os.path.exists("data/Fox-Cogs"):
        print("Creating data/Fox-Cogs folder...")
        os.makedirs("data/Fox-Cogs")

    if not os.path.exists("data/Fox-Cogs/hangman"):
        print("Creating data/Fox-Cogs/hangman folder...")
        os.makedirs("data/Fox-Cogs/hangman")

def check_files():
    if not dataIO.is_valid_json("data/Fox-Cogs/hangman/hangman.json"):
        dataIO.save_json("data/Fox-Cogs/hangman/hangman.json" ,{"running" : False, "hangman" : 0 })

def setup(bot):
    check_folders()
    check_files()
    if soupAvailable:
        bot.add_cog(hangman(bot))
    else:
        raise RuntimeError("You need to run `pip3 install beautifulsoup4`")<|endoftext|>