<commit_before># PointGenerator.py
import numpy
import math
import random
from Point import *

def _checkInputs(lowerBounds, upperBounds, spacing, number, testDim=None):
    if testDim is None:
        testDim = len(lowerBounds)
    if not (testDim == len(lowerBounds) == len(upperBounds)):
        raise(TypeError("All supplied arguments must be iterables of the same length."))
    if spacing is None and number is None:
        raise(TypeError("Must specify either spacing or number and not both."))
    if spacing is not None and number is not None:
        raise(TypeError("Must specify either spacing or number and not both."))
    if spacing is None:
        if len(number) != testDim:
            raise(TypeError("All supplied arguments must be iterables of the same length."))
    if number is None:
        if len(spacing)!=2:
            raise(TypeError("All supplied arguments must be iterables of the same length."))

def cart_2D(lowerBounds, upperBounds, spacing=None, number=None):
    _checkInputs(lowerBounds, upperBounds, spacing, number, 2)
    if number is None:
        number = [math.floor((u-l)/s)+1 for l,u,s in zip(lowerBounds,upperBounds,spacing)]
    for x in numpy.linspace(lowerBounds[0], upperBounds[0], num=number[0]):
        for y in numpy.linspace(lowerBounds[1], upperBounds[1], num=number[1]):
            yield Point([x,y])

def perterbed_cart_2D(lowerBounds, upperBounds, spacing=None, number=None, r=0.1, seed=None):
    grid_points = cart_2D(lowerBounds, upperBounds, spacing, number, return_iterator=True)
    random.seed(seed)
    for point in grid_points:
        r_x = r * (2*random.random()-1)
        r_y = r * (2*random.random()-1)
        point.move((r_x, r_y))
        yield point

def random_2D(lowerBounds, upperBounds, numPoints=20, seed=None):
    random.seed(seed)
    r = random.random
    points = []
    if not (2 == len(lowerBounds) == len(upperBounds)):
        raise(TypeError("lowerBounds and upperBounds must be iterables of length 2."))
    for i in range(numPoints):
        yield Point([l+r()*(u-l) for l,u in zip(lowerBounds, upperBounds)])

def lloyd_relaxation(points):
    pass
<commit_msg>Changed named number arg to num, inline with numpy.linspace<commit_after># PointGenerator.py
import numpy
import math
import random
from Point import *

def _checkInputs(lowerBounds, upperBounds, spacing, num, testDim=None):
    if testDim is None:
        testDim = len(lowerBounds)
    if not (testDim == len(lowerBounds) == len(upperBounds)):
        raise(TypeError("All supplied arguments must be iterables of the same length."))
    if spacing is None and num is None:
        raise(TypeError("Must specify either spacing or number and not both."))
    if spacing is not None and num is not None:
        raise(TypeError("Must specify either spacing or number and not both."))
    if spacing is None:
        if len(num) != testDim:
            raise(TypeError("All supplied arguments must be iterables of the same length."))
    if num is None:
        if len(spacing)!=2:
            raise(TypeError("All supplied arguments must be iterables of the same length."))

def cart_2D(lowerBounds, upperBounds, spacing=None, num=None):
    _checkInputs(lowerBounds, upperBounds, spacing, num, 2)
    if num is None:
        num = [math.floor((u-l)/s)+1 for l,u,s in zip(lowerBounds,upperBounds,spacing)]
    for x in numpy.linspace(lowerBounds[0], upperBounds[0], num=num[0]):
        for y in numpy.linspace(lowerBounds[1], upperBounds[1], num=num[1]):
            yield Point([x,y])

def perterbed_cart_2D(lowerBounds, upperBounds, spacing=None, num=None, r=0.1, seed=None):
    grid_points = cart_2D(lowerBounds, upperBounds, spacing, num, return_iterator=True)
    random.seed(seed)
    for point in grid_points:
        r_x = r * (2*random.random()-1)
        r_y = r * (2*random.random()-1)
        point.move((r_x, r_y))
        yield point

def random_2D(lowerBounds, upperBounds, numPoints=20, seed=None):
    random.seed(seed)
    r = random.random
    points = []
    if not (2 == len(lowerBounds) == len(upperBounds)):
        raise(TypeError("lowerBounds and upperBounds must be iterables of length 2."))
    for i in range(numPoints):
        yield Point([l+r()*(u-l) for l,u in zip(lowerBounds, upperBounds)])

def lloyd_relaxation(points):
    pass
<|endoftext|>


<commit_before>#!/usr/bin/python

import pygame
from pygame.locals import *
import Vec2D
from Vec2D import *
import random

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE =  (  0,   0, 255)
GREEN = (  0, 255,   0)
RED =   (255,   0,   0)
MAGENTA = (255,0,255)
CYAN = (0,255,255)
YELLOW = (255,255,0)

MAXSTATIONS = 5

MAX_X = MAX_Y = 500

LINES = [YELLOW,MAGENTA,CYAN,GREEN,BLUE,RED]

CARWITH = 10     # actually half of it
CARLENGTH = 20   # actually half of it
CARSPEED = 3

STATIONSIZE = 17
STATIONTHICKNESS = 5
STATIONDISTANCE = CARLENGTH * 4

screen = pygame.display.set_mode((MAX_X, MAX_Y))

class Car():
	"""A railcar. Each track holds at least one"""

	def __init__(self,track):
		self.track = track
		self.pos = track.startpos
		self.direction = 1
		self.counter = 0
		self.poly = ((-CARWITH,-CARLENGTH),(-CARWITH,CARLENGTH),
		   			 (CARWITH,CARLENGTH),(CARWITH,-CARLENGTH))

	def move(self):
		"""returns the moved polygon to self.pos with angle of self.track"""

		ret = []
		pol = self.poly

		# determine angle of track
		start = self.track.startpos
		end = self.track.endpos
		v = Vec2d(start[0]-end[0],start[1]-end[1])
		angle = v.get_angle() + 90

		# turn around
		turnedpol = []
		for p in pol:
			v = Vec2d(p)
			turnedpol.append(v.rotated(angle))

		# move to self.pos
		for p in turnedpol:
			ret.append([p[0] + self.pos[0], p[1] + self.pos[1]])

		return ret

	def draw(self):
		"""draw the car."""

		moved = self.move()
		pygame.draw.polygon(screen,self.track.color,moved,0)
		# pygame.draw.aalines(screen,BLUE,False,moved,5)

	def update(self):
		"""calculate new position of car"""

		self.pos = self.track.get_newpos(self.pos,self.counter,self.direction)
		# print "new position: ", self.pos
		if self.track.is_end(self.pos):
			print "TURN AROUND!"
			self.direction *= -1
			print "NEW DIRECTION: ", self.direction
			self.counter = 0
		self.counter += 1

class Track():
	"""A railtrack between stations. Holds at minimum one Car"""

	def __init__(self,start,end):
		"""constructor should only be called, if LINES[] is not empty"""

		self.color = LINES.pop()
		print "Track has color ", self.color
		self.startpos = start
		self.endpos = end
		self.cars = []
		self.cars.append(Car(self))

	def draw(self):
		pygame.draw.line(screen,self.color,self.startpos,self.endpos,5)
		for c in self.cars:
			c.draw()

	def length(self):
		"""returns the length of the track"""

		#TODO: calculate only once if track changes
		start = self.startpos
		end = self.endpos
		return ( (start[0]-end[0])**2 + (start[1]-end[1])**2 ) ** .5

	def get_newpos(self,pos,count,direction=1):
		""" calculates new position of a car in direction.
		direction should be 1 or -1"""

		start = self.startpos
		end = self.endpos
		ret = [0,0]
		length = self.length()
		xdiff = (start[0] - end[0]) / length * CARSPEED * -1
		ydiff = (start[1] - end[1]) / length * CARSPEED * -1
		if direction > 0:
			ret[0] = int(xdiff * count) + start[0]
			ret[1] = int(ydiff * count) + start[1]
		else:
			ret[0] = end[0] - int(xdiff * count)
			ret[1] = end[1] - int(ydiff * count)
		return ret

	def is_end(self,pos):
		"""returns True if is one of the ends of the track"""

		start = self.startpos
		end = self.endpos
		x_range = [start[0],end[0]]
		y_range = [start[1],end[1]]
		x_range.sort()
		y_range.sort()
		if (x_range[0] <= pos[0] <= x_range[1] and
		   y_range[0] <= pos[1] <= y_range[1]):
			return False
		return True

class Line():
	"""A line contains multiple tracks between stations"""

	# TODO

class Station():
	"""a station"""

	def __init__(self,pos,shape='circle'):
		self.shape = shape
		self.pos = pos

	def draw(self):
		size = 20
		pos = self.pos

		if self.shape == 'circle':
			pygame.draw.circle(screen,BLACK,pos,STATIONSIZE)
			pygame.draw.circle(screen,WHITE,pos,STATIONSIZE-STATIONTHICKNESS)

stations = []
tracks = []

def init_city():
	"""we set some Stations in place."""

	print "Setting stations..."
	for i in range(0,MAXSTATIONS):
		foundpos = False
		while not foundpos:
			newstationpos = (random.randint(0 + 2 * STATIONSIZE,
								   MAX_X - 2 * STATIONSIZE),
			        random.randint(0 + 2 * STATIONSIZE,
								   MAX_Y - 2 * STATIONSIZE))
			print "trying position ", newstationpos
			foundpos = True
			for s in stations:
				if is_in_range(newstationpos,s.pos,STATIONDISTANCE):
					foundpos = False
					print "... is to near to ", s.pos

			if foundpos:
				print "position ok!"
				s = Station(newstationpos)
				stations.append(s)

def is_in_range(pos1,pos2,dist=STATIONSIZE):
	"""returns true if pos1 and pos2 are not more than dist pixels apart"""

	if pos1[0] < pos2[0] - dist:
		return False
	if pos1[0] > pos2[0] + dist:
		return False
	if pos1[1] < pos2[1] - dist:
		return False
	if pos1[1] > pos2[1] + dist:
		return False
	return True

def is_station_pos(pos):
	"""returns center of station if at pos is a station.
	this could maybe easier implemented with SpriteGroups?"""

	for s in stations:
		if is_in_range(pos,s.pos):
			return s.pos
	return False

def update():
	"""updates (position of) all user independent objects"""

	for t in tracks:
		for c in t.cars:
			c.update()

def main():

	# this status is True if the user is drawing a track
	draw_status = False

	init_city()

	# Initialise screen
	pygame.init()
	clock = pygame.time.Clock()
	pygame.display.set_caption('Maxi Metro')
	pygame.display.update()

	pos = (0,0);
	startpos = (0,0)
	# Event loop
	while 1:

		screen.fill(WHITE)

		# TODO: the whole handling of track-creation should be
		#       in the Line-class
		for event in pygame.event.get():
			if event.type == QUIT:
				return
			elif event.type == MOUSEBUTTONDOWN:
				draw_status = False
				if LINES:
					pos = event.pos
					spos = is_station_pos(pos)
					if spos and not draw_status:
						#track = Track(spos)
						startpos = spos
						print "start drawing from " ,pos, " moving to ", startpos
						draw_status = True
				else:
					print "NO MORE LINES AVAIABLE!"
			elif event.type == MOUSEMOTION:
				pos = event.pos
				spos = is_station_pos(pos)
				# TODO: end should be not start
				# TODO: there should be no station in the way
				#       (plus a little extrasize)
				# TODO: should not cross other tracks
				if draw_status and spos and not is_in_range(pos,startpos):
					print "stop drawing at " , pos , " moving to " , spos
					track = Track(startpos, spos)
					tracks.append(track)
					draw_status = False
			# elif event.type == MOUSEBUTTONUP:

		if draw_status:
			pygame.draw.line(screen,LINES[-1],startpos,pos,5)

		update()

		# display all stations and tracks
		for t in tracks:
			t.draw()
		for s in stations:
			s.draw()

		pygame.display.update()
		msElapsed = clock.tick(10)

if __name__ == '__main__': main()
<commit_msg>more preparations for multi-track lines<commit_after>#!/usr/bin/python

import pygame
from pygame.locals import *
import Vec2D
from Vec2D import *
import random

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE =  (  0,   0, 255)
GREEN = (  0, 255,   0)
RED =   (255,   0,   0)
MAGENTA = (255,0,255)
CYAN = (0,255,255)
YELLOW = (255,255,0)

MAXSTATIONS = 5

MAX_X = MAX_Y = 500

LINES = [YELLOW,MAGENTA,CYAN,GREEN,BLUE,RED]

CARWITH = 10     # actually half of it
CARLENGTH = 20   # actually half of it
CARSPEED = 3

STATIONSIZE = 17
STATIONTHICKNESS = 5
STATIONDISTANCE = CARLENGTH * 4

screen = pygame.display.set_mode((MAX_X, MAX_Y))

class Car():
	"""A railcar. Each track holds at least one"""

	def __init__(self,track):
		self.track = track
		self.pos = track.startpos
		self.direction = 1
		self.counter = 0
		self.poly = ((-CARWITH,-CARLENGTH),(-CARWITH,CARLENGTH),
		   			 (CARWITH,CARLENGTH),(CARWITH,-CARLENGTH))

	def move(self):
		"""returns the moved polygon to self.pos with angle of self.track"""

		ret = []
		pol = self.poly

		# determine angle of track
		start = self.track.startpos
		end = self.track.endpos
		v = Vec2d(start[0]-end[0],start[1]-end[1])
		angle = v.get_angle() + 90

		# turn around
		turnedpol = []
		for p in pol:
			v = Vec2d(p)
			turnedpol.append(v.rotated(angle))

		# move to self.pos
		for p in turnedpol:
			ret.append([p[0] + self.pos[0], p[1] + self.pos[1]])

		return ret

	def draw(self):
		"""draw the car."""

		moved = self.move()
		pygame.draw.polygon(screen,self.track.color,moved,0)
		# pygame.draw.aalines(screen,BLUE,False,moved,5)

	def update(self):
		"""calculate new position of car"""

		self.pos = self.track.get_newpos(self.pos,self.counter,self.direction)
		# print "new position: ", self.pos
		if self.track.is_end(self.pos):
			print "TURN AROUND!"
			self.direction *= -1
			print "NEW DIRECTION: ", self.direction
			self.counter = 0
		self.counter += 1

class Track():
	"""A railtrack between stations. Holds at minimum one Car"""

	def __init__(self,start,end,color):
		"""constructor should only be called, if LINES[] is not empty"""

		self.color = color
		self.startpos = start
		self.endpos = end
		self.cars = []
		self.cars.append(Car(self))

	def draw(self):
		pygame.draw.line(screen,self.color,self.startpos,self.endpos,5)
		for c in self.cars:
			c.draw()

	def length(self):
		"""returns the length of the track"""

		#TODO: calculate only once if track changes
		start = self.startpos
		end = self.endpos
		return ( (start[0]-end[0])**2 + (start[1]-end[1])**2 ) ** .5

	def get_newpos(self,pos,count,direction=1):
		""" calculates new position of a car in direction.
		direction should be 1 or -1"""

		start = self.startpos
		end = self.endpos
		ret = [0,0]
		length = self.length()
		xdiff = (start[0] - end[0]) / length * CARSPEED * -1
		ydiff = (start[1] - end[1]) / length * CARSPEED * -1
		if direction > 0:
			ret[0] = int(xdiff * count) + start[0]
			ret[1] = int(ydiff * count) + start[1]
		else:
			ret[0] = end[0] - int(xdiff * count)
			ret[1] = end[1] - int(ydiff * count)
		return ret

	def is_end(self,pos):
		"""returns True if is one of the ends of the track"""

		start = self.startpos
		end = self.endpos
		x_range = [start[0],end[0]]
		y_range = [start[1],end[1]]
		x_range.sort()
		y_range.sort()
		if (x_range[0] <= pos[0] <= x_range[1] and
		   y_range[0] <= pos[1] <= y_range[1]):
			return False
		return True

class Line():
	"""A line contains multiple tracks between stations"""

	def __init__(self,start,end):
		self.color = LINES.pop()
		self.tracks = []
		self.tracks.append(Track(start,end,self.color))

	def update(self):
		for t in self.tracks:
			t.update()

	def draw(self):
		for t in self.tracks:
			t.draw()

class Station():
	"""a station"""

	def __init__(self,pos,shape='circle'):
		self.shape = shape
		self.pos = pos

	def draw(self):
		size = 20
		pos = self.pos

		if self.shape == 'circle':
			pygame.draw.circle(screen,BLACK,pos,STATIONSIZE)
			pygame.draw.circle(screen,WHITE,pos,STATIONSIZE-STATIONTHICKNESS)

stations = []
lines = []

def init_city():
	"""we set some Stations in place."""

	print "Setting stations..."
	for i in range(0,MAXSTATIONS):
		foundpos = False
		while not foundpos:
			newstationpos = (random.randint(0 + 2 * STATIONSIZE,
								   MAX_X - 2 * STATIONSIZE),
			        random.randint(0 + 2 * STATIONSIZE,
								   MAX_Y - 2 * STATIONSIZE))
			print "trying position ", newstationpos
			foundpos = True
			for s in stations:
				if is_in_range(newstationpos,s.pos,STATIONDISTANCE):
					foundpos = False
					print "... is to near to ", s.pos

			if foundpos:
				print "position ok!"
				s = Station(newstationpos)
				stations.append(s)

def is_in_range(pos1,pos2,dist=STATIONSIZE):
	"""returns true if pos1 and pos2 are not more than dist pixels apart"""

	if pos1[0] < pos2[0] - dist:
		return False
	if pos1[0] > pos2[0] + dist:
		return False
	if pos1[1] < pos2[1] - dist:
		return False
	if pos1[1] > pos2[1] + dist:
		return False
	return True

def is_station_pos(pos):
	"""returns center of station if at pos is a station.
	this could maybe easier implemented with SpriteGroups?"""

	for s in stations:
		if is_in_range(pos,s.pos):
			return s.pos
	return False

def update():
	"""updates (position of) all user independent objects"""

	for l in lines:
		for t in l.tracks:
			for c in t.cars:
				c.update()

def main():

	# this status is True if the user is drawing a track
	draw_status = False

	init_city()

	# Initialise screen
	pygame.init()
	clock = pygame.time.Clock()
	pygame.display.set_caption('Maxi Metro')
	pygame.display.update()

	pos = (0,0);
	startpos = (0,0)
	# Event loop
	while 1:

		screen.fill(WHITE)

		# TODO: the whole handling of track-creation should be
		#       in the Line-class
		for event in pygame.event.get():
			if event.type == QUIT:
				return
			elif event.type == MOUSEBUTTONDOWN:
				draw_status = False
				if LINES:
					pos = event.pos
					spos = is_station_pos(pos)
					if spos and not draw_status:
						#track = Track(spos)
						startpos = spos
						print "start drawing from " ,pos, " moving to ", startpos
						draw_status = True
				else:
					print "NO MORE LINES AVAIABLE!"
			elif event.type == MOUSEMOTION:
				pos = event.pos
				spos = is_station_pos(pos)
				# TODO: end should be not start
				# TODO: there should be no station in the way
				#       (plus a little extrasize)
				# TODO: should not cross other tracks
				if draw_status and spos and not is_in_range(pos,startpos):
					print "stop drawing at " , pos , " moving to " , spos
					line = Line(startpos, spos)
					lines.append(line)
					draw_status = False
			# elif event.type == MOUSEBUTTONUP:

		if draw_status:
			pygame.draw.line(screen,LINES[-1],startpos,pos,5)

		update()

		# display all stations and tracks
		for l in lines:
			l.draw()
		for s in stations:
			s.draw()

		pygame.display.update()
		msElapsed = clock.tick(10)

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


<commit_before><commit_msg><commit_after><|endoftext|>


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

class Vector:
	""" Represent a vector in a multidimensional space. """

	def __init__(self, d):
		""" Create d-dimensional vector of zeros. """
		self._coords = [0] * d

	def __len__(self):
		""" Return the dimension of the vector. """
		return len(self._coords)

	def __getitem__(self, j):
		""" Return jth coordinate of vector. """
		return self._coords[j]

	def __setitem__(self, j, val):
		""" Set jth coordinate of vector to given value."""
		self._coords[j] = val

	def __add__(self, other):
		""" Return sum of two vectors. """
		if len(self) != len(other):
			raise ValueError('dimensions must agree')
		result = Vector(len(self))
		for j in range(len(self)):
			result[j] = self[j] + other[j]
		return result

	def __eq__(self, other):
		""" Return True if vector has some coordinate as other. """
		return self._coords == other._coords

	def __ne__(self, other):
		""" Return True if vector differs from other. """
		return not self == other

	def __str__(self):
		""" Produce string representation of vector. """
		return '<' + str(self._coords)[1:-1] + '>'

if __name__ == '__main__':
	v1 = Vector(2)
	v2 = Vector(3)
	print len(v1)
	print len(v2)<commit_msg>modified env python<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

class Vector:
	""" Represent a vector in a multidimensional space. """

	def __init__(self, d):
		""" Create d-dimensional vector of zeros. """
		self._coords = [0] * d

	def __len__(self):
		""" Return the dimension of the vector. """
		return len(self._coords)

	def __getitem__(self, j):
		""" Return jth coordinate of vector. """
		return self._coords[j]

	def __setitem__(self, j, val):
		""" Set jth coordinate of vector to given value."""
		self._coords[j] = val

	def __add__(self, other):
		""" Return sum of two vectors. """
		if len(self) != len(other):
			raise ValueError('dimensions must agree')
		result = Vector(len(self))
		for j in range(len(self)):
			result[j] = self[j] + other[j]
		return result

	def __eq__(self, other):
		""" Return True if vector has some coordinate as other. """
		return self._coords == other._coords

	def __ne__(self, other):
		""" Return True if vector differs from other. """
		return not self == other

	def __str__(self):
		""" Produce string representation of vector. """
		return '<' + str(self._coords)[1:-1] + '>'

if __name__ == '__main__':
	v1 = Vector(2)
	v2 = Vector(3)
	print v1
	print len(v1)
	print len(v2)
<|endoftext|>


<commit_before><commit_msg>cannot add int and str.  did you know that?<commit_after><|endoftext|>


<commit_before>from selenium import webdriver
import os
import tests

browsers = [
	{"browserName": "chrome", "platform": "Windows 7", "version": "45.0"},
	{"browserName": "chrome", "platform": "Windows 7", "version": "44.0"},
	{"browserName": "chrome", "platform": "Windows 7", "version": "43.0"},

	{"browserName": "firefox", "platform": "Windows 7", "version": "40.0"},
	{"browserName": "firefox", "platform": "Windows 7", "version": "39.0"},
	{"browserName": "firefox", "platform": "Windows 7", "version": "38.0"},

	{"browserName": "internet explorer", "platform": "Windows 7", "version": "11.0"},
	{"browserName": "internet explorer", "platform": "Windows 7", "version": "10.0"},

	{"browserName": "opera", "platform": "Windows 7", "version": "12.12"}
]

default_capabilities = {}
default_capabilities["javascriptEnabled"] = True
username = os.environ["SAUCE_USERNAME"]
access_key = os.environ["SAUCE_ACCESS_KEY"]
default_capabilities["tunnel-identifier"] = os.environ["TRAVIS_JOB_NUMBER"]
default_capabilities["build"] = os.environ["TRAVIS_BUILD_NUMBER"]
url = "%s:%s@localhost:4445" % (username, access_key)

for browser in browsers:
	capabilities = default_capabilities.copy()
	capabilities.update(browser)
	driver = webdriver.Remote(desired_capabilities=capabilities, command_executor="http://%s/wd/hub" % url)

	print("Running tests on %s v%s" % (browser["browserName"], browser["version"]))
	tests.login.test(driver, "tests", "password")
	driver.add_cookie({"name": "sessionId", "value": ""})
	tests.addpost.test(driver, "tests", "password")

	driver.close()
	driver.quit()
<commit_msg>Add catches and prints of tests from outside their tests.<commit_after>from selenium import webdriver
import os
import traceback
from termcolor import cprint
import tests

browsers = [
	{"browserName": "chrome", "platform": "Windows 7", "version": "45.0"},
	{"browserName": "chrome", "platform": "Windows 7", "version": "44.0"},
	{"browserName": "chrome", "platform": "Windows 7", "version": "43.0"},

	{"browserName": "firefox", "platform": "Windows 7", "version": "40.0"},
	{"browserName": "firefox", "platform": "Windows 7", "version": "39.0"},
	{"browserName": "firefox", "platform": "Windows 7", "version": "38.0"},

	{"browserName": "internet explorer", "platform": "Windows 7", "version": "11.0"},
	{"browserName": "internet explorer", "platform": "Windows 7", "version": "10.0"},

	{"browserName": "opera", "platform": "Windows 7", "version": "12.12"}
]

default_capabilities = {}
default_capabilities["javascriptEnabled"] = True
username = os.environ["SAUCE_USERNAME"]
access_key = os.environ["SAUCE_ACCESS_KEY"]
default_capabilities["tunnel-identifier"] = os.environ["TRAVIS_JOB_NUMBER"]
default_capabilities["build"] = os.environ["TRAVIS_BUILD_NUMBER"]
url = "%s:%s@localhost:4445" % (username, access_key)

for browser in browsers:
	capabilities = default_capabilities.copy()
	capabilities.update(browser)
	driver = webdriver.Remote(desired_capabilities=capabilities, command_executor="http://%s/wd/hub" % url)

	print("Running tests on %s v%s" % (browser["browserName"], browser["version"]))

	#Login Test
	failed = False
	try:
		tests.login.test(driver, "tests", "password")

	except:
		traceback.print_exc()
		failed = True

	if failed:
		cprint("Login test failed.", "red")

	else:
		cprint("Login test passed", "green")

	driver.add_cookie({"name": "sessionId", "value": ""})

	#Add Post Test
	failed = False
	try:
		tests.addpost.test(driver, "tests", "password")

	except:
		traceback.print_exc()
		failed = True

	if failed:
		cprint("Add post test failed.", "red")

	else:
		cprint("Add post test passed", "green")

	driver.close()
	driver.quit()
<|endoftext|>


<commit_before># Standard
import threading
import time
from queue import Queue

# Internal
from readers import *

class Worker(threading.Thread):
    """ A worker thread which sleeps for a set interval then reads a current
    temperature using the get_temp method of the passed reader object
    """
    def __init__(self, interval, reader, queue):
        super().__init__()
        self.daemon = True
        self.interval = interval
        self.reader = reader
        self.queue = queue

    def run(self):
        while True:
            time.sleep(self.interval)
            reading = self.reader.get_temp()
            self.queue.put(reading)

def printr(writing_queue):
    while True:
        message = writing_queue.get()
        print(message)

class PhpWriter(threading.Thread):

    def __init__(self, queue):
        super().__init__()
        self.queue = queue
        self.url = "http://www.cutsquash.com/add-reading.php"
        self.key = PHP_KEY
        self.daemon = False

    def run(self):
        while True:
            # Get the reading from the queue
            reading = self.queue.get()

            # Add the secret key
            reading['key'] = self.key

            # Add to the db
            # TODO handle connection errors
            response = requests.get(self.url, params=reading)
            print(reading)

if __name__ == "__main__":

    # Set up queue and workers
    q = Queue()
    workers = list()
    workers.append(Worker(60, WebReader("web"), q))
    workers.append(Worker(60, DHTReader("dht"), q))
    #workers.append(Worker(0.1, DummySerialReader(), q))

    # Set up thread for output
    p = PhpWriter(q)

    # Start threads
    for worker in workers:
        worker.start()
    p.start()
<commit_msg>Untested SerialReader class<commit_after># Standard
import threading
import time
from queue import Queue

# Internal
from readers import *
from readers_pi import *

class Worker(threading.Thread):
    """ A worker thread which sleeps for a set interval then reads a current
    temperature using the get_temp method of the passed reader object
    """
    def __init__(self, interval, reader, queue):
        super().__init__()
        self.daemon = True
        self.interval = interval
        self.reader = reader
        self.queue = queue

    def run(self):
        while True:
            time.sleep(self.interval)
            reading = self.reader.get_temp()
            self.queue.put(reading)

def printr(writing_queue):
    while True:
        message = writing_queue.get()
        print(message)

class PhpWriter(threading.Thread):

    def __init__(self, queue):
        super().__init__()
        self.queue = queue
        self.url = "http://www.cutsquash.com/add-reading.php"
        self.key = PHP_KEY
        self.daemon = False

    def run(self):
        while True:
            # Get the reading from the queue
            reading = self.queue.get()

            # Add the secret key
            reading['key'] = self.key

            # Add to the db
            # TODO handle connection errors
            response = requests.get(self.url, params=reading)
            print(reading)

if __name__ == "__main__":

    # Set up queue and workers
    q = Queue()
    workers = list()
    workers.append(Worker(600, WebReader("web"), q))
    #workers.append(Worker(60, DHTReader("dht"), q))
    workers.append(Worker(0.1, SerialReader(), q))

    # Set up thread for output
    p = PhpWriter(q)

    # Start threads
    for worker in workers:
        worker.start()
    p.start()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from __future__ import absolute_import

import datetime
import getpass
import logging
import pytz

from django.core import mail

from sentry.conf import settings
from sentry.exceptions import InvalidInterface, InvalidData
from sentry.interfaces import Interface
from sentry.models import Group, Project

from tests.base import TestCase

# Configure our test handler

logger = logging.getLogger(__name__)

class SentryMailTest(TestCase):
    fixtures = ['tests/fixtures/mail.json']

    def setUp(self):
        settings.ADMINS = ('%s@localhost' % getpass.getuser(),)

    def test_mail_admins(self):
        group = Group.objects.get()
        self.assertEquals(len(mail.outbox), 0)
        group.mail_admins(fail_silently=False)
        self.assertEquals(len(mail.outbox), 1)

        # TODO: needs a new fixture
        # out = mail.outbox[0]

        # self.assertTrue('Traceback (most recent call last):' in out.body)
        # self.assertTrue("COOKIES:{'commenter_name': 'admin'," in out.body, out.body)
        # self.assertEquals(out.subject, '[Django] Error (EXTERNAL IP): /group/1')

    # def test_mail_on_creation(self):
    #     settings.MAIL = True

    #     self.assertEquals(len(mail.outbox), 0)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)

    #     out = mail.outbox[0]

    #     self.assertTrue('Traceback (most recent call last):' in out.body)
    #     self.assertTrue("<Request" in out.body)
    #     self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    # def test_mail_on_duplication(self):
    #     settings.MAIL = True

    #     self.assertEquals(len(mail.outbox), 0)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     # XXX: why wont this work
    #     # group = Group.objects.update(status=1)
    #     group = Group.objects.all().order_by('-id')[0]
    #     group.status = 1
    #     group.save()
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 2)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 2)

    #     out = mail.outbox[1]

    #     self.assertTrue('Traceback (most recent call last):' in out.body)
    #     self.assertTrue("<Request" in out.body)
    #     self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    def test_url_prefix(self):
        settings.URL_PREFIX = 'http://example.com'

        group = Group.objects.get()
        group.mail_admins(fail_silently=False)

        out = mail.outbox[0]

        self.assertTrue('http://example.com/group/2' in out.body, out.body)

class DummyInterface(Interface):
    def __init__(self, baz):
        self.baz = baz

class SentryManagerTest(TestCase):
    def test_invalid_project(self):
        self.assertRaises(Project.DoesNotExist, Group.objects.from_kwargs, 2, message='foo')

    def test_invalid_interface_name(self):
        self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={
            'foo': 'bar',
        })

    def test_invalid_interface_import_path(self):
        self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={
            'sentry.interfaces.Exception2': 'bar',
        })

    def test_invalid_interface_args(self):
        self.assertRaises(InvalidData, Group.objects.from_kwargs, 1, message='foo', data={
            'tests.tests.DummyInterface': {'foo': 'bar'}
        })

    def test_missing_required_args(self):
        self.assertRaises(InvalidData, Group.objects.from_kwargs, 1)

    def test_valid_only_message(self):
        event = Group.objects.from_kwargs(1, message='foo')
        self.assertEquals(event.message, 'foo')
        self.assertEquals(event.project_id, 1)

    def test_valid_timestamp_with_tz(self):
        with self.Settings(USE_TZ=True):
            date = datetime.datetime.now().replace(tzinfo=pytz.utc)
            event = Group.objects.from_kwargs(1, message='foo', timestamp=date)
            self.assertEquals(event.message, 'foo')
            self.assertEquals(event.project_id, 1)
            self.assertEquals(event.datetime, date)

    def test_valid_timestamp_without_tz(self):
        # TODO: this doesnt error, but it will throw a warning. What should we do?
        with self.Settings(USE_TZ=True):
            date = datetime.datetime.now()
            event = Group.objects.from_kwargs(1, message='foo', timestamp=date)
            self.assertEquals(event.message, 'foo')
            self.assertEquals(event.project_id, 1)
            self.assertEquals(event.datetime, date)

    def test_legacy_data(self):
        result = Group.objects.convert_legacy_kwargs({'message_id': '1234'})
        self.assertEquals(result['event_id'], '1234')

        result = Group.objects.convert_legacy_kwargs({'message': 'hello', 'class_name': 'ValueError'})
        self.assertEquals(result['message'], 'ValueError: hello')

        result = Group.objects.convert_legacy_kwargs({'view': 'foo.bar'})
        self.assertEquals(result['culprit'], 'foo.bar')

        result = Group.objects.convert_legacy_kwargs({'data': {
            'url': 'http://foo.com',
            'META': {
                'REQUEST_METHOD': 'POST',
                'QUERY_STRING': 'foo=bar'
            }
        }})
        self.assertTrue('sentry.interfaces.Http' in result)
        http = result['sentry.interfaces.Http']
        self.assertEquals(http['url'], 'http://foo.com')
        self.assertEquals(http['query_string'], 'foo=bar')
        self.assertEquals(http['method'], 'POST')
        self.assertEquals(http['data'], {})

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'exception': ('TypeError', ('hello world',)),
            }
        }})
        self.assertTrue('sentry.interfaces.Exception' in result)
        exc = result['sentry.interfaces.Exception']
        self.assertEquals(exc['type'], 'TypeError')
        self.assertEquals(exc['value'], 'hello world')

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'frames': [
                    {
                        'filename': 'foo.py',
                        'function': 'hello_world',
                        'vars': {},
                        'pre_context': ['before i did something'],
                        'context_line': 'i did something',
                        'post_context': ['after i did something'],
                        'lineno': 15,
                    },
                ],
            }
        }})
        self.assertTrue('sentry.interfaces.Stacktrace' in result)
        stack = result['sentry.interfaces.Stacktrace']
        self.assertEquals(len(stack['frames']), 1)
        frame = stack['frames'][0]
        self.assertEquals(frame['filename'], 'foo.py')
        self.assertEquals(frame['function'], 'hello_world')

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'user': {
                    'is_authenticated': True,
                    'id': 1,
                },
            }
        }})
        self.assertTrue('sentry.interfaces.User' in result)
        user = result['sentry.interfaces.User']
        self.assertTrue('is_authenticated' in user)
        self.assertEquals(user['is_authenticated'], True)
        self.assertTrue('id' in user)
        self.assertEquals(user['id'], 1)

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'template': [
                    "foo\nbar\nbaz\nbiz\nbin",
                    5,
                    3,
                    'foo.html',
                ],
            }
        }})
        self.assertTrue('sentry.interfaces.Template' in result)
        user = result['sentry.interfaces.Template']
        # 'post_context': [(2, 'bar\n'), (3, 'baz\n'), (4, 'biz\n')], 'pre_context': [(0, '')], 'lineno': 1, 'context_line': (1, 'foo\n'), 'filename': 'foo.html'}

        self.assertTrue('pre_context' in user)
        self.assertEquals(user['pre_context'], [(0, ''), (1, 'foo\n')])
        self.assertTrue('post_context' in user)
        self.assertEquals(user['post_context'], [(3, 'baz\n'), (4, 'biz\n'), (5, 'bin')])
        self.assertTrue('lineno' in user)
        self.assertEquals(user['lineno'], 2)
        self.assertTrue('context_line' in user)
        self.assertEquals(user['context_line'], 'bar\n')
<commit_msg>Ensure timestamp works in convert legacy kwargs<commit_after># -*- coding: utf-8 -*-

from __future__ import absolute_import

import datetime
import getpass
import logging
import pytz

from django.core import mail

from sentry.conf import settings
from sentry.exceptions import InvalidInterface, InvalidData
from sentry.interfaces import Interface
from sentry.models import Group, Project

from tests.base import TestCase

# Configure our test handler

logger = logging.getLogger(__name__)

class SentryMailTest(TestCase):
    fixtures = ['tests/fixtures/mail.json']

    def setUp(self):
        settings.ADMINS = ('%s@localhost' % getpass.getuser(),)

    def test_mail_admins(self):
        group = Group.objects.get()
        self.assertEquals(len(mail.outbox), 0)
        group.mail_admins(fail_silently=False)
        self.assertEquals(len(mail.outbox), 1)

        # TODO: needs a new fixture
        # out = mail.outbox[0]

        # self.assertTrue('Traceback (most recent call last):' in out.body)
        # self.assertTrue("COOKIES:{'commenter_name': 'admin'," in out.body, out.body)
        # self.assertEquals(out.subject, '[Django] Error (EXTERNAL IP): /group/1')

    # def test_mail_on_creation(self):
    #     settings.MAIL = True

    #     self.assertEquals(len(mail.outbox), 0)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)

    #     out = mail.outbox[0]

    #     self.assertTrue('Traceback (most recent call last):' in out.body)
    #     self.assertTrue("<Request" in out.body)
    #     self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    # def test_mail_on_duplication(self):
    #     settings.MAIL = True

    #     self.assertEquals(len(mail.outbox), 0)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 1)
    #     # XXX: why wont this work
    #     # group = Group.objects.update(status=1)
    #     group = Group.objects.all().order_by('-id')[0]
    #     group.status = 1
    #     group.save()
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 2)
    #     self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc'))
    #     self.assertEquals(len(mail.outbox), 2)

    #     out = mail.outbox[1]

    #     self.assertTrue('Traceback (most recent call last):' in out.body)
    #     self.assertTrue("<Request" in out.body)
    #     self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500')

    def test_url_prefix(self):
        settings.URL_PREFIX = 'http://example.com'

        group = Group.objects.get()
        group.mail_admins(fail_silently=False)

        out = mail.outbox[0]

        self.assertTrue('http://example.com/group/2' in out.body, out.body)

class DummyInterface(Interface):
    def __init__(self, baz):
        self.baz = baz

class SentryManagerTest(TestCase):
    def test_invalid_project(self):
        self.assertRaises(Project.DoesNotExist, Group.objects.from_kwargs, 2, message='foo')

    def test_invalid_interface_name(self):
        self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={
            'foo': 'bar',
        })

    def test_invalid_interface_import_path(self):
        self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={
            'sentry.interfaces.Exception2': 'bar',
        })

    def test_invalid_interface_args(self):
        self.assertRaises(InvalidData, Group.objects.from_kwargs, 1, message='foo', data={
            'tests.tests.DummyInterface': {'foo': 'bar'}
        })

    def test_missing_required_args(self):
        self.assertRaises(InvalidData, Group.objects.from_kwargs, 1)

    def test_valid_only_message(self):
        event = Group.objects.from_kwargs(1, message='foo')
        self.assertEquals(event.message, 'foo')
        self.assertEquals(event.project_id, 1)

    def test_valid_timestamp_with_tz(self):
        with self.Settings(USE_TZ=True):
            date = datetime.datetime.now().replace(tzinfo=pytz.utc)
            event = Group.objects.from_kwargs(1, message='foo', timestamp=date)
            self.assertEquals(event.message, 'foo')
            self.assertEquals(event.project_id, 1)
            self.assertEquals(event.datetime, date)

    def test_valid_timestamp_without_tz(self):
        # TODO: this doesnt error, but it will throw a warning. What should we do?
        with self.Settings(USE_TZ=True):
            date = datetime.datetime.now()
            event = Group.objects.from_kwargs(1, message='foo', timestamp=date)
            self.assertEquals(event.message, 'foo')
            self.assertEquals(event.project_id, 1)
            self.assertEquals(event.datetime, date)

    def test_legacy_data(self):
        result = Group.objects.convert_legacy_kwargs({'timestamp': '1234'})
        self.assertEquals(result['timestamp'], '1234')

        result = Group.objects.convert_legacy_kwargs({'message_id': '1234'})
        self.assertEquals(result['event_id'], '1234')

        result = Group.objects.convert_legacy_kwargs({'message': 'hello', 'class_name': 'ValueError'})
        self.assertEquals(result['message'], 'ValueError: hello')

        result = Group.objects.convert_legacy_kwargs({'view': 'foo.bar'})
        self.assertEquals(result['culprit'], 'foo.bar')

        result = Group.objects.convert_legacy_kwargs({'data': {
            'url': 'http://foo.com',
            'META': {
                'REQUEST_METHOD': 'POST',
                'QUERY_STRING': 'foo=bar'
            }
        }})
        self.assertTrue('sentry.interfaces.Http' in result)
        http = result['sentry.interfaces.Http']
        self.assertEquals(http['url'], 'http://foo.com')
        self.assertEquals(http['query_string'], 'foo=bar')
        self.assertEquals(http['method'], 'POST')
        self.assertEquals(http['data'], {})

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'exception': ('TypeError', ('hello world',)),
            }
        }})
        self.assertTrue('sentry.interfaces.Exception' in result)
        exc = result['sentry.interfaces.Exception']
        self.assertEquals(exc['type'], 'TypeError')
        self.assertEquals(exc['value'], 'hello world')

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'frames': [
                    {
                        'filename': 'foo.py',
                        'function': 'hello_world',
                        'vars': {},
                        'pre_context': ['before i did something'],
                        'context_line': 'i did something',
                        'post_context': ['after i did something'],
                        'lineno': 15,
                    },
                ],
            }
        }})
        self.assertTrue('sentry.interfaces.Stacktrace' in result)
        stack = result['sentry.interfaces.Stacktrace']
        self.assertEquals(len(stack['frames']), 1)
        frame = stack['frames'][0]
        self.assertEquals(frame['filename'], 'foo.py')
        self.assertEquals(frame['function'], 'hello_world')

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'user': {
                    'is_authenticated': True,
                    'id': 1,
                },
            }
        }})
        self.assertTrue('sentry.interfaces.User' in result)
        user = result['sentry.interfaces.User']
        self.assertTrue('is_authenticated' in user)
        self.assertEquals(user['is_authenticated'], True)
        self.assertTrue('id' in user)
        self.assertEquals(user['id'], 1)

        result = Group.objects.convert_legacy_kwargs({'data': {
            '__sentry__': {
                'template': [
                    "foo\nbar\nbaz\nbiz\nbin",
                    5,
                    3,
                    'foo.html',
                ],
            }
        }})
        self.assertTrue('sentry.interfaces.Template' in result)
        user = result['sentry.interfaces.Template']
        # 'post_context': [(2, 'bar\n'), (3, 'baz\n'), (4, 'biz\n')], 'pre_context': [(0, '')], 'lineno': 1, 'context_line': (1, 'foo\n'), 'filename': 'foo.html'}

        self.assertTrue('pre_context' in user)
        self.assertEquals(user['pre_context'], [(0, ''), (1, 'foo\n')])
        self.assertTrue('post_context' in user)
        self.assertEquals(user['post_context'], [(3, 'baz\n'), (4, 'biz\n'), (5, 'bin')])
        self.assertTrue('lineno' in user)
        self.assertEquals(user['lineno'], 2)
        self.assertTrue('context_line' in user)
        self.assertEquals(user['context_line'], 'bar\n')
<|endoftext|>


<commit_before>import unittest
#from kiigameEditorServer import server

class Tests(unittest.TestCase):

    def test_tests_should_work(self):
        self.assertEqual(True, True)

<commit_msg>Removed pointless tests<commit_after>import unittest
#from kiigameEditorServer import server

class Tests(unittest.TestCase):

    def test_tests_should_work(self):
        self.assertEqual(True, True)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding:utf-8
import requests
from re import search
from bs4 import BeautifulSoup
from time import sleep

class v2ex(object):
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
        'Origin': 'http://www.v2ex.com',
        'Referer': 'http://www.v2ex.com/signin',
        'Host': 'www.v2ex.com'
    }

    def __init__(self, usrname, usrpswd):
        self.usrname = usrname
        self.usrpswd = usrpswd

    def login(self):
        sess = requests.Session()
        LoginHtml = sess.get('http://www.v2ex.com/signin', headers=self.headers)
        LoginSoup = BeautifulSoup(LoginHtml.text, 'lxml')
        usrnamecode = LoginSoup.find('input', {'class': 'sl'})['name']
        usrpswdcode = LoginSoup.find('input', {'type': 'password'})['name']
        once = LoginSoup.find('input', {'name': 'once'})['value']
        from_data = {
            usrnamecode: self.usrname,
            usrpswdcode: self.usrpswd,
            'once': once,
            'next': '/'
            }
        sess.post('http://www.v2ex.com/signin', from_data, headers=self.headers)
        sethtml = sess.get('http://www.v2ex.com/settings', headers=self.headers)
        soup = BeautifulSoup(sethtml.text, 'lxml')
        email = soup.find('input', {'type': 'email'})['value']
        status = True if email else False
        print '登录成功！' if status else '登录失败！'
        return [sess, status]

    def balance(self, sess):
        '''
        :param sess: 登录状态
        :return: 获取签到奖励和余额
        '''
        BalanceHtml = sess.get('http://www.v2ex.com/balance',headers={'Referer': 'http://www.v2ex.com/balance'}).text
        dailygold = search('\">(\d+.+的每日.+)</span', BalanceHtml).group(1)
        print dailygold
        with open('v2exLog.txt', 'a') as log:
            log.write(dailygold)
            log.write('*'*30)
            print '写入日志成功...'

    def daily(self, sess):
        DailyUrl = 'http://www.v2ex.com/mission/daily'
        html = sess.get(DailyUrl, headers=self.headers)
        MSoup = BeautifulSoup(html.text, 'lxml')
        u = MSoup.find('input', {"type": 'button'})['onclick'].split('\'')[1]
        RealUrl = 'http://www.v2ex.com' + u
        res = sess.get(RealUrl, headers={'Referer': 'http://www.v2ex.com/mission/daily'})
        if res.text.find(u'已成功领取每日登录奖励') > 0:
            print '已成功领取每日登录奖励...'
            self.balance(sess)
        else:
            print '已经领取过每日登录奖励...'

if __name__ == '__main__':
    usrname = raw_input('用户名: ')
    usrpswd = raw_input('密码: ')
    while True:
        foo = v2ex(usrname, usrpswd)
        sess = foo.login()
        if sess[1] is True:
            foo.daily(sess[0])
            sleep(86400)
        else:
            break

<commit_msg>update<commit_after>#!/usr/bin/env python
# coding:utf-8
import requests
from re import search
from bs4 import BeautifulSoup
from time import sleep

class v2ex(object):
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
        'Origin': 'http://www.v2ex.com',
        'Referer': 'http://www.v2ex.com/signin',
        'Host': 'www.v2ex.com'
    }

    def __init__(self, usrname, usrpswd):
        self.usrname = usrname
        self.usrpswd = usrpswd

    def login(self):
        sess = requests.Session()
        LoginHtml = sess.get('http://www.v2ex.com/signin', headers=self.headers)
        LoginSoup = BeautifulSoup(LoginHtml.text, 'lxml')
        usrnamecode = LoginSoup.find('input', {'class': 'sl'})['name']
        usrpswdcode = LoginSoup.find('input', {'type': 'password'})['name']
        once = LoginSoup.find('input', {'name': 'once'})['value']
        from_data = {
            usrnamecode: self.usrname,
            usrpswdcode: self.usrpswd,
            'once': once,
            'next': '/'
            }
        sess.post('http://www.v2ex.com/signin', from_data, headers=self.headers)
        sethtml = sess.get('http://www.v2ex.com/settings', headers=self.headers)
        soup = BeautifulSoup(sethtml.text, 'lxml')
        email = soup.find('input', {'type': 'email'})['value']
        status = True if email else False
        print '登录成功！' if status else '登录失败！'
        return [sess, status]

    def balance(self, sess):
        '''
        :param sess: 登录状态
        :return: 获取签到奖励和余额
        '''
        BalanceHtml = sess.get('http://www.v2ex.com/balance',headers={'Referer': 'http://www.v2ex.com/balance'}).text
        soup = BeautifulSoup(BalanceHtml, 'lxml')
        dailygold = soup.find('td', {'class': 'd', 'style': 'border-right: none;'}).text
        return dailygold

    def writelog(self, des):
        with open(self.usrname+'v2exLog.txt', 'a') as log:
            log.write(des.encode('gbk')+'\n')
            log.write('*'*30)
            print '写入日志成功...'

    def daily(self, sess):
        DailyUrl = 'http://www.v2ex.com/mission/daily'
        html = sess.get(DailyUrl, headers=self.headers)
        MSoup = BeautifulSoup(html.text, 'lxml')
        u = MSoup.find('input', {"type": 'button'})['onclick'].split('\'')[1]
        RealUrl = 'http://www.v2ex.com' + u
        res = sess.get(RealUrl, headers={'Referer': 'http://www.v2ex.com/mission/daily'})
        des = self.balance(sess)
        print des
        if res.text.find(u'已成功领取每日登录奖励') > 0:
            print '已成功领取每日登录奖励...'
            self.writelog(des)
        else:
            print '已经领取过每日登录奖励...'

if __name__ == '__main__':
    usrname = raw_input('用户名: ')
    usrpswd = raw_input('密码: ')
    while True:
        foo = v2ex(usrname, usrpswd)
        sess = foo.login()
        if sess[1] is True:
            foo.daily(sess[0])
            break;
        else:
            break

<|endoftext|>


<commit_before>import warnings
from sys import version_info

import numpy as np
from scipy import interpolate
import scipy.sparse as sp

from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal

from nose import SkipTest
from nose.tools import assert_true
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less, assert_greater

from sklearn.linear_model.coordinate_descent import Lasso, \
    LassoCV, ElasticNet, ElasticNetCV
from sklearn.datasets.samples_generator import make_regression

def test_sparse_coef():
    """ Check that the sparse_coef propery works """
    clf = ElasticNet()
    clf.coef_ = [1, 2, 3]

    assert_true(sp.isspmatrix(clf.sparse_coef_))
    assert_equal(clf.sparse_coef_.todense().tolist()[0], clf.coef_)

def test_normalize_option():
    """ Check that the normalize option in enet works """
    X = sp.csc_matrix([[-1], [0], [1]])
    y = [-1, 0, 1]
    clf_dense = ElasticNet(fit_intercept=True, normalize=True)
    clf_sparse = ElasticNet(fit_intercept=True, normalize=True)
    clf_dense.fit(X, y)
    X = sp.csc_matrix(X)
    clf_sparse.fit(X, y)
    assert_almost_equal(clf_dense.dual_gap_, 0)
    assert_array_almost_equal(clf_dense.coef_, clf_sparse.coef_)

def test_lasso_zero():
    """Check that the sparse lasso can handle zero data without crashing"""
    X = sp.csc_matrix((3, 1))
    y = [0, 0, 0]
    T = np.array([[1], [2], [3]])
    clf = Lasso().fit(X, y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0])
    assert_array_almost_equal(pred, [0, 0, 0])
    assert_almost_equal(clf.dual_gap_,  0)

def test_enet_toy_list_input():
    """Test ElasticNet for various parameters of alpha and rho with list X"""

    X = np.array([[-1], [0], [1]])
    X = sp.csc_matrix(X)
    Y = [-1, 0, 1]       # just a straight line
    T = np.array([[2], [3], [4]])  # test sample

    # this should be the same as unregularized least squares
    clf = ElasticNet(alpha=0, rho=1.0)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [1])
    assert_array_almost_equal(pred, [2, 3, 4])
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.50819], decimal=3)
    assert_array_almost_equal(pred, [1.0163,  1.5245,  2.0327], decimal=3)
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.5)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.45454], 3)
    assert_array_almost_equal(pred, [0.9090,  1.3636,  1.8181], 3)
    assert_almost_equal(clf.dual_gap_, 0)

def test_enet_toy_explicit_sparse_input():
    """Test ElasticNet for various parameters of alpha and rho with sparse X"""

    # training samples
    X = sp.lil_matrix((3, 1))
    X[0, 0] = -1
    # X[1, 0] = 0
    X[2, 0] = 1
    Y = [-1, 0, 1]       # just a straight line (the identity function)

    # test samples
    T = sp.lil_matrix((3, 1))
    T[0, 0] = 2
    T[1, 0] = 3
    T[2, 0] = 4

    # this should be the same as lasso
    clf = ElasticNet(alpha=0, rho=1.0)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [1])
    assert_array_almost_equal(pred, [2, 3, 4])
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.50819], decimal=3)
    assert_array_almost_equal(pred, [1.0163,  1.5245,  2.0327], decimal=3)
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.5)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.45454], 3)
    assert_array_almost_equal(pred, [0.9090,  1.3636,  1.8181], 3)
    assert_almost_equal(clf.dual_gap_, 0)

def make_sparse_data(n_samples, n_features, n_informative, seed=42,
                     positive=False):
    random_state = np.random.RandomState(seed)

    # build an ill-posed linear regression problem with many noisy features and
    # comparatively few samples

    # generate a ground truth model
    w = random_state.randn(n_features)
    w[n_informative:] = 0.0  # only the top features are impacting the model
    if positive:
        w = np.abs(w)

    X = random_state.randn(n_samples, n_features)
    rnd = random_state.uniform(size=(n_samples, n_features))
    X[rnd > 0.5] = 0.0  # 50% of zeros in input signal

    # generate training ground truth labels
    y = np.dot(X, w)
    X = sp.csc_matrix(X)
    return X, y

def _test_sparse_enet_not_as_toy_dataset(alpha, fit_intercept, positive):
    n_samples, n_features, max_iter = 100, 100, 1000
    n_informative = 10

    X, y = make_sparse_data(n_samples, n_features, n_informative,
                            positive=positive)

    X_train, X_test = X[n_samples / 2:], X[:n_samples / 2]
    y_train, y_test = y[n_samples / 2:], y[:n_samples / 2]

    s_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept,
                       max_iter=max_iter, tol=1e-7, positive=positive,
                       warm_start=True)
    s_clf.fit(X_train, y_train)

    assert_almost_equal(s_clf.dual_gap_, 0, 4)
    assert_greater(s_clf.score(X_test, y_test), 0.85)

    # check the convergence is the same as the dense version
    d_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept,
                      max_iter=max_iter, tol=1e-7, positive=positive,
                      warm_start=True)
    d_clf.fit(X_train, y_train)

    assert_almost_equal(d_clf.dual_gap_, 0, 4)
    assert_greater(d_clf.score(X_test, y_test), 0.85)

    assert_almost_equal(s_clf.coef_, d_clf.coef_, 5)
    assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5)

    # check that the coefs are sparse
    assert_less(np.sum(s_clf.coef_ != 0.0), 2 * n_informative)

    # check that warm restart leads to the same result with
    # sparse and dense versions

    rng = np.random.RandomState(seed=0)
    coef_init = rng.randn(n_features)

    d_clf.fit(X_train, y_train, coef_init=coef_init)
    s_clf.fit(X_train, y_train, coef_init=coef_init)

    assert_almost_equal(s_clf.coef_, d_clf.coef_, 5)
    assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5)

def test_sparse_enet_not_as_toy_dataset():
    _test_sparse_enet_not_as_toy_dataset(alpha=0.1, fit_intercept=False,
                                         positive=False)
    _test_sparse_enet_not_as_toy_dataset(alpha=0.1, fit_intercept=True,
                                         positive=False)
    _test_sparse_enet_not_as_toy_dataset(alpha=1e-3, fit_intercept=False,
                                         positive=True)
    _test_sparse_enet_not_as_toy_dataset(alpha=1e-3, fit_intercept=True,
                                         positive=True)

def test_sparse_lasso_not_as_toy_dataset():
    n_samples, n_features, max_iter = 100, 100, 1000
    n_informative = 10

    X, y = make_sparse_data(n_samples, n_features, n_informative)

    X_train, X_test = X[n_samples / 2:], X[:n_samples / 2]
    y_train, y_test = y[n_samples / 2:], y[:n_samples / 2]

    s_clf = Lasso(alpha=0.1, fit_intercept=False,
                        max_iter=max_iter, tol=1e-7)
    s_clf.fit(X_train, y_train)
    assert_almost_equal(s_clf.dual_gap_, 0, 4)
    assert_greater(s_clf.score(X_test, y_test), 0.85)

    # check the convergence is the same as the dense version
    d_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter,
            tol=1e-7)
    d_clf.fit(X_train, y_train)
    assert_almost_equal(d_clf.dual_gap_, 0, 4)
    assert_greater(d_clf.score(X_test, y_test), 0.85)

    # check that the coefs are sparse
    assert_equal(np.sum(s_clf.coef_ != 0.0), n_informative)<commit_msg>remove unused imports<commit_after>import numpy as np
import scipy.sparse as sp

from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal

from nose.tools import assert_true
from sklearn.utils.testing import assert_less, assert_greater

from sklearn.linear_model.coordinate_descent import Lasso, ElasticNet

def test_sparse_coef():
    """ Check that the sparse_coef propery works """
    clf = ElasticNet()
    clf.coef_ = [1, 2, 3]

    assert_true(sp.isspmatrix(clf.sparse_coef_))
    assert_equal(clf.sparse_coef_.todense().tolist()[0], clf.coef_)

def test_normalize_option():
    """ Check that the normalize option in enet works """
    X = sp.csc_matrix([[-1], [0], [1]])
    y = [-1, 0, 1]
    clf_dense = ElasticNet(fit_intercept=True, normalize=True)
    clf_sparse = ElasticNet(fit_intercept=True, normalize=True)
    clf_dense.fit(X, y)
    X = sp.csc_matrix(X)
    clf_sparse.fit(X, y)
    assert_almost_equal(clf_dense.dual_gap_, 0)
    assert_array_almost_equal(clf_dense.coef_, clf_sparse.coef_)

def test_lasso_zero():
    """Check that the sparse lasso can handle zero data without crashing"""
    X = sp.csc_matrix((3, 1))
    y = [0, 0, 0]
    T = np.array([[1], [2], [3]])
    clf = Lasso().fit(X, y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0])
    assert_array_almost_equal(pred, [0, 0, 0])
    assert_almost_equal(clf.dual_gap_,  0)

def test_enet_toy_list_input():
    """Test ElasticNet for various parameters of alpha and rho with list X"""

    X = np.array([[-1], [0], [1]])
    X = sp.csc_matrix(X)
    Y = [-1, 0, 1]       # just a straight line
    T = np.array([[2], [3], [4]])  # test sample

    # this should be the same as unregularized least squares
    clf = ElasticNet(alpha=0, rho=1.0)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [1])
    assert_array_almost_equal(pred, [2, 3, 4])
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.50819], decimal=3)
    assert_array_almost_equal(pred, [1.0163,  1.5245,  2.0327], decimal=3)
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.5)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.45454], 3)
    assert_array_almost_equal(pred, [0.9090,  1.3636,  1.8181], 3)
    assert_almost_equal(clf.dual_gap_, 0)

def test_enet_toy_explicit_sparse_input():
    """Test ElasticNet for various parameters of alpha and rho with sparse X"""

    # training samples
    X = sp.lil_matrix((3, 1))
    X[0, 0] = -1
    # X[1, 0] = 0
    X[2, 0] = 1
    Y = [-1, 0, 1]       # just a straight line (the identity function)

    # test samples
    T = sp.lil_matrix((3, 1))
    T[0, 0] = 2
    T[1, 0] = 3
    T[2, 0] = 4

    # this should be the same as lasso
    clf = ElasticNet(alpha=0, rho=1.0)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [1])
    assert_array_almost_equal(pred, [2, 3, 4])
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.3, max_iter=1000)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.50819], decimal=3)
    assert_array_almost_equal(pred, [1.0163,  1.5245,  2.0327], decimal=3)
    assert_almost_equal(clf.dual_gap_, 0)

    clf = ElasticNet(alpha=0.5, rho=0.5)
    clf.fit(X, Y)
    pred = clf.predict(T)
    assert_array_almost_equal(clf.coef_, [0.45454], 3)
    assert_array_almost_equal(pred, [0.9090,  1.3636,  1.8181], 3)
    assert_almost_equal(clf.dual_gap_, 0)

def make_sparse_data(n_samples, n_features, n_informative, seed=42,
                     positive=False):
    random_state = np.random.RandomState(seed)

    # build an ill-posed linear regression problem with many noisy features and
    # comparatively few samples

    # generate a ground truth model
    w = random_state.randn(n_features)
    w[n_informative:] = 0.0  # only the top features are impacting the model
    if positive:
        w = np.abs(w)

    X = random_state.randn(n_samples, n_features)
    rnd = random_state.uniform(size=(n_samples, n_features))
    X[rnd > 0.5] = 0.0  # 50% of zeros in input signal

    # generate training ground truth labels
    y = np.dot(X, w)
    X = sp.csc_matrix(X)
    return X, y

def _test_sparse_enet_not_as_toy_dataset(alpha, fit_intercept, positive):
    n_samples, n_features, max_iter = 100, 100, 1000
    n_informative = 10

    X, y = make_sparse_data(n_samples, n_features, n_informative,
                            positive=positive)

    X_train, X_test = X[n_samples / 2:], X[:n_samples / 2]
    y_train, y_test = y[n_samples / 2:], y[:n_samples / 2]

    s_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept,
                       max_iter=max_iter, tol=1e-7, positive=positive,
                       warm_start=True)
    s_clf.fit(X_train, y_train)

    assert_almost_equal(s_clf.dual_gap_, 0, 4)
    assert_greater(s_clf.score(X_test, y_test), 0.85)

    # check the convergence is the same as the dense version
    d_clf = ElasticNet(alpha=alpha, rho=0.8, fit_intercept=fit_intercept,
                      max_iter=max_iter, tol=1e-7, positive=positive,
                      warm_start=True)
    d_clf.fit(X_train, y_train)

    assert_almost_equal(d_clf.dual_gap_, 0, 4)
    assert_greater(d_clf.score(X_test, y_test), 0.85)

    assert_almost_equal(s_clf.coef_, d_clf.coef_, 5)
    assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5)

    # check that the coefs are sparse
    assert_less(np.sum(s_clf.coef_ != 0.0), 2 * n_informative)

    # check that warm restart leads to the same result with
    # sparse and dense versions

    rng = np.random.RandomState(seed=0)
    coef_init = rng.randn(n_features)

    d_clf.fit(X_train, y_train, coef_init=coef_init)
    s_clf.fit(X_train, y_train, coef_init=coef_init)

    assert_almost_equal(s_clf.coef_, d_clf.coef_, 5)
    assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5)

def test_sparse_enet_not_as_toy_dataset():
    _test_sparse_enet_not_as_toy_dataset(alpha=0.1, fit_intercept=False,
                                         positive=False)
    _test_sparse_enet_not_as_toy_dataset(alpha=0.1, fit_intercept=True,
                                         positive=False)
    _test_sparse_enet_not_as_toy_dataset(alpha=1e-3, fit_intercept=False,
                                         positive=True)
    _test_sparse_enet_not_as_toy_dataset(alpha=1e-3, fit_intercept=True,
                                         positive=True)

def test_sparse_lasso_not_as_toy_dataset():
    n_samples, n_features, max_iter = 100, 100, 1000
    n_informative = 10

    X, y = make_sparse_data(n_samples, n_features, n_informative)

    X_train, X_test = X[n_samples / 2:], X[:n_samples / 2]
    y_train, y_test = y[n_samples / 2:], y[:n_samples / 2]

    s_clf = Lasso(alpha=0.1, fit_intercept=False,
                        max_iter=max_iter, tol=1e-7)
    s_clf.fit(X_train, y_train)
    assert_almost_equal(s_clf.dual_gap_, 0, 4)
    assert_greater(s_clf.score(X_test, y_test), 0.85)

    # check the convergence is the same as the dense version
    d_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter,
            tol=1e-7)
    d_clf.fit(X_train, y_train)
    assert_almost_equal(d_clf.dual_gap_, 0, 4)
    assert_greater(d_clf.score(X_test, y_test), 0.85)

    # check that the coefs are sparse
    assert_equal(np.sum(s_clf.coef_ != 0.0), n_informative)<|endoftext|>


<commit_before>#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Tests for javaobj

See:
http://download.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html

:authors: Volodymyr Buell, Thomas Calmant
:license: Apache License 2.0
:version: 0.2.3
:status: Alpha

..

    Copyright 2016 Thomas Calmant

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

# Standard library
import logging
import subprocess
import unittest
import os
import sys

# Prepare Python path to import javaobj
sys.path.insert(0, os.path.abspath(os.path.dirname(os.getcwd())))

# Local
import javaobj

# ------------------------------------------------------------------------------

# Documentation strings format
__docformat__ = "restructuredtext en"

_logger = logging.getLogger("javaobj.tests")

# ------------------------------------------------------------------------------

class TestJavaobj(unittest.TestCase):
    """
    Full test suite for javaobj
    """
    @classmethod
    def setUpClass(cls):
        """
        Calls Maven to compile & run Java classes that will generate serialized
        data
        """
        # Compute the java directory
        java_dir = os.path.join(os.path.dirname(__file__), 'java')

        # Run Maven and go back to the working folder
        cwd = os.getcwd()
        os.chdir(java_dir)
        subprocess.call('mvn test', shell=True)
        os.chdir(cwd)

    def read_file(self, filename, stream=False):
        """
        Reads the content of the given file in binary mode

        :param filename: Name of the file to read
        :param stream: If True, return the file stream
        :return: File content or stream
        """
        for subfolder in ('java', ''):
            found_file = os.path.join(
                os.path.dirname(__file__), subfolder, filename)
            if os.path.exists(found_file):
                break
        else:
            raise IOError("File not found: {0}".format(filename))

        if stream:
            return open(found_file, "rb")
        else:
            with open(found_file, 'rb') as filep:
                return filep.read()

    def _try_marshalling(self, original_stream, original_object):
        """
        Tries to marshall an object and compares it to the original stream
        """
        marshalled_stream = javaobj.dumps(original_object)
        # Reloading the new dump allows to compare the decoding sequence
        try:
            javaobj.loads(marshalled_stream)
            self.assertEqual(original_stream, marshalled_stream)
        except:
            print("-" * 80)
            print("=" * 30, "Original", "=" * 30)
            print(javaobj.JavaObjectUnmarshaller._create_hexdump(
                original_stream))
            print("*" * 30, "Marshalled", "*" * 30)
            print(javaobj.JavaObjectUnmarshaller._create_hexdump(
                marshalled_stream))
            print("-" * 80)
            raise

    def test_char_rw(self):
        """
        Reads testChar.ser and checks the serialization process
        """
        jobj = self.read_file("testChar.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read char object: %s", pobj)
        self.assertEqual(pobj, '\x00C')
        self._try_marshalling(jobj, pobj)

    def test_chars_rw(self):
        """
        Reads testChars.ser and checks the serialization process
        """
        # Expected string as a UTF-16 string
        expected = "python-javaobj".encode("utf-16-be").decode("latin1")

        jobj = self.read_file("testChars.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read char objects: %s", pobj)
        self.assertEqual(pobj, expected)
        self._try_marshalling(jobj, pobj)

    def test_double_rw(self):
        """
        Reads testDouble.ser and checks the serialization process
        """
        jobj = self.read_file("testDouble.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read double object: %s", pobj)

        self.assertEqual(pobj, '\x7f\xef\xff\xff\xff\xff\xff\xff')
        self._try_marshalling(jobj, pobj)

    def test_bytes_rw(self):
        """
        Reads testBytes.ser and checks the serialization process
        """
        jobj = self.read_file("testBytes.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read bytes: %s", pobj)

        self.assertEqual(pobj, 'HelloWorld')
        self._try_marshalling(jobj, pobj)

    def test_class_with_byte_array_rw(self):
        jobj = self.read_file("testClassWithByteArray.ser")
        pobj = javaobj.loads(jobj)

        # j8spencer (Google, LLC) 2018-01-16:  It seems specific support for
        # byte arrays was added, but is a little out-of-step with the other
        # types in terms of style.  This UT was broken, since the "myArray"
        # member has the array stored as a tuple of ints (not a byte string)
        # in memeber called '_data.'  I've updated to pass the UTs.
        self.assertEqual(pobj.myArray._data, (1, 3, 7, 11))
        self._try_marshalling(jobj, pobj)

    def test_boolean(self):
        """
        Reads testBoolean.ser and checks the serialization process
        """
        jobj = self.read_file("testBoolean.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read boolean object: %s", pobj)

        self.assertEqual(pobj, chr(0))
        self._try_marshalling(jobj, pobj)

    def test_byte(self):
        """
        Reads testByte.ser

        The result from javaobj is a single-character string.
        """
        jobj = self.read_file("testByte.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read Byte: %r", pobj)

        self.assertEqual(pobj, chr(127))
        self._try_marshalling(jobj, pobj)

    def test_fields(self):
        """
        Reads a serialized object and checks its fields
        """
        jobj = self.read_file("test_readFields.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read object: %s", pobj)

        self.assertEqual(pobj.aField1, 'Gabba')
        self.assertEqual(pobj.aField2, None)

        classdesc = pobj.get_class()
        self.assertTrue(classdesc)
        self.assertEqual(classdesc.serialVersionUID, 0x7F0941F5)
        self.assertEqual(classdesc.name, "OneTest$SerializableTestHelper")

        _logger.debug("Class..........: %s", classdesc)
        _logger.debug(".. Flags.......: %s", classdesc.flags)
        _logger.debug(".. Fields Names: %s", classdesc.fields_names)
        _logger.debug(".. Fields Types: %s", classdesc.fields_types)

        self.assertEqual(len(classdesc.fields_names), 3)
        self._try_marshalling(jobj, pobj)

    def test_class(self):
        """
        Reads the serialized String class
        """
        jobj = self.read_file("testClass.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read object: %s", pobj)
        self.assertEqual(pobj.name, 'java.lang.String')
        self._try_marshalling(jobj, pobj)

    # def test_swing_object(self):
    #     """
    #     Reads a serialized Swing component
    #     """
    #     jobj = self.read_file("testSwingObject.ser")
    #     pobj = javaobj.loads(jobj)
    #     _logger.debug("Read object: %s", pobj)
    #
    #     classdesc = pobj.get_class()
    #     _logger.debug("Class..........: %s", classdesc)
    #     _logger.debug(".. Fields Names: %s", classdesc.fields_names)
    #     _logger.debug(".. Fields Types: %s", classdesc.fields_types)

    def test_super(self):
        jobj = self.read_file("objSuper.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        self.assertEqual(pobj.childString, "Child!!")
        self.assertEqual(pobj.bool, True)
        self.assertEqual(pobj.integer, -1)
        self.assertEqual(pobj.superString, "Super!!")

        self._try_marshalling(jobj, pobj)

    def test_arrays(self):
        jobj = self.read_file("objArrays.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        # public String[] stringArr = {"1", "2", "3"};
        # public int[] integerArr = {1,2,3};
        # public boolean[] boolArr = {true, false, true};
        # public TestConcrete[] concreteArr = {new TestConcrete(),
        #                                      new TestConcrete()};

        _logger.debug(pobj.stringArr)
        _logger.debug(pobj.integerArr)
        _logger.debug(pobj.boolArr)
        _logger.debug(pobj.concreteArr)

        self._try_marshalling(jobj, pobj)

    def test_char_array(self):
        jobj = self.read_file("testCharArray.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)
        self.assertEqual(pobj, [u'\u0000', u'\ud800', u'\u0001', u'\udc00', u'\u0002', u'\uffff', u'\u0003'])
        self._try_marshalling(jobj, pobj)

    def test_enums(self):
        jobj = self.read_file("objEnums.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        self.assertEqual(classdesc.name, "ClassWithEnum")
        self.assertEqual(pobj.color.classdesc.name, "Color")
        self.assertEqual(pobj.color.constant, "GREEN")

        for color, intended in zip(pobj.colors, ("GREEN", "BLUE", "RED")):
            self.assertEqual(color.classdesc.name, "Color")
            self.assertEqual(color.constant, intended)

            # self._try_marshalling(jobj, pobj)

    # def test_exception(self):
    #     jobj = self.read_file("objException.ser")
    #     pobj = javaobj.loads(jobj)
    #     _logger.debug(pobj)
    #
    #     classdesc = pobj.get_class()
    #     _logger.debug(classdesc)
    #     _logger.debug(classdesc.fields_names)
    #     _logger.debug(classdesc.fields_types)
    #
    #     # TODO: add some tests
    #     self.assertEqual(classdesc.name, "MyExceptionWhenDumping")

    def test_sun_example(self):
       marshaller = javaobj.JavaObjectUnmarshaller(
           self.read_file("sunExample.ser", stream=True))
       pobj = marshaller.readObject()

       self.assertEqual(pobj.value, 17)
       self.assertTrue(pobj.next)

       pobj = marshaller.readObject()

       self.assertEqual(pobj.value, 19)
       self.assertFalse(pobj.next)

    def test_collections(self):
        jobj = self.read_file("objCollections.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        _logger.debug("arrayList: %s", pobj.arrayList)
        self.assertTrue(isinstance(pobj.arrayList, list))
        _logger.debug("hashMap: %s", pobj.hashMap)
        self.assertTrue(isinstance(pobj.hashMap, dict))
        _logger.debug("linkedList: %s", pobj.linkedList)
        self.assertTrue(isinstance(pobj.linkedList, list))

        # FIXME: referencing problems with the collection class
        # self._try_marshalling(jobj, pobj)

    def test_jceks_issue_5(self):
        jobj = self.read_file("jceks_issue_5.ser")
        pobj = javaobj.loads(jobj)
        _logger.info(pobj)
        # self._try_marshalling(jobj, pobj)

# ------------------------------------------------------------------------------

if __name__ == '__main__':
    # Setup logging
    logging.basicConfig(level=logging.INFO)

    # Run tests
    unittest.main()
<commit_msg>Disabled the test_char_array<commit_after>#!/usr/bin/python
# -- Content-Encoding: utf-8 --
"""
Tests for javaobj

See:
http://download.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html

:authors: Volodymyr Buell, Thomas Calmant
:license: Apache License 2.0
:version: 0.2.3
:status: Alpha

..

    Copyright 2016 Thomas Calmant

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

# Standard library
import logging
import subprocess
import unittest
import os
import sys

# Prepare Python path to import javaobj
sys.path.insert(0, os.path.abspath(os.path.dirname(os.getcwd())))

# Local
import javaobj

# ------------------------------------------------------------------------------

# Documentation strings format
__docformat__ = "restructuredtext en"

_logger = logging.getLogger("javaobj.tests")

# ------------------------------------------------------------------------------

class TestJavaobj(unittest.TestCase):
    """
    Full test suite for javaobj
    """
    @classmethod
    def setUpClass(cls):
        """
        Calls Maven to compile & run Java classes that will generate serialized
        data
        """
        # Compute the java directory
        java_dir = os.path.join(os.path.dirname(__file__), 'java')

        # Run Maven and go back to the working folder
        cwd = os.getcwd()
        os.chdir(java_dir)
        subprocess.call('mvn test', shell=True)
        os.chdir(cwd)

    def read_file(self, filename, stream=False):
        """
        Reads the content of the given file in binary mode

        :param filename: Name of the file to read
        :param stream: If True, return the file stream
        :return: File content or stream
        """
        for subfolder in ('java', ''):
            found_file = os.path.join(
                os.path.dirname(__file__), subfolder, filename)
            if os.path.exists(found_file):
                break
        else:
            raise IOError("File not found: {0}".format(filename))

        if stream:
            return open(found_file, "rb")
        else:
            with open(found_file, 'rb') as filep:
                return filep.read()

    def _try_marshalling(self, original_stream, original_object):
        """
        Tries to marshall an object and compares it to the original stream
        """
        marshalled_stream = javaobj.dumps(original_object)
        # Reloading the new dump allows to compare the decoding sequence
        try:
            javaobj.loads(marshalled_stream)
            self.assertEqual(original_stream, marshalled_stream)
        except:
            print("-" * 80)
            print("=" * 30, "Original", "=" * 30)
            print(javaobj.JavaObjectUnmarshaller._create_hexdump(
                original_stream))
            print("*" * 30, "Marshalled", "*" * 30)
            print(javaobj.JavaObjectUnmarshaller._create_hexdump(
                marshalled_stream))
            print("-" * 80)
            raise

    def test_char_rw(self):
        """
        Reads testChar.ser and checks the serialization process
        """
        jobj = self.read_file("testChar.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read char object: %s", pobj)
        self.assertEqual(pobj, '\x00C')
        self._try_marshalling(jobj, pobj)

    def test_chars_rw(self):
        """
        Reads testChars.ser and checks the serialization process
        """
        # Expected string as a UTF-16 string
        expected = "python-javaobj".encode("utf-16-be").decode("latin1")

        jobj = self.read_file("testChars.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read char objects: %s", pobj)
        self.assertEqual(pobj, expected)
        self._try_marshalling(jobj, pobj)

    def test_double_rw(self):
        """
        Reads testDouble.ser and checks the serialization process
        """
        jobj = self.read_file("testDouble.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read double object: %s", pobj)

        self.assertEqual(pobj, '\x7f\xef\xff\xff\xff\xff\xff\xff')
        self._try_marshalling(jobj, pobj)

    def test_bytes_rw(self):
        """
        Reads testBytes.ser and checks the serialization process
        """
        jobj = self.read_file("testBytes.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read bytes: %s", pobj)

        self.assertEqual(pobj, 'HelloWorld')
        self._try_marshalling(jobj, pobj)

    def test_class_with_byte_array_rw(self):
        jobj = self.read_file("testClassWithByteArray.ser")
        pobj = javaobj.loads(jobj)

        # j8spencer (Google, LLC) 2018-01-16:  It seems specific support for
        # byte arrays was added, but is a little out-of-step with the other
        # types in terms of style.  This UT was broken, since the "myArray"
        # member has the array stored as a tuple of ints (not a byte string)
        # in memeber called '_data.'  I've updated to pass the UTs.
        self.assertEqual(pobj.myArray._data, (1, 3, 7, 11))
        self._try_marshalling(jobj, pobj)

    def test_boolean(self):
        """
        Reads testBoolean.ser and checks the serialization process
        """
        jobj = self.read_file("testBoolean.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read boolean object: %s", pobj)

        self.assertEqual(pobj, chr(0))
        self._try_marshalling(jobj, pobj)

    def test_byte(self):
        """
        Reads testByte.ser

        The result from javaobj is a single-character string.
        """
        jobj = self.read_file("testByte.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read Byte: %r", pobj)

        self.assertEqual(pobj, chr(127))
        self._try_marshalling(jobj, pobj)

    def test_fields(self):
        """
        Reads a serialized object and checks its fields
        """
        jobj = self.read_file("test_readFields.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read object: %s", pobj)

        self.assertEqual(pobj.aField1, 'Gabba')
        self.assertEqual(pobj.aField2, None)

        classdesc = pobj.get_class()
        self.assertTrue(classdesc)
        self.assertEqual(classdesc.serialVersionUID, 0x7F0941F5)
        self.assertEqual(classdesc.name, "OneTest$SerializableTestHelper")

        _logger.debug("Class..........: %s", classdesc)
        _logger.debug(".. Flags.......: %s", classdesc.flags)
        _logger.debug(".. Fields Names: %s", classdesc.fields_names)
        _logger.debug(".. Fields Types: %s", classdesc.fields_types)

        self.assertEqual(len(classdesc.fields_names), 3)
        self._try_marshalling(jobj, pobj)

    def test_class(self):
        """
        Reads the serialized String class
        """
        jobj = self.read_file("testClass.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug("Read object: %s", pobj)
        self.assertEqual(pobj.name, 'java.lang.String')
        self._try_marshalling(jobj, pobj)

    # def test_swing_object(self):
    #     """
    #     Reads a serialized Swing component
    #     """
    #     jobj = self.read_file("testSwingObject.ser")
    #     pobj = javaobj.loads(jobj)
    #     _logger.debug("Read object: %s", pobj)
    #
    #     classdesc = pobj.get_class()
    #     _logger.debug("Class..........: %s", classdesc)
    #     _logger.debug(".. Fields Names: %s", classdesc.fields_names)
    #     _logger.debug(".. Fields Types: %s", classdesc.fields_types)

    def test_super(self):
        jobj = self.read_file("objSuper.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        self.assertEqual(pobj.childString, "Child!!")
        self.assertEqual(pobj.bool, True)
        self.assertEqual(pobj.integer, -1)
        self.assertEqual(pobj.superString, "Super!!")

        self._try_marshalling(jobj, pobj)

    def test_arrays(self):
        jobj = self.read_file("objArrays.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        # public String[] stringArr = {"1", "2", "3"};
        # public int[] integerArr = {1,2,3};
        # public boolean[] boolArr = {true, false, true};
        # public TestConcrete[] concreteArr = {new TestConcrete(),
        #                                      new TestConcrete()};

        _logger.debug(pobj.stringArr)
        _logger.debug(pobj.integerArr)
        _logger.debug(pobj.boolArr)
        _logger.debug(pobj.concreteArr)

        self._try_marshalling(jobj, pobj)

    def test_japan(self):
        # Japan.ser contains a string using wide characters: the name of the
        # state from Japan (according to wikipedia)
        jobj = self.read_file("testJapan.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)
        # Compare the UTF-8 encoded version of the name
        self.assertEqual(pobj, b"\xe6\x97\xa5\xe6\x9c\xac\xe5\x9b\xbd".decode("utf-8"))
        self._try_marshalling(jobj, pobj)

    # def test_char_array(self):
    #     jobj = self.read_file("testCharArray.ser")
    #     pobj = javaobj.loads(jobj)
    #     _logger.debug(pobj)
    #     self.assertEqual(pobj, [u'\u0000', u'\ud800', u'\u0001', u'\udc00', u'\u0002', u'\uffff', u'\u0003'])
    #     self._try_marshalling(jobj, pobj)

    def test_enums(self):
        jobj = self.read_file("objEnums.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        classdesc = pobj.get_class()
        _logger.debug(classdesc)
        _logger.debug(classdesc.fields_names)
        _logger.debug(classdesc.fields_types)

        self.assertEqual(classdesc.name, "ClassWithEnum")
        self.assertEqual(pobj.color.classdesc.name, "Color")
        self.assertEqual(pobj.color.constant, "GREEN")

        for color, intended in zip(pobj.colors, ("GREEN", "BLUE", "RED")):
            self.assertEqual(color.classdesc.name, "Color")
            self.assertEqual(color.constant, intended)

            # self._try_marshalling(jobj, pobj)

    # def test_exception(self):
    #     jobj = self.read_file("objException.ser")
    #     pobj = javaobj.loads(jobj)
    #     _logger.debug(pobj)
    #
    #     classdesc = pobj.get_class()
    #     _logger.debug(classdesc)
    #     _logger.debug(classdesc.fields_names)
    #     _logger.debug(classdesc.fields_types)
    #
    #     # TODO: add some tests
    #     self.assertEqual(classdesc.name, "MyExceptionWhenDumping")

    def test_sun_example(self):
       marshaller = javaobj.JavaObjectUnmarshaller(
           self.read_file("sunExample.ser", stream=True))
       pobj = marshaller.readObject()

       self.assertEqual(pobj.value, 17)
       self.assertTrue(pobj.next)

       pobj = marshaller.readObject()

       self.assertEqual(pobj.value, 19)
       self.assertFalse(pobj.next)

    def test_collections(self):
        jobj = self.read_file("objCollections.ser")
        pobj = javaobj.loads(jobj)
        _logger.debug(pobj)

        _logger.debug("arrayList: %s", pobj.arrayList)
        self.assertTrue(isinstance(pobj.arrayList, list))
        _logger.debug("hashMap: %s", pobj.hashMap)
        self.assertTrue(isinstance(pobj.hashMap, dict))
        _logger.debug("linkedList: %s", pobj.linkedList)
        self.assertTrue(isinstance(pobj.linkedList, list))

        # FIXME: referencing problems with the collection class
        # self._try_marshalling(jobj, pobj)

    def test_jceks_issue_5(self):
        jobj = self.read_file("jceks_issue_5.ser")
        pobj = javaobj.loads(jobj)
        _logger.info(pobj)
        # self._try_marshalling(jobj, pobj)

# ------------------------------------------------------------------------------

if __name__ == '__main__':
    # Setup logging
    logging.basicConfig(level=logging.INFO)

    # Run tests
    unittest.main()
<|endoftext|>