<commit_before>import tkinter as tk
import random
import numpy as np
import gamecfg

root = tk.Tk()
root.title("Tic Tac Toe")

# The main class
class Square(tk.Canvas):
	"""A Square is a canvas on which nought or cross can be played"""

	# Cross starts, board of length m, and the game has no result yet
	crossToPlay = True
	result = None
	m = gamecfg.n

	# moveList, squareDict and state are all representations of the board
	moveList = []
	squareDict = {}
	state = np.zeros((m, m))

	def __init__(self, name, master=None, size=None):
		super().__init__(master, width=size, height=size)
		self.bind("<Button-1>", self.tic)
		self.config(highlightbackground="Black")
		self.config(highlightthickness=1)

		self.symbol = None
		self.name = name
		self.topLeft = size * 0.15
		self.bottomRight = size * 0.85
		Square.squareDict[self.name] = self

	def draw(self):
		"""This will draw a nought or cross on itself,
		depending on who is to play."""
		if not self.symbol and not self.result:
			tl = self.topLeft
			br = self.bottomRight
			if Square.crossToPlay:
				self.create_line(tl, tl, br, br)
				self.create_line(tl, br, br, tl)
				self.symbol = 'X'
				Square.state[self.name] = 1
			else:
				self.create_oval(tl, tl, br, br)
				self.symbol = 'O'
				Square.state[self.name] = Square.m + 1
			Square.crossToPlay = not Square.crossToPlay
			Square.moveList.append(self)
			Square.print()
			winCheck(Square.state)
			computerMove()

	def tic(self, event):
		""""A tic is a player clicking on a square"""
		self.draw()

	def tac(self):
		"""A tac is the computer playing"""
		self.draw()

	def clear(self):
		""""This will clear the selected Square."""
		if self.symbol:
			self.delete("all")
			self.symbol = None
			Square.result = None
			Square.crossToPlay = not Square.crossToPlay
			Square.print()
			Square.state[self.name] = 0

	@classmethod
	def undo(cls):
		cls.moveList.pop().clear()

	@classmethod
	def print(cls):
		print('Moves:', *[square.name for square in cls.moveList])

# Creating the board, 600 x 600 pixels, n squares across
m = gamecfg.n
size = 600 // m
squares = [(rank, file) for rank in range(m) for file in range(m)]

for (rank, file) in squares:
	square = Square((rank, file), master=root, size=size)
	square.grid(row=rank, column=file)

def clearAll():
	while Square.moveList:
		Square.moveList.pop().clear()
	computerMove()

# Creating File Menu
menu = tk.Menu(root)
root.config(menu=menu)

fileMenu = tk.Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
# Undo calls the clear function on the most recently played square.
fileMenu.add_command(label="Undo", command=lambda: Square.moveList.pop().clear())
fileMenu.add_command(label="State", command=lambda: print(Square.state))
fileMenu.add_command(label="Result", command=lambda: print(Square.result))
fileMenu.add_command(label="Restart", command=lambda: clearAll())

def winCheck(state):
	# Sums which correspond to a line across a column
	winNums = list(state.sum(axis=0))
	# Sums which correspond to a line across a row
	winNums.extend(list(state.sum(axis=1)))
	# Sums which correspond to a line across the main diagonal
	winNums.append(state.trace())
	# Sums which correspond to a line across the off diagonal
	winNums.append(np.flipud(state).trace())

	# Bit dodgy, only set the result if state given matches the true state
	if np.array_equal(state, Square.state):
		if Square.m in winNums:
			print("Victory for X!")
			Square.result = 'X'
		elif (Square.m**2 + Square.m) in winNums:
			print("Victory for O!")
			Square.result = 'O'
		elif np.count_nonzero(state) == Square.m**2:
			print("It's a draw!")
			Square.result = 'D'

# This function is called safely anytime it might be the computer's turn
def computerMove():
	# Decide whether or not the computer is to play
	if gamecfg.engineIsCross == Square.crossToPlay and not Square.result:
		# Use Square.state to determine the legal moves
		gameState = Square.state.copy()
		moveChoices = []
		it = np.nditer(gameState, flags=['multi_index'])
		while not it.finished:
			if it[0] == 0:
				moveChoices.append(it.multi_index)
			it.iternext()
		print(moveChoices)
		Square.squareDict[random.choice(moveChoices)].tac()

computerMove()
root.mainloop()
<commit_msg>winCheck now returns a result, rather than set a class variable, which is done by Square.setResult<commit_after>import tkinter as tk
import random
import numpy as np
import gamecfg

root = tk.Tk()
root.title("Tic Tac Toe")

# The main class
class Square(tk.Canvas):
	"""A Square is a canvas on which nought or cross can be played"""

	# Cross starts, board of length m, and the game has no result yet
	crossToPlay = True
	result = None
	m = gamecfg.n

	# moveList, squareDict and state are all representations of the board
	moveList = []
	squareDict = {}
	state = np.zeros((m, m))

	def __init__(self, name, master=None, size=None):
		super().__init__(master, width=size, height=size)
		self.bind("<Button-1>", self.tic)
		self.config(highlightbackground="Black")
		self.config(highlightthickness=1)

		self.symbol = None
		self.name = name
		self.topLeft = size * 0.15
		self.bottomRight = size * 0.85
		Square.squareDict[self.name] = self

	def draw(self):
		"""This will draw a nought or cross on itself,
		depending on who is to play."""
		if not self.symbol and not self.result:
			tl = self.topLeft
			br = self.bottomRight
			if Square.crossToPlay:
				self.create_line(tl, tl, br, br)
				self.create_line(tl, br, br, tl)
				self.symbol = 'X'
				Square.state[self.name] = 1
			else:
				self.create_oval(tl, tl, br, br)
				self.symbol = 'O'
				Square.state[self.name] = Square.m + 1
			Square.crossToPlay = not Square.crossToPlay
			Square.moveList.append(self)
			Square.print()
			Square.setResult(winCheck(Square.state))
			computerMove()

	def tic(self, event):
		""""A tic is a player clicking on a square"""
		self.draw()

	def tac(self):
		"""A tac is the computer playing"""
		self.draw()

	def clear(self):
		""""This will clear the selected Square."""
		if self.symbol:
			self.delete("all")
			self.symbol = None
			Square.result = None
			Square.crossToPlay = not Square.crossToPlay
			Square.print()
			Square.state[self.name] = 0

	@classmethod
	def undo(cls):
		cls.moveList.pop().clear()

	@classmethod
	def print(cls):
		print('Moves:', *[square.name for square in cls.moveList])

	@classmethod
	def setResult(cls, result):
		if result:
			cls.result = result
			print("Result: {}".format(result))

# Creating the board, 600 x 600 pixels, n squares across
m = gamecfg.n
size = 600 // m
squares = [(rank, file) for rank in range(m) for file in range(m)]

for (rank, file) in squares:
	square = Square((rank, file), master=root, size=size)
	square.grid(row=rank, column=file)

def clearAll():
	while Square.moveList:
		Square.moveList.pop().clear()
	computerMove()

# Creating File Menu
menu = tk.Menu(root)
root.config(menu=menu)

fileMenu = tk.Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
# Undo calls the clear function on the most recently played square.
fileMenu.add_command(label="Undo", command=lambda: Square.moveList.pop().clear())
fileMenu.add_command(label="State", command=lambda: print(Square.state))
fileMenu.add_command(label="Result", command=lambda: print(Square.result))
fileMenu.add_command(label="Restart", command=lambda: clearAll())

def winCheck(state):
	# Sums which correspond to a line across a column
	winNums = list(state.sum(axis=0))
	# Sums which correspond to a line across a row
	winNums.extend(list(state.sum(axis=1)))
	# Sums which correspond to a line across the main diagonal
	winNums.append(state.trace())
	# Sums which correspond to a line across the off diagonal
	winNums.append(np.flipud(state).trace())

	if np.array_equal(state, Square.state):
		if Square.m in winNums:
			return 'X'
		elif (Square.m**2 + Square.m) in winNums:
			return 'O'
		elif np.count_nonzero(state) == Square.m**2:
			return 'D'
		else:
			return None

# This function is called safely anytime it might be the computer's turn
def computerMove():
	# Decide whether or not the computer is to play
	if gamecfg.engineIsCross == Square.crossToPlay and not Square.result:
		# Use Square.state to determine the legal moves
		gameState = Square.state.copy()
		moveChoices = []
		it = np.nditer(gameState, flags=['multi_index'])
		while not it.finished:
			if it[0] == 0:
				moveChoices.append(it.multi_index)
			it.iternext()
		print(moveChoices)
		Square.squareDict[random.choice(moveChoices)].tac()

computerMove()
root.mainloop()
<|endoftext|>


<commit_before>import array
from __pypy__.builders import UnicodeBuilder

from markupsafe import Markup

ESCAPED_CHARS_TABLE_SIZE = 256
ESCAPED_CHARS_DELTA_LEN = array.array("l", [0]) * ESCAPED_CHARS_TABLE_SIZE
ESCAPED_CHARS_REPL = [""] * ESCAPED_CHARS_TABLE_SIZE
for c, repl in [
    ('"', u"""),
    ("'", u"'"),
    ("&", u"&"),
    ("<", u"<"),
    (">", u">"),
]:
    ESCAPED_CHARS_DELTA_LEN[ord(c)] = len(repl)
    ESCAPED_CHARS_REPL[ord(c)] = repl

def escape(s):
    if hasattr(s, '__html__'):
        return s.__html__()
    s = unicode(s)

    i = 0
    delta = 0
    repls = 0
    # Find the total number of replacements, and their total distance.
    while i < len(s):
        c = ord(s[i])
        try:
            d = ESCAPED_CHARS_DELTA_LEN[c]
        except IndexError:
            pass
        else:
            delta += d
            repls += d != 0
        i += 1
        # Performance hack, can go away when PyPy's bridges are better
        # optimized
        del c
        del d
    # If there are no replacements just return the original string.
    if not repls:
        return s

    res = UnicodeBuilder(len(s) + delta)
    in_idx = 0
    # While there are still replcaements in the string.
    while repls > 0:
        repls -= 1
        next_escp = in_idx
        # Find the next escape
        while next_escp < len(s):
            if (ord(s[next_escp]) < len(ESCAPED_CHARS_DELTA_LEN) and
                ESCAPED_CHARS_DELTA_LEN[ord(s[next_escp])]):
                break
            next_escp += 1
        # If we moved anywhere between escapes, copy that data.
        if next_escp > in_idx:
            res.append_slice(s, in_idx, next_escp)
        res.append(ESCAPED_CHARS_REPL[ord(s[next_escp])])
        in_idx = next_escp + 1
        # Another performance hack
        del next_escp
    # If there's anything left of the string, copy it over.
    if in_idx < len(s):
        res.append_slice(s, in_idx, len(s))
    return Markup(res.build())

def escape_silent(s):
    """Like :func:`escape` but converts `None` into an empty
    markup string.
    """
    if s is None:
        return Markup()
    return escape(s)

def soft_unicode(s):
    """Make a string unicode if it isn't already.  That way a markup
    string is not converted back to unicode.
    """
    if not isinstance(s, unicode):
        s = unicode(s)
    return s
<commit_msg>Change this back, the difference doesn't matter.<commit_after>import array
from __pypy__.builders import UnicodeBuilder

from markupsafe import Markup

ESCAPED_CHARS_TABLE_SIZE = 256
ESCAPED_CHARS_DELTA_LEN = array.array("l", [0]) * ESCAPED_CHARS_TABLE_SIZE
ESCAPED_CHARS_REPL = [""] * ESCAPED_CHARS_TABLE_SIZE
for c, repl in [
    ('"', u"""),
    ("'", u"'"),
    ("&", u"&"),
    ("<", u"<"),
    (">", u">"),
]:
    ESCAPED_CHARS_DELTA_LEN[ord(c)] = len(repl)
    ESCAPED_CHARS_REPL[ord(c)] = repl

def escape(s):
    if hasattr(s, '__html__'):
        return s.__html__()
    s = unicode(s)

    i = 0
    delta = 0
    repls = 0
    # Find the total number of replacements, and their total distance.
    while i < len(s):
        c = ord(s[i])
        try:
            d = ESCAPED_CHARS_DELTA_LEN[c]
        except IndexError:
            pass
        else:
            delta += d
            repls += bool(d)
        i += 1
        # Performance hack, can go away when PyPy's bridges are better
        # optimized
        del c
        del d
    # If there are no replacements just return the original string.
    if not repls:
        return s

    res = UnicodeBuilder(len(s) + delta)
    in_idx = 0
    # While there are still replcaements in the string.
    while repls > 0:
        repls -= 1
        next_escp = in_idx
        # Find the next escape
        while next_escp < len(s):
            if (ord(s[next_escp]) < len(ESCAPED_CHARS_DELTA_LEN) and
                ESCAPED_CHARS_DELTA_LEN[ord(s[next_escp])]):
                break
            next_escp += 1
        # If we moved anywhere between escapes, copy that data.
        if next_escp > in_idx:
            res.append_slice(s, in_idx, next_escp)
        res.append(ESCAPED_CHARS_REPL[ord(s[next_escp])])
        in_idx = next_escp + 1
        # Another performance hack
        del next_escp
    # If there's anything left of the string, copy it over.
    if in_idx < len(s):
        res.append_slice(s, in_idx, len(s))
    return Markup(res.build())

def escape_silent(s):
    """Like :func:`escape` but converts `None` into an empty
    markup string.
    """
    if s is None:
        return Markup()
    return escape(s)

def soft_unicode(s):
    """Make a string unicode if it isn't already.  That way a markup
    string is not converted back to unicode.
    """
    if not isinstance(s, unicode):
        s = unicode(s)
    return s
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import json
from dajaxice.decorators import dajaxice_register
from django.contrib.contenttypes.models import ContentType
from ipware.ip import get_ip
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from models import Eintrage as Rating, UserIP
from django.db.models import Q
from django.conf import settings

###Liste der möglichen Ausnahmen####
fehlerliste = {
	"1": "Fehler bei GetContent: App_label, Model oder Object ID stimmen nicht!",
	"2": "Du willst zu hoch hinaus!",
	"3": "Produkt nicht vorhanden!",
	"4": "Bitte ein Kommentar abgeben!",
	"5": "Anonyme User können keine Kommentare haben!",
	"6": "Fehler2",

}

### GENERAL ###
class GetContent(object):
	# Hier werden die Daten gespeichert, die bei __init__ rausgefunden werden
	# Name des Models
	content_type = ""
	# ID des bewerteten Objektes
	content = ""
	# Das ganze Model des bewerteten Objektes
	model_type = ""
	# Die Model Klasse
	model_class = ""

	# ein Initialisator
	# self ist für automatische Zuweisung zuständig --> general = GetContent(id, model, app_label)
	def __init__(self, model, app_label, id=0):
		self.content_type = ContentType.objects.get(app_label=app_label, model=model)
		# Python Model Class
		self.model_class = self.content_type.model_class()
		# Das ganze Model (COntent Type Model) wird geholt. Es ist nötig zuerst COntentTYpe abzufragen.
		self.model_type = ContentType.objects.get_for_model(self.model_class)
		if id:
			# Inhalt vom Objekt = ganzes Row
			self.content = self.content_type.get_object_for_this_type(id=id)

#### STARS ####
# Abfrage einer Bewertung
@dajaxice_register
# ID, Model und App_label des bewerteten Objekts werden übergeben
def get_rating(request, id, model, app_label):
	result = ""
	counter = 0
	# GetContent wird aufgerufen und geholte Daten(id, model, app_label) in general Variable gespeichert.
	# try:
	general = GetContent(model, app_label, id)
	# except:
	# 	return json.dumps({'fehler':fehlerliste['1']})
	# Django Filter = SQL SELECT ... WHERE content_type__pk =
	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, sterne__isnull=False)
	if ratings:
		for rating in ratings:
			if counter == 0:
				result = int(rating.sterne)
			else:
				result = int(rating.sterne) + result
			counter = counter + 1
		result = result / counter
	return json.dumps({'sterne': result, "menge": counter})

# Abfrage aller Bewertungen für Produktenliste
@dajaxice_register
def get_rating_list(request, ids, model, app_label):
	results = {}
	mengen = {}
	content_type = ContentType.objects.get(app_label=app_label, model=model)
	for id in ids:
		result = 0
		counter = 0
		content = content_type.get_object_for_this_type(id=id)
		model_type = ContentType.objects.get_for_model(content)
		ratings = Rating.objects.filter(content_type__pk=model_type.id, object_id=content.id, sterne__isnull=False)
		if ratings:
			for rating in ratings:
				if rating.sterne:
					if counter == 0:
						result = int(rating.sterne)
					else:
						result = int(rating.sterne) + result
				counter = counter + 1
			if result and counter:
				result = result / counter
			results[id] = result
			mengen[id] = ratings.count()
	return json.dumps({'results': results, "mengen": mengen})

@dajaxice_register
def set_rating(request, id, model, app_label, sterne):
	ip_object = ""
	general = GetContent(model, app_label, id)
	# Wenn ein SternValue grösser ist.
	if int(sterne) > 5:
		return json.dumps({'fehler': fehlerliste['1']})
	try:
		content = general.content_type.get_object_for_this_type(id=id)
	except:
		return json.dumps({'fehler': fehlerliste['3']})

	# IP ermitteln
	if not request.user.is_authenticated():
		ip = get_ip(request)
		# UserIP Tabelle wird nach angefangene IP Adresse durchgesucht.
		try:
			ip_object = UserIP.objects.get(ip=ip)
		# IP wird neu gespeichert oder überschrieben, damit es keine doppelte Einträge mit gleichen IP-Adresse gibt
		except:
			ip_object = UserIP(ip=ip)
			ip_object.save()

	# Bewertungen speichern
	try:
		# Wenn IP vorhanden ist, wird die Bewertungen-Tabelle nach Einträge mit dieser Adresse durchgesucht.
		if ip_object:
			rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, ip=ip_object)
		# Sonst die Bewertungen mit dem ID vom eingeloggten User.
		else:
			rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		# Die Sterne werden neu abgespeichert.
		rating.sterne = int(sterne)
	except:
		if ip_object:
			rating = Rating(content_object=content, sterne=sterne, ip=ip_object)
		else:
			rating = Rating(content_object=content, sterne=sterne, user=request.user)
	rating.save()
	menge = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=content.id,
	                              sterne__isnull=False).count()
	return json.dumps({'message': sterne, 'menge': menge})

######################## LIKES ########################

@login_required
@dajaxice_register
def get_like(request, id, model, app_label):
	general = GetContent(model, app_label, id)
	status = False
	try:
		rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		if rating.likes:
			status = True
	except:
		pass
	return json.dumps({'like': status})

# Like setzen
@login_required
@dajaxice_register
def set_like(request, id, model, app_label):
	content_type = ContentType.objects.get(app_label=app_label, model=model)
	try:
		content = content_type.get_object_for_this_type(id=id)
	except:
		return json.dumps({'message': "Produkt nicht vorhanden!"})
	model_type = ContentType.objects.get_for_model(content)

	try:
		rating = Rating.objects.get(content_type__pk=model_type.id, object_id=content.id, user=request.user)
		if rating.likes:
			rating.likes = False
		else:
			rating.likes = True
	except:
		rating = Rating(content_object=content, likes=True, user=request.user)
	rating.save()
	return json.dumps({'like': rating.likes})

######################## COMMENTS ########################
# Abfrage von Kommentaren
@login_required
@dajaxice_register
def get_comments(request, id, model, app_label):
	result = ""
	counter = 0
	try:
		general = GetContent(model, app_label, id)
	except:
		return json.dumps({'fehler':fehlerliste['1']})

	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False)
	user_comment = ""
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False, user=request.user)
	except:
		pass
	return render(request, 'rating/comments_box.html', {
		'ratings': ratings,
		'user_comment': user_comment,
	})

# Kommentar setzen
@login_required
@dajaxice_register
def set_comment(request, id, model, app_label, comment):
	try:
		general = GetContent(model, app_label, id)
	except:
		return json.dumps({'fehler': fehlerliste['1']})
	# Wenn comment leer ist
	if not comment:
		return json.dumps({'fehler': fehlerliste['4']})
	# Überprüfung, ob eine Bewertung über ein Kommentar schon verfügt.
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		user_comment.kommentar = str(comment)
	except:
		user_comment = Rating(content_object=general.content, kommentar=comment, user=request.user)
	user_comment.save()
	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False)
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id,  kommentar__isnull=False, user=request.user)
	except:
		pass
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/comments_box.html', {
		'ratings': ratings,
		'user_comment': user_comment,
	})

# Abfragen von Bewertungen
@login_required
@dajaxice_register
def profile_get_data(request, app_label, model):
	general = GetContent(model, app_label)
	# Überprüfung, ob User ein Administrator ist
	if not request.user.is_superuser:
		user_ratings = Rating.objects.filter(user=request.user, content_type__model=general.model_type)
	else:
		user_ratings = Rating.objects.filter(content_type__model=general.model_type)
	user_ratings = user_ratings.filter(Q(kommentar__isnull=False) | Q(sterne__isnull=False))
	products = general.model_class.objects.all()
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/user_profile_items.html', {
		'model_type': general.model_type,
		'products': products,
		'user_ratings': user_ratings,
	})

# Löschen einer Bewertung
@login_required
@dajaxice_register
def profile_remove_rating(request, id):
	try:
		# Überprüfung, ob User ein Administrator ist.
		if not request.user.is_superuser:
			rating = Rating.objects.get(id=id, user=request.user)
		else:
			rating = Rating.objects.get(id=id)
		rating.delete()
	except:
		return json.dumps({'message': "Kein Bewertungsbjekt mit dem ID: " + id})
	return json.dumps({'message': "Gelöschte Bewertunsobjekt mit dem ID : " + id})

# Bearbeitung einer Bewertung
@login_required
@dajaxice_register
def profile_edit_rating(request, id, comment):
	try:
		# Überprüfung, ob User ein Administrator ist.
		if not request.user.is_superuser:
			rating = Rating.objects.get(id=id, user=request.user)
		else:
			rating = Rating.objects.get(id=id)
		# Wenn Kommentar leer ist
		if not comment:
			rating.kommentar = None
		else:
			rating.kommentar = comment
		# Wenn Bewertung nicht vom eingeloggter User ist, wird der Kommentar nicht gespeichert
		if not rating.user:
			return json.dumps({'fehler': fehlerliste['5']})
		rating.save()
	except:
		return json.dumps({'message': "Kein Bewertungsbjekt mit dem ID: " + id})
	return json.dumps({'message': "Veränderte Bewertunsobjekt mit dem ID : " + id})

# Abfragen von den Produkten mit einem Like
@login_required
@dajaxice_register
def get_like_list(request, app_label, model):
	general = GetContent(model, app_label)
	user_like_ratings = Rating.objects.filter(user=request.user, content_type__model=general.model_type, likes=True)
	products = general.model_class.objects.all()
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/like_list_items.html', {
		'model_type':general.model_type,
		'products':products,
		'user_like_ratings':user_like_ratings,
	})
<commit_msg>Update ajax.py<commit_after># -*- coding: utf-8 -*-
import json
from dajaxice.decorators import dajaxice_register
from django.contrib.contenttypes.models import ContentType
from ipware.ip import get_ip
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from models import Eintrage as Rating, UserIP
from django.db.models import Q
from django.conf import settings

###Liste der möglichen Ausnahmen####
fehlerliste = {
	"1": "Fehler bei GetContent: App_label, Model oder Object ID stimmen nicht!",
	"2": "Du willst zu hoch hinaus!",
	"3": "Produkt nicht vorhanden!",
	"4": "Bitte ein Kommentar abgeben!",
	"5": u"Anonyme User können keine Kommentare haben!",
	"6": "Fehler2",

}

### GENERAL ###
class GetContent(object):
	# Hier werden die Daten gespeichert, die bei __init__ rausgefunden werden
	# Name des Models
	content_type = ""
	# ID des bewerteten Objektes
	content = ""
	# Das ganze Model des bewerteten Objektes
	model_type = ""
	# Die Model Klasse
	model_class = ""

	# ein Initialisator
	# self ist für automatische Zuweisung zuständig --> general = GetContent(id, model, app_label)
	def __init__(self, model, app_label, id=0):
		self.content_type = ContentType.objects.get(app_label=app_label, model=model)
		# Python Model Class
		self.model_class = self.content_type.model_class()
		# Das ganze Model (COntent Type Model) wird geholt. Es ist nötig zuerst COntentTYpe abzufragen.
		self.model_type = ContentType.objects.get_for_model(self.model_class)
		if id:
			# Inhalt vom Objekt = ganzes Row
			self.content = self.content_type.get_object_for_this_type(id=id)

#### STARS ####
# Abfrage einer Bewertung
@dajaxice_register
# ID, Model und App_label des bewerteten Objekts werden übergeben
def get_rating(request, id, model, app_label):
	result = ""
	counter = 0
	# GetContent wird aufgerufen und geholte Daten(id, model, app_label) in general Variable gespeichert.
	# try:
	general = GetContent(model, app_label, id)
	# except:
	# 	return json.dumps({'fehler':fehlerliste['1']})
	# Django Filter = SQL SELECT ... WHERE content_type__pk =
	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, sterne__isnull=False)
	if ratings:
		for rating in ratings:
			if counter == 0:
				result = int(rating.sterne)
			else:
				result = int(rating.sterne) + result
			counter = counter + 1
		result = result / counter
	return json.dumps({'sterne': result, "menge": counter})

# Abfrage aller Bewertungen für Produktenliste
@dajaxice_register
def get_rating_list(request, ids, model, app_label):
	results = {}
	mengen = {}
	content_type = ContentType.objects.get(app_label=app_label, model=model)
	for id in ids:
		result = 0
		counter = 0
		content = content_type.get_object_for_this_type(id=id)
		model_type = ContentType.objects.get_for_model(content)
		ratings = Rating.objects.filter(content_type__pk=model_type.id, object_id=content.id, sterne__isnull=False)
		if ratings:
			for rating in ratings:
				if rating.sterne:
					if counter == 0:
						result = int(rating.sterne)
					else:
						result = int(rating.sterne) + result
				counter = counter + 1
			if result and counter:
				result = result / counter
			results[id] = result
			mengen[id] = ratings.count()
	return json.dumps({'results': results, "mengen": mengen})

@dajaxice_register
def set_rating(request, id, model, app_label, sterne):
	ip_object = ""
	general = GetContent(model, app_label, id)
	# Wenn ein SternValue grösser ist.
	if int(sterne) > 5:
		return json.dumps({'fehler': fehlerliste['1']})
	try:
		content = general.content_type.get_object_for_this_type(id=id)
	except:
		return json.dumps({'fehler': fehlerliste['3']})

	# IP ermitteln
	if not request.user.is_authenticated():
		ip = get_ip(request)
		# UserIP Tabelle wird nach angefangene IP Adresse durchgesucht.
		try:
			ip_object = UserIP.objects.get(ip=ip)
		# IP wird neu gespeichert oder überschrieben, damit es keine doppelte Einträge mit gleichen IP-Adresse gibt
		except:
			ip_object = UserIP(ip=ip)
			ip_object.save()

	# Bewertungen speichern
	try:
		# Wenn IP vorhanden ist, wird die Bewertungen-Tabelle nach Einträge mit dieser Adresse durchgesucht.
		if ip_object:
			rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, ip=ip_object)
		# Sonst die Bewertungen mit dem ID vom eingeloggten User.
		else:
			rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		# Die Sterne werden neu abgespeichert.
		rating.sterne = int(sterne)
	except:
		if ip_object:
			rating = Rating(content_object=content, sterne=sterne, ip=ip_object)
		else:
			rating = Rating(content_object=content, sterne=sterne, user=request.user)
	rating.save()
	menge = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=content.id,
	                              sterne__isnull=False).count()
	return json.dumps({'message': sterne, 'menge': menge})

######################## LIKES ########################

@login_required
@dajaxice_register
def get_like(request, id, model, app_label):
	general = GetContent(model, app_label, id)
	status = False
	try:
		rating = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		if rating.likes:
			status = True
	except:
		pass
	return json.dumps({'like': status})

# Like setzen
@login_required
@dajaxice_register
def set_like(request, id, model, app_label):
	content_type = ContentType.objects.get(app_label=app_label, model=model)
	try:
		content = content_type.get_object_for_this_type(id=id)
	except:
		return json.dumps({'message': "Produkt nicht vorhanden!"})
	model_type = ContentType.objects.get_for_model(content)

	try:
		rating = Rating.objects.get(content_type__pk=model_type.id, object_id=content.id, user=request.user)
		if rating.likes:
			rating.likes = False
		else:
			rating.likes = True
	except:
		rating = Rating(content_object=content, likes=True, user=request.user)
	rating.save()
	return json.dumps({'like': rating.likes})

######################## COMMENTS ########################
# Abfrage von Kommentaren
@login_required
@dajaxice_register
def get_comments(request, id, model, app_label):
	result = ""
	counter = 0
	try:
		general = GetContent(model, app_label, id)
	except:
		return json.dumps({'fehler':fehlerliste['1']})

	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False)
	user_comment = ""
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False, user=request.user)
	except:
		pass
	return render(request, 'rating/comments_box.html', {
		'ratings': ratings,
		'user_comment': user_comment,
	})

# Kommentar setzen
@login_required
@dajaxice_register
def set_comment(request, id, model, app_label, comment):
	try:
		general = GetContent(model, app_label, id)
	except:
		return json.dumps({'fehler': fehlerliste['1']})
	# Wenn comment leer ist
	if not comment:
		return json.dumps({'fehler': fehlerliste['4']})
	# Überprüfung, ob eine Bewertung über ein Kommentar schon verfügt.
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id, user=request.user)
		user_comment.kommentar = str(comment)
	except:
		user_comment = Rating(content_object=general.content, kommentar=comment, user=request.user)
	user_comment.save()
	ratings = Rating.objects.filter(content_type__pk=general.model_type.id, object_id=general.content.id, kommentar__isnull=False)
	try:
		user_comment = Rating.objects.get(content_type__pk=general.model_type.id, object_id=general.content.id,  kommentar__isnull=False, user=request.user)
	except:
		pass
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/comments_box.html', {
		'ratings': ratings,
		'user_comment': user_comment,
	})

# Abfragen von Bewertungen
@login_required
@dajaxice_register
def profile_get_data(request, app_label, model):
	general = GetContent(model, app_label)
	# Überprüfung, ob User ein Administrator ist
	if not request.user.is_superuser:
		user_ratings = Rating.objects.filter(user=request.user, content_type__model=general.model_type)
	else:
		user_ratings = Rating.objects.filter(content_type__model=general.model_type)
	user_ratings = user_ratings.filter(Q(kommentar__isnull=False) | Q(sterne__isnull=False))
	products = general.model_class.objects.all()
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/user_profile_items.html', {
		'model_type': general.model_type,
		'products': products,
		'user_ratings': user_ratings,
	})

# Löschen einer Bewertung
@login_required
@dajaxice_register
def profile_remove_rating(request, id):
	try:
		# Überprüfung, ob User ein Administrator ist.
		if not request.user.is_superuser:
			rating = Rating.objects.get(id=id, user=request.user)
		else:
			rating = Rating.objects.get(id=id)
		rating.delete()
	except:
		return json.dumps({'message': "Kein Bewertungsbjekt mit dem ID: " + id})
	return json.dumps({'message': u"Gelöschte Bewertunsobjekt mit dem ID : " + id})

# Bearbeitung einer Bewertung
@login_required
@dajaxice_register
def profile_edit_rating(request, id, comment):
	try:
		# Überprüfung, ob User ein Administrator ist.
		if not request.user.is_superuser:
			rating = Rating.objects.get(id=id, user=request.user)
		else:
			rating = Rating.objects.get(id=id)
		# Wenn Kommentar leer ist
		if not comment:
			rating.kommentar = None
		else:
			rating.kommentar = comment
		# Wenn Bewertung nicht vom eingeloggter User ist, wird der Kommentar nicht gespeichert
		if not rating.user:
			return json.dumps({'fehler': fehlerliste['5']})
		rating.save()
	except:
		return json.dumps({'message': "Kein Bewertungsbjekt mit dem ID: " + id})
	return json.dumps({'message': u"Veränderte Bewertunsobjekt mit dem ID : " + id})

# Abfragen von den Produkten mit einem Like
@login_required
@dajaxice_register
def get_like_list(request, app_label, model):
	general = GetContent(model, app_label)
	user_like_ratings = Rating.objects.filter(user=request.user, content_type__model=general.model_type, likes=True)
	products = general.model_class.objects.all()
	# Daten werden in Variablen gespeichert und an Template übergeben
	return render(request, 'rating/like_list_items.html', {
		'model_type':general.model_type,
		'products':products,
		'user_like_ratings':user_like_ratings,
	})
<|endoftext|>


<commit_before>'''
Unit tests for the robotutils.strmap_helper module.

This is a port of the JUnit test for the corresponding Java
robotutils class, StringmapHelper
Author: JMJ
'''

import unittest
import re
import random

#import strmap_helper
from . import strmap_helper

_REGEX_VALIDNAME = re.compile(r"\w+")
_STRING_DEFAULT = 'WOAH!!!'

_INT_MIN = -10
_INT_MAX = 10
_INT_DEFAULT = _INT_MAX * 10

_FLOAT_MIN = -1.0
_FLOAT_MAX = 1.0
_FLOAT_DEFAULT = _FLOAT_MAX * 10

class TestStringmapHelper(unittest.TestCase):
    """Container class for unittest tests."""

    def test_empty_map(self):
        """Checks against empty map - should return defaults"""
        empty = strmap_helper.StringDictHelper(dict())

        self.assertEqual("bar", empty.get_as_str("foo", "bar"))
        self.assertEqual(True, empty.get_as_bool("foo", True))
        self.assertEqual(42, empty.get_as_num("foo", 42))
        self.assertAlmostEqual(3.14, empty.get_as_num("foo", 3.14))

        # Same deal, with the more complex versions...
        self.assertEqual("bar", empty.get_as_str("foo", "bar", _REGEX_VALIDNAME))
        self.assertEqual(42, empty.get_as_num("foo", 42, 0, 100))
        self.assertAlmostEqual(3.14, empty.get_as_num("foo", 3.14, 0.0, 100.0))

    @staticmethod
    def buildRandomInput(count):
        """Construct and return {count} random test inputs in an iterable"""
        randomInput = [] # contains (k, v) tuples
        for i in range(count):
            key = "key" + str(i);
            k = random.randint(0, 3)
            if k == 0:
                # String. The following can't have any embedded digits, so substrings can never
                # be valid ints, longs or doubles. Also the two can't have overlapping
                # character sets,
                # and only goodS must pass the string validity test.
                goodS = "jfAGsrhGGhAhafHaahwHghqgQghqh"
                badS = "!@#$%^&*)&^#**%&%*@(*&*&*&*&!#%^*"
                s = goodS if random.randint(0,1) else badS
                assert _REGEX_VALIDNAME.fullmatch(goodS)
                assert not _REGEX_VALIDNAME.match(badS)
                rs = s[:random.randint(0, len(s))]
                kvi = (key, rs);
                randomInput.append(kvi)
            elif k == 1:
                # int
                ri = int(2 * (_INT_MIN + random.random() * (_INT_MAX - _INT_MIN)))
                kvi = (key, ri)
                randomInput.append(kvi)
            elif k == 2:
                # float
                df = 2 * (_FLOAT_MIN + random.random() * (_FLOAT_MAX - _FLOAT_MIN))
                kvi = (key, df)
                randomInput.append(kvi)
            else:
                # bool
                rb = True if random.randint(0,1) else False
                kvi = (key, rb)
                randomInput.append(kvi)
        return randomInput

    @staticmethod
    def buildRandomDict(kv_infos):
        """Build a random dictionary of (k,v) pairs"""
        return {k: str(v) for k, v in kv_infos}

    def run_gauntlet(self, smg, kvi):
        """Run tests using all the (key, value) pairs in kv_infos"""
        key, expected_val = kvi
        got_val = smg.get_as_str(key, _STRING_DEFAULT, _REGEX_VALIDNAME)
        isValid = _REGEX_VALIDNAME.fullmatch(str(expected_val))
        if isValid:
            self.assertEqual(got_val, str(expected_val))
        else:
            self.assertEqual(got_val, _STRING_DEFAULT)

    def test_bigTest(self):
        """Create many (k,v) pairs and run the gauntlet test on them."""
        kv_infos =  self.buildRandomInput(20)
        smap =   self.buildRandomDict(kv_infos)
        smh = strmap_helper.StringDictHelper(smap)
        for kv in kv_infos:
            self.run_gauntlet(smh, kv)

if __name__ == '__main__':
    L = TestStringmapHelper.buildRandomInput(5)
    print(L)
    D = TestStringmapHelper.buildRandomDict(L)
    print(D)
<commit_msg>testing misc/strmap_helper.get_as_bool<commit_after>'''
Unit tests for the robotutils.strmap_helper module.

This is a port of the JUnit test for the corresponding Java
robotutils class, StringmapHelper
Author: JMJ
'''

import unittest
import re
import random

#import strmap_helper
from . import strmap_helper

_REGEX_VALIDNAME = re.compile(r"\w+")
_STRING_DEFAULT = 'WOAH!!!'
_BOOL_DEFAULT = True

_INT_MIN = -10
_INT_MAX = 10
_INT_DEFAULT = _INT_MAX * 10

_FLOAT_MIN = -1.0
_FLOAT_MAX = 1.0
_FLOAT_DEFAULT = _FLOAT_MAX * 10

class TestStringmapHelper(unittest.TestCase):
    """Container class for unittest tests."""

    def test_empty_map(self):
        """Checks against empty map - should return defaults"""
        empty = strmap_helper.StringDictHelper(dict())

        self.assertEqual("bar", empty.get_as_str("foo", "bar"))
        self.assertEqual(True, empty.get_as_bool("foo", True))
        self.assertEqual(42, empty.get_as_num("foo", 42))
        self.assertAlmostEqual(3.14, empty.get_as_num("foo", 3.14))

        # Same deal, with the more complex versions...
        self.assertEqual("bar", empty.get_as_str("foo", "bar", _REGEX_VALIDNAME))
        self.assertEqual(42, empty.get_as_num("foo", 42, 0, 100))
        self.assertAlmostEqual(3.14, empty.get_as_num("foo", 3.14, 0.0, 100.0))

    @staticmethod
    def buildRandomInput(count):
        """Construct and return {count} random test inputs in an iterable"""
        randomInput = [] # contains (k, v) tuples
        for i in range(count):
            key = "key" + str(i);
            k = random.randint(0, 3)
            if k == 0:
                # String. The following can't have any embedded digits, so substrings can never
                # be valid ints, longs or doubles. Also the two can't have overlapping
                # character sets,
                # and only goodS must pass the string validity test.
                goodS = "jfAGsrhGGhAhafHaahwHghqgQghqh"
                badS = "!@#$%^&*)&^#**%&%*@(*&*&*&*&!#%^*"
                s = goodS if random.randint(0,1) else badS
                assert _REGEX_VALIDNAME.fullmatch(goodS)
                assert not _REGEX_VALIDNAME.match(badS)
                rs = s[:random.randint(0, len(s))]
                kvi = (key, rs);
                randomInput.append(kvi)
            elif k == 1:
                # int
                ri = int(2 * (_INT_MIN + random.random() * (_INT_MAX - _INT_MIN)))
                kvi = (key, ri)
                randomInput.append(kvi)
            elif k == 2:
                # float
                df = 2 * (_FLOAT_MIN + random.random() * (_FLOAT_MAX - _FLOAT_MIN))
                kvi = (key, df)
                randomInput.append(kvi)
            else:
                # bool
                rb = True if random.randint(0,1) else False
                kvi = (key, rb)
                randomInput.append(kvi)
        return randomInput

    @staticmethod
    def buildRandomDict(kv_infos):
        """Build a random dictionary of (k,v) pairs"""
        return {k: str(v) for k, v in kv_infos}

    def run_gauntlet(self, smg, kvi):
        """Run tests using all the (key, value) pairs in kv_infos"""
        key, expected_val = kvi

        # Test get_as_str...
        got_val = smg.get_as_str(key, _STRING_DEFAULT, _REGEX_VALIDNAME)
        isValid = _REGEX_VALIDNAME.fullmatch(str(expected_val))
        if isValid:
            self.assertEqual(got_val, str(expected_val))
        else:
            self.assertEqual(got_val, _STRING_DEFAULT)

        # Test get_as_bool...
        got_val = smg.get_as_bool(key, _BOOL_DEFAULT)
        isValid = isinstance(expected_val, bool)
        if isValid:
            self.assertEqual(got_val, expected_val)
        else:
            self.assertEqual(got_val, _BOOL_DEFAULT)

        # TODO
        # Test get_as_num: int without min, max
        # Test get_as_num: int with min, max
        # Test get_as_num: float without min, max
        # Test get_as_num: float with min, max

    def test_bigTest(self):
        """Create many (k,v) pairs and run the gauntlet test on them."""
        kv_infos =  self.buildRandomInput(20)
        smap =   self.buildRandomDict(kv_infos)
        smh = strmap_helper.StringDictHelper(smap)
        for kv in kv_infos:
            self.run_gauntlet(smh, kv)

if __name__ == '__main__':
    L = TestStringmapHelper.buildRandomInput(5)
    print(L)
    D = TestStringmapHelper.buildRandomDict(L)
    print(D)
<|endoftext|>


<commit_before>import re

class Playfair():
    """The Playfair Cipher enciphers pairs of characters, the key consists of
    a keysquare 25 characters in length.
    More information about the algorithm can be
    found at http://www.practicalcryptography.com/ciphers/playfair-cipher/.

    :param key: The keysquare, as a 25 character string.
    :param newkey: The key to make an unique keysquare
    """
    def __init__(self, newkey, key='ABCDEFGHIKLMNOPQRSTUVWXYZ'):
        newkey = newkey.replace(' ', '').upper().replace('J', 'I')
        newkey = ''.join([newkey, key])
        self.newkey = (sorted(set(newkey), key=newkey.index))

    def remove_punctuation(self, text, filter='[^A-Z]'):
        return re.sub(filter, '', text.upper())

    def encipher_pair(self, a, b):
        if a == b:
            b = 'X'
        arow, acol = int(self.newkey.index(a) / 5), self.newkey.index(a) % 5
        brow, bcol = int(self.newkey.index(b) / 5), self.newkey.index(b) % 5
        if arow == brow:
            return self.newkey[arow * 5 + (acol + 1) % 5] + self.newkey[brow * 5 + (bcol + 1) % 5]
        elif acol == bcol:
            return self.newkey[((arow + 1) % 5) * 5 + acol] + self.newkey[((brow + 1) % 5) * 5 + bcol]
        else:
            return self.newkey[arow * 5 + bcol] + self.newkey[brow * 5 + acol]

    def decipher_pair(self, a, b):
        assert a != b, 'two of the same letters occurred together, illegal in playfair'
        arow, acol = int(self.newkey.index(a) / 5), self.newkey.index(a) % 5
        brow, bcol = int(self.newkey.index(b) / 5), self.newkey.index(b) % 5
        if arow == brow:
            return self.newkey[arow * 5 + (acol - 1) % 5] + self.newkey[brow * 5 + (bcol - 1) % 5]
        elif acol == bcol:
            return self.newkey[((arow - 1) % 5) * 5 + acol] + self.newkey[((brow - 1) % 5) * 5 + bcol]
        else:
            return self.newkey[arow * 5 + bcol] + self.newkey[brow * 5 + acol]

    def encipher(self, string):
        """Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
        are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
        :param string: The string to encipher.
        :returns: The enciphered string.
        """
        string = self.remove_punctuation(string)
        string = re.sub(r'[J]', 'I', string)
        if len(string) % 2 == 1:
            string += 'X'
        ret = ''
        for c in range(0, len(string), 2):
            ret += self.encipher_pair(string[c], string[c + 1])
        return ret

    def decipher(self, string):
        """Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
        are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
        :param string: The string to decipher.
        :returns: The deciphered string.
        """
        string = self.remove_punctuation(string)
        if len(string) % 2 == 1:
            print(string)
            string += 'X'
        ret = ''
        for c in range(0, len(string), 2):
            ret += self.decipher_pair(string[c], string[c + 1])
        return ret

if __name__ == '__main__':
    while True:
        print("Would you like to encode or decode")
        print("press [E] to encode, [D] to decode")
        inputselect = input("Pick an option between E and D:")
        if inputselect.lower() not in ('e', 'd'):
            print("Not an appropriate choice.")
        else:
            break

    if inputselect == 'e':
        print("")
        keyword = input('Enter a keyword: ')
        message = input('Enter string to encode: ')
        playfair_object = Playfair(keyword)
        print(playfair_object.encipher(message))

    if inputselect == 'd':
        print("")
        keyword = input('Enter a keyword: ')
        message = input('Enter string to decode: ')
        playfair_object = Playfair(keyword)
        print(playfair_object.decipher(message))
<commit_msg>removed debuging<commit_after>import re

class Playfair():
    """The Playfair Cipher enciphers pairs of characters, the key consists of
    a keysquare 25 characters in length.
    More information about the algorithm can be
    found at http://www.practicalcryptography.com/ciphers/playfair-cipher/.

    :param key: The keysquare, as a 25 character string.
    :param newkey: The key to make an unique keysquare
    """
    def __init__(self, newkey, key='ABCDEFGHIKLMNOPQRSTUVWXYZ'):
        newkey = newkey.replace(' ', '').upper().replace('J', 'I')
        newkey = ''.join([newkey, key])
        self.newkey = (sorted(set(newkey), key=newkey.index))

    def remove_punctuation(self, text, filter='[^A-Z]'):
        return re.sub(filter, '', text.upper())

    def encipher_pair(self, a, b):
        if a == b:
            b = 'X'
        arow, acol = int(self.newkey.index(a) / 5), self.newkey.index(a) % 5
        brow, bcol = int(self.newkey.index(b) / 5), self.newkey.index(b) % 5
        if arow == brow:
            return self.newkey[arow * 5 + (acol + 1) % 5] + self.newkey[brow * 5 + (bcol + 1) % 5]
        elif acol == bcol:
            return self.newkey[((arow + 1) % 5) * 5 + acol] + self.newkey[((brow + 1) % 5) * 5 + bcol]
        else:
            return self.newkey[arow * 5 + bcol] + self.newkey[brow * 5 + acol]

    def decipher_pair(self, a, b):
        assert a != b, 'two of the same letters occurred together, illegal in playfair'
        arow, acol = int(self.newkey.index(a) / 5), self.newkey.index(a) % 5
        brow, bcol = int(self.newkey.index(b) / 5), self.newkey.index(b) % 5
        if arow == brow:
            return self.newkey[arow * 5 + (acol - 1) % 5] + self.newkey[brow * 5 + (bcol - 1) % 5]
        elif acol == bcol:
            return self.newkey[((arow - 1) % 5) * 5 + acol] + self.newkey[((brow - 1) % 5) * 5 + bcol]
        else:
            return self.newkey[arow * 5 + bcol] + self.newkey[brow * 5 + acol]

    def encipher(self, string):
        """Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
        are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
        :param string: The string to encipher.
        :returns: The enciphered string.
        """
        string = self.remove_punctuation(string)
        string = re.sub(r'[J]', 'I', string)
        if len(string) % 2 == 1:
            string += 'X'
        ret = ''
        for c in range(0, len(string), 2):
            ret += self.encipher_pair(string[c], string[c + 1])
        return ret

    def decipher(self, string):
        """Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
        are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
        :param string: The string to decipher.
        :returns: The deciphered string.
        """
        string = self.remove_punctuation(string)
        if len(string) % 2 == 1:
            string += 'X'
        ret = ''
        for c in range(0, len(string), 2):
            ret += self.decipher_pair(string[c], string[c + 1])
        return ret

if __name__ == '__main__':
    while True:
        print("Would you like to encode or decode")
        print("press [E] to encode, [D] to decode")
        inputselect = input("Pick an option between E and D:")
        if inputselect.lower() not in ('e', 'd'):
            print("Not an appropriate choice.")
        else:
            break

    if inputselect == 'e':
        print("")
        keyword = input('Enter a keyword: ')
        message = input('Enter string to encode: ')
        playfair_object = Playfair(keyword)
        print(playfair_object.encipher(message))

    if inputselect == 'd':
        print("")
        keyword = input('Enter a keyword: ')
        message = input('Enter string to decode: ')
        playfair_object = Playfair(keyword)
        print(playfair_object.decipher(message))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# @Author: twankim
# @Date:   2017-02-24 17:46:51
# @Last Modified by:   twankim
# @Last Modified time: 2017-10-25 14:53:07

import numpy as np
import time
import sys
import os
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from ssac import weakSSAC
from ssac_org import SSAC
# from gen_data import genData
from utils import *
import cPickle as pickle

weak = "weak"
delta = 0.99
base_dir= os.path.join('./results',weak+'_compare_mnist')

def main(args):
    # Load MNIST 2500 subset
    with open('dataset/mnist2500.pkl','rb') as fp:
        dataset = pickle.load(fp)

    rep = args.rep
    i_plot = 0

    # qs = [float(q) for q in args.qs.split(',')]
    etas = [float(eta) for eta in args.etas.split(',')]
    beta = args.beta
    verbose = args.verbose

    cs = [float(q) for q in args.cs.split(',')]

    res_acc = np.zeros((rep,len(cs),len(etas))) # Accuracy of clustering
    res_mean_acc = np.zeros((rep,len(cs),len(etas))) # Mean accuracy of clustering (per cluster)
    # res_err = np.zeros((rep,len(qs),len(etas))) # Number of misclustered points
    res_fail = np.zeros((rep,len(cs),len(etas))) # Number of Failure

    res_acc_org = np.zeros((rep,len(cs),len(etas))) # Accuracy of clustering
    res_mean_acc_org = np.zeros((rep,len(cs),len(etas))) # Mean accuracy of clustering (per cluster)
    # res_err = np.zeros((rep,len(qs),len(etas))) # Number of misclustered points
    res_fail_org = np.zeros((rep,len(cs),len(etas))) # Number of Failure

    gammas = np.zeros(rep)
    nus = np.zeros((rep,len(cs)))
    rhos = np.zeros((rep,len(cs)))

    digits = [str(int(dataset.dict_label[label])) for label in dataset.dict_label.keys()]
    # Make directories to save results
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    res_dir = base_dir + '/{}'.format(
        ','.join(digits))
    if not os.path.exists(res_dir):
        os.makedirs(res_dir)

    if verbose:
        print "MNIST2500 Subset... Digits:{}".format(','.join(digits))

    for i_rep in xrange(rep):
        if verbose:
            print "({}/{})... Testing Algorithm".format(i_rep+1,rep)
        X = dataset.X
        y_true = dataset.y
        ris = dataset.ris
        gamma = dataset.gamma
        gammas[i_rep] = gamma

        n = dataset.n
        m = dataset.m
        k = dataset.k

        algo = weakSSAC(X,y_true,k,wtype=weak,ris=ris)
        algo_org = SSAC(X,y_true,k,wtype=weak,ris=ris)
        # Test SSAC algorithm for different c's and eta's (fix beta in this case)
        for i_c,c_dist in enumerate(cs):
            assert (c_dist>0.5) & (c_dist<=1.0), "c_dist must be in (0.5,1]"

            nus[i_rep,i_c] = float(gamma) + 1.5*(1-c_dist)
            rhos[i_rep,i_c] = c_dist

            # Calculate proper eta and beta based on parameters including delta
            if verbose:
                print "   - Proper eta={}, beta={} (delta={})".format(
                        dataset.calc_eta(delta,weak=weak,nu=nus[i_rep,i_c],rho=rhos[i_rep,i_c]),
                        dataset.calc_beta(delta,weak=weak,nu=nus[i_rep,i_c],rho=rhos[i_rep,i_c]),
                        delta)

            for i_eta,eta in enumerate(etas):
                if verbose:
                    print "     <Test: c_dist={}, eta={}, beta={}>".format(c_dist,eta,beta)
                algo.set_params(eta,beta,rho=rhos[i_rep,i_c],nu=nus[i_rep,i_c])
                algo_org.set_params(eta,beta,rho=rhos[i_rep,i_c],nu=nus[i_rep,i_c])

                if not algo.fit():
                    # Algorithm has failed
                    res_fail[i_rep,i_c,i_eta] = 1
                    i_plot = np.random.randint(i_rep+1,rep) # Index of experiment to plot the figure
                if not algo_org.fit():
                    # Algorithm has failed
                    res_fail_org[i_rep,i_c,i_eta] = 1
                    # i_plot = np.random.randint(i_rep+1,rep) # Index of experiment to plot the figure

                y_pred = algo.y
                mpps = algo.mpps # Estimated cluster centers
                # print "     ... Clustering is done. Number of binary search steps = {}\n".format(algo.bs_num)
                y_pred_org = algo_org.y
                mpps_org = algo_org.mpps # Estimated cluster centers

                # For evaluation & plotting, find best permutation of cluster assignment
                y_pred_perm = find_permutation(dataset,algo)
                y_pred_perm_org = find_permutation(dataset,algo_org)

                # Calculate accuracy and mean accuracy
                res_acc[i_rep,i_c,i_eta] = accuracy(y_true,y_pred_perm)
                res_mean_acc[i_rep,i_c,i_eta] = mean_accuracy(y_true,y_pred_perm)
                res_acc_org[i_rep,i_c,i_eta] = accuracy(y_true,y_pred_perm_org)
                res_mean_acc_org[i_rep,i_c,i_eta] = mean_accuracy(y_true,y_pred_perm_org)

                # # Calculate number of errors
                # res_err[i_rep,i_c,i_eta] = error(y_true,y_pred_perm)

                if (i_rep == i_plot) and (m<=2):
                    list_classes = ['Not assigned']
                    for i in xrange(k):
                        list_classes.append('Digit {}'.format(i))
                    title = r"SSAC with {} weak oracle ($\eta={}, \beta={}, \nu={:.2f}, \rho={:.2f}$)".format(
                                weak,eta,beta,nus[i_rep,i_c],rhos[i_rep,i_c])
                    f_name = res_dir+'/fig_n{}_m{}_k{}_c{:03d}_e{:d}.png'.format(n,m,k,int(100*c_dist),int(eta))
                    plot_cluster(X,y_true,y_pred_perm,k,mpps,gamma,
                                 title,f_name,verbose,
                                 classes=list_classes)
                    # title_org = r"SSAC(original) with {} weak oracle ($\eta={}, \beta={}, \rho={:.2f}$)".format(
                    #             weak,eta,beta,rhos[i_rep,i_c])
                    # f_name_org = res_dir+'/fig_org_n{}_m{}_k{}_c{:03d}_e{:d}.png'.format(n,m,k,int(100*c_dist),int(eta))
                    # plot_cluster(X,y_true,y_pred_perm_org,k,mpps_org,gamma,
                    #              title_org,f_name_org,verbose)

    # Write result as table
    print_eval("Accuracy(%)",res_acc,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("acc",n,m,k),weak=weak,params=cs)
    print_eval("Mean Accuracy(%)",res_mean_acc,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("meanacc",n,m,k),weak=weak,params=cs)
    # print_eval("# Error(%)",res_err,qs,etas,
    #            res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("err",n,m,k))
    print_eval("# Failure",res_fail,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("fail",n,m,k),
               is_sum=True,weak=weak,params=cs)

    print_eval("Accuracy(%)",res_acc_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("acc",n,m,k),weak=weak,params=cs)
    print_eval("Mean Accuracy(%)",res_mean_acc_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("meanacc",n,m,k),weak=weak,params=cs)
    # print_eval("# Error(%)",res_err,qs,etas,
    #            res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("err",n,m,k))
    print_eval("# Failure",res_fail_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("fail",n,m,k),
               is_sum=True,weak=weak,params=cs)

    # if args.isplot:
    # Plot Accuracy vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("acc",n,m,k)
    plot_eval("Accuracy(%)",res_acc,etas,fig_name,weak=weak,params=cs,res_org=res_acc_org)

    # Plot Mean Accuracy vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("meanacc",n,m,k)
    plot_eval("Mean Accuracy(%)",res_mean_acc,etas,fig_name,weak=weak,params=cs,res_org=res_mean_acc_org)

    # Plot Failure vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("fail",n,m,k)
    plot_eval("# Failure",res_fail,etas,fig_name,is_sum=True,weak=weak,params=cs,res_org=res_fail_org)

    # # Plot histogram of gammas
    # fig_name = res_dir+'/fig_gamma_hist.pdf'
    # plot_hist(gammas,args.min_gamma,args.max_gamma,fig_name)

    if args.isplot:
        plt.show()

def parse_args():
    def str2bool(v):
        return v.lower() in ('true', '1')

    parser = argparse.ArgumentParser(description=
                        'Test Semi-Supervised Active Clustering with Weak Oracles: Random-weak model')
    # parser.add_argument('-m', dest='m',
    #                     help='Dimension of data points in synthetic data',
    #                     default = 2, type = int)
    parser.add_argument('-rep', dest='rep',
                        help='Number of experiments to repeat',
                        default = 1000, type = int)
    parser.add_argument('-qs', dest='qs',
                        help='Probabilities q (not-sure with 1-q) ex) 0.7,0.85,1',
                        default = '0.7,0.85,1', type = str)
    parser.add_argument('-etas', dest='etas',
                        help='etas: parameter for sampling (phase 1) ex) 10,50',
                        default = '2,5,10,20,30', type = str)
    parser.add_argument('-beta', dest='beta',
                        help='beta: parameter for sampling (phase 2)',
                        default = 1, type = int)
    parser.add_argument('-cs', dest='cs',
                        help='Fractions to set distance-weak parameters (0.5,1] ex) 0.7,0.85,1',
                        default = '0.6,0.8,1', type = str)
    parser.add_argument('-isplot', dest='isplot',
                        help='plot the result: True/False',
                        default = False, type = str2bool)
    parser.add_argument('-verbose', dest='verbose',
                        help='verbose: True/False',
                        default = False, type = str2bool)
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse_args()
    print "Called with args:"
    print args
    sys.exit(main(args))
<commit_msg>Adding MNIST2500<commit_after># -*- coding: utf-8 -*-
# @Author: twankim
# @Date:   2017-02-24 17:46:51
# @Last Modified by:   twankim
# @Last Modified time: 2017-10-25 17:19:50

import numpy as np
import time
import sys
import os
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from ssac import weakSSAC
from ssac_org import SSAC
# from gen_data import genData
from utils import *
import cPickle as pickle

weak = "local"
delta = 0.99
base_dir= os.path.join('./results',weak+'_compare_mnist')

def main(args):
    # Load MNIST 2500 subset
    with open('dataset/mnist2500.pkl','rb') as fp:
        dataset = pickle.load(fp)

    rep = args.rep
    i_plot = 0

    # qs = [float(q) for q in args.qs.split(',')]
    etas = [float(eta) for eta in args.etas.split(',')]
    beta = args.beta
    verbose = args.verbose

    cs = [float(q) for q in args.cs.split(',')]

    res_acc = np.zeros((rep,len(cs),len(etas))) # Accuracy of clustering
    res_mean_acc = np.zeros((rep,len(cs),len(etas))) # Mean accuracy of clustering (per cluster)
    # res_err = np.zeros((rep,len(qs),len(etas))) # Number of misclustered points
    res_fail = np.zeros((rep,len(cs),len(etas))) # Number of Failure

    res_acc_org = np.zeros((rep,len(cs),len(etas))) # Accuracy of clustering
    res_mean_acc_org = np.zeros((rep,len(cs),len(etas))) # Mean accuracy of clustering (per cluster)
    # res_err = np.zeros((rep,len(qs),len(etas))) # Number of misclustered points
    res_fail_org = np.zeros((rep,len(cs),len(etas))) # Number of Failure

    gammas = np.zeros(rep)
    nus = np.zeros((rep,len(cs)))
    rhos = np.zeros((rep,len(cs)))

    digits = [str(int(dataset.dict_label[label])) for label in dataset.dict_label.keys()]
    # Make directories to save results
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    res_dir = base_dir + '/{}'.format(
        ','.join(digits))
    if not os.path.exists(res_dir):
        os.makedirs(res_dir)

    if verbose:
        print "MNIST2500 Subset... Digits:{}".format(','.join(digits))

    for i_rep in xrange(rep):
        if verbose:
            print "({}/{})... Testing Algorithm".format(i_rep+1,rep)
        X = dataset.X
        y_true = dataset.y
        ris = dataset.ris
        gamma = dataset.gamma
        gammas[i_rep] = gamma

        n = dataset.n
        m = dataset.m
        k = dataset.k

        algo = weakSSAC(X,y_true,k,wtype=weak,ris=ris)
        algo_org = SSAC(X,y_true,k,wtype=weak,ris=ris)
        # Test SSAC algorithm for different c's and eta's (fix beta in this case)
        for i_c,c_dist in enumerate(cs):
            assert (c_dist>0.5) & (c_dist<=1.0), "c_dist must be in (0.5,1]"

            nus[i_rep,i_c] = float(gamma) + 1.5*(1-c_dist)
            rhos[i_rep,i_c] = c_dist

            # Calculate proper eta and beta based on parameters including delta
            if verbose:
                print "   - Proper eta={}, beta={} (delta={})".format(
                        dataset.calc_eta(delta,weak=weak,nu=nus[i_rep,i_c],rho=rhos[i_rep,i_c]),
                        dataset.calc_beta(delta,weak=weak,nu=nus[i_rep,i_c],rho=rhos[i_rep,i_c]),
                        delta)

            for i_eta,eta in enumerate(etas):
                if verbose:
                    print "     <Test: c_dist={}, eta={}, beta={}>".format(c_dist,eta,beta)
                algo.set_params(eta,beta,rho=rhos[i_rep,i_c],nu=nus[i_rep,i_c])
                algo_org.set_params(eta,beta,rho=rhos[i_rep,i_c],nu=nus[i_rep,i_c])

                if not algo.fit():
                    # Algorithm has failed
                    res_fail[i_rep,i_c,i_eta] = 1
                    i_plot = np.random.randint(i_rep+1,rep) # Index of experiment to plot the figure
                if not algo_org.fit():
                    # Algorithm has failed
                    res_fail_org[i_rep,i_c,i_eta] = 1
                    # i_plot = np.random.randint(i_rep+1,rep) # Index of experiment to plot the figure

                y_pred = algo.y
                mpps = algo.mpps # Estimated cluster centers
                # print "     ... Clustering is done. Number of binary search steps = {}\n".format(algo.bs_num)
                y_pred_org = algo_org.y
                mpps_org = algo_org.mpps # Estimated cluster centers

                # For evaluation & plotting, find best permutation of cluster assignment
                y_pred_perm = find_permutation(dataset,algo)
                y_pred_perm_org = find_permutation(dataset,algo_org)

                # Calculate accuracy and mean accuracy
                res_acc[i_rep,i_c,i_eta] = accuracy(y_true,y_pred_perm)
                res_mean_acc[i_rep,i_c,i_eta] = mean_accuracy(y_true,y_pred_perm)
                res_acc_org[i_rep,i_c,i_eta] = accuracy(y_true,y_pred_perm_org)
                res_mean_acc_org[i_rep,i_c,i_eta] = mean_accuracy(y_true,y_pred_perm_org)

                # # Calculate number of errors
                # res_err[i_rep,i_c,i_eta] = error(y_true,y_pred_perm)

                if (i_rep == i_plot) and (m<=2):
                    list_classes = ['Not assigned']
                    for i in xrange(k):
                        list_classes.append('Digit {}'.format(i))
                    title = r"SSAC with {} weak oracle ($\eta={}, \beta={}, \nu={:.2f}, \rho={:.2f}$)".format(
                                weak,eta,beta,nus[i_rep,i_c],rhos[i_rep,i_c])
                    f_name = res_dir+'/fig_n{}_m{}_k{}_c{:03d}_e{:d}.png'.format(n,m,k,int(100*c_dist),int(eta))
                    plot_cluster(X,y_true,y_pred_perm,k,mpps,gamma,
                                 title,f_name,verbose,
                                 classes=list_classes)
                    # title_org = r"SSAC(original) with {} weak oracle ($\eta={}, \beta={}, \rho={:.2f}$)".format(
                    #             weak,eta,beta,rhos[i_rep,i_c])
                    # f_name_org = res_dir+'/fig_org_n{}_m{}_k{}_c{:03d}_e{:d}.png'.format(n,m,k,int(100*c_dist),int(eta))
                    # plot_cluster(X,y_true,y_pred_perm_org,k,mpps_org,gamma,
                    #              title_org,f_name_org,verbose)

    # Write result as table
    print_eval("Accuracy(%)",res_acc,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("acc",n,m,k),weak=weak,params=cs)
    print_eval("Mean Accuracy(%)",res_mean_acc,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("meanacc",n,m,k),weak=weak,params=cs)
    # print_eval("# Error(%)",res_err,qs,etas,
    #            res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("err",n,m,k))
    print_eval("# Failure",res_fail,etas,
               res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("fail",n,m,k),
               is_sum=True,weak=weak,params=cs)

    print_eval("Accuracy(%)",res_acc_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("acc",n,m,k),weak=weak,params=cs)
    print_eval("Mean Accuracy(%)",res_mean_acc_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("meanacc",n,m,k),weak=weak,params=cs)
    # print_eval("# Error(%)",res_err,qs,etas,
    #            res_dir+'/res_{}_n{}_m{}_k{}.csv'.format("err",n,m,k))
    print_eval("# Failure",res_fail_org,etas,
               res_dir+'/res_org_{}_n{}_m{}_k{}.csv'.format("fail",n,m,k),
               is_sum=True,weak=weak,params=cs)

    # if args.isplot:
    # Plot Accuracy vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("acc",n,m,k)
    plot_eval("Accuracy(%)",res_acc,etas,fig_name,weak=weak,params=cs,res_org=res_acc_org)

    # Plot Mean Accuracy vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("meanacc",n,m,k)
    plot_eval("Mean Accuracy(%)",res_mean_acc,etas,fig_name,weak=weak,params=cs,res_org=res_mean_acc_org)

    # Plot Failure vs. eta
    fig_name = res_dir+'/fig_{}_n{}_m{}_k{}.pdf'.format("fail",n,m,k)
    plot_eval("# Failure",res_fail,etas,fig_name,is_sum=True,weak=weak,params=cs,res_org=res_fail_org)

    # # Plot histogram of gammas
    # fig_name = res_dir+'/fig_gamma_hist.pdf'
    # plot_hist(gammas,args.min_gamma,args.max_gamma,fig_name)

    if args.isplot:
        plt.show()

def parse_args():
    def str2bool(v):
        return v.lower() in ('true', '1')

    parser = argparse.ArgumentParser(description=
                        'Test Semi-Supervised Active Clustering with Weak Oracles: Random-weak model')
    # parser.add_argument('-m', dest='m',
    #                     help='Dimension of data points in synthetic data',
    #                     default = 2, type = int)
    parser.add_argument('-rep', dest='rep',
                        help='Number of experiments to repeat',
                        default = 1000, type = int)
    parser.add_argument('-qs', dest='qs',
                        help='Probabilities q (not-sure with 1-q) ex) 0.7,0.85,1',
                        default = '0.7,0.85,1', type = str)
    parser.add_argument('-etas', dest='etas',
                        help='etas: parameter for sampling (phase 1) ex) 10,50',
                        default = '2,5,10,20,30', type = str)
    parser.add_argument('-beta', dest='beta',
                        help='beta: parameter for sampling (phase 2)',
                        default = 1, type = int)
    parser.add_argument('-cs', dest='cs',
                        help='Fractions to set distance-weak parameters (0.5,1] ex) 0.7,0.85,1',
                        default = '0.6,0.8,1', type = str)
    parser.add_argument('-isplot', dest='isplot',
                        help='plot the result: True/False',
                        default = False, type = str2bool)
    parser.add_argument('-verbose', dest='verbose',
                        help='verbose: True/False',
                        default = False, type = str2bool)
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse_args()
    print "Called with args:"
    print args
    sys.exit(main(args))
<|endoftext|>


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

import cPickle as pickle

from django.db import models
from django.test import TestCase

from people.models import Group, Person

class SimpleTest(TestCase):

    fixtures = ['testing']

    def test_manager(self):
        self.failUnless(isinstance(
            Person.objects.minors(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.minors()),
            pks(Person.objects.filter(age__lt=18)))

        self.failUnless(isinstance(
            Person.objects.adults(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.adults()),
            pks(Person.objects.filter(age__gte=18)))

    def test_qset(self):
        self.failUnless(isinstance(
            Person.objects.all().minors(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.all().minors()),
            pks(Person.objects.filter(age__lt=18)))

        self.failUnless(isinstance(
            Person.objects.all().adults(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.all().adults()),
            pks(Person.objects.filter(age__gte=18)))

class RelationTest(TestCase):

    fixtures = ['testing']

    def test(self):
        for group in Group.objects.all():
            self.failUnless(isinstance(
                group.people.all(),
                models.query.QuerySet))

            self.failUnless(isinstance(
                group.people.minors(),
                models.query.QuerySet))

            self.failUnlessEqual(
                pks(group.people.minors()),
                pks(group.people.filter(age__lt=18)))

            self.failUnless(isinstance(
                group.people.adults(),
                models.query.QuerySet))

            self.failUnlessEqual(
                pks(group.people.adults()),
                pks(group.people.filter(age__gte=18)))

class PickleTest(TestCase):

    fixtures = ['testing']

    def assert_pickles(self, qset):
        self.failUnlessEqual(pks(qset),
                             pks(pickle.loads(pickle.dumps(qset))))

    def test(self):
        self.assert_pickles(Person.objects.minors())
        self.assert_pickles(Person.objects.all().minors())
        self.assert_pickles(Person.objects.minors().all())
        self.assert_pickles(Group.objects.all())
        self.assert_pickles(Group.objects.all()[0].people.all())
        self.assert_pickles(Group.objects.all()[0].people.minors())

def pks(qset):
    """Return the list of primary keys for the results of a QuerySet."""

    return sorted(tuple(qset.values_list('pk', flat=True)))
<commit_msg>Added a small regression test to ensure related managers can be used to create objects.<commit_after># -*- coding: utf-8 -*-

import cPickle as pickle

from django.db import models
from django.test import TestCase

from people.models import Group, Person

class SimpleTest(TestCase):

    fixtures = ['testing']

    def test_manager(self):
        self.failUnless(isinstance(
            Person.objects.minors(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.minors()),
            pks(Person.objects.filter(age__lt=18)))

        self.failUnless(isinstance(
            Person.objects.adults(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.adults()),
            pks(Person.objects.filter(age__gte=18)))

    def test_qset(self):
        self.failUnless(isinstance(
            Person.objects.all().minors(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.all().minors()),
            pks(Person.objects.filter(age__lt=18)))

        self.failUnless(isinstance(
            Person.objects.all().adults(),
            models.query.QuerySet))

        self.failUnlessEqual(
            pks(Person.objects.all().adults()),
            pks(Person.objects.filter(age__gte=18)))

class RelationTest(TestCase):

    fixtures = ['testing']

    def test_querying(self):
        for group in Group.objects.all():
            self.failUnless(isinstance(
                group.people.all(),
                models.query.QuerySet))

            self.failUnless(isinstance(
                group.people.minors(),
                models.query.QuerySet))

            self.failUnlessEqual(
                pks(group.people.minors()),
                pks(group.people.filter(age__lt=18)))

            self.failUnless(isinstance(
                group.people.adults(),
                models.query.QuerySet))

            self.failUnlessEqual(
                pks(group.people.adults()),
                pks(group.people.filter(age__gte=18)))

    def test_creation(self):
        group = Group.objects.get(pk=1)
        person = group.people.create(age=32)
        assert person.group_id == group.pk

class PickleTest(TestCase):

    fixtures = ['testing']

    def assert_pickles(self, qset):
        self.failUnlessEqual(pks(qset),
                             pks(pickle.loads(pickle.dumps(qset))))

    def test(self):
        self.assert_pickles(Person.objects.minors())
        self.assert_pickles(Person.objects.all().minors())
        self.assert_pickles(Person.objects.minors().all())
        self.assert_pickles(Group.objects.all())
        self.assert_pickles(Group.objects.all()[0].people.all())
        self.assert_pickles(Group.objects.all()[0].people.minors())

def pks(qset):
    """Return the list of primary keys for the results of a QuerySet."""

    return sorted(tuple(qset.values_list('pk', flat=True)))
<|endoftext|>


<commit_before>"""
******
Tables
******

Table entity

syn.getColumns

syn.getTableColumns

"""
from synapseclient.exceptions import *
from synapseclient.dict_object import DictObject
from synapseclient.utils import id_of, query_limit_and_offset

#COLUMN_TYPES = ['STRING', 'DOUBLE', 'LONG', 'BOOLEAN', 'DATE', 'FILEHANDLEID']
DTYPE_2_TABLETYPE = {'?':'BOOLEAN',
                     'd': 'DOUBLE', 'g': 'DOUBLE', 'e': 'DOUBLE', 'f': 'DOUBLE',
                     'b': 'LONG', 'B': 'LONG', 'h': 'LONG', 'H': 'LONG',
                     'i': 'LONG', 'I': 'LONG', 'l': 'LONG', 'L': 'LONG',
                     'm': 'LONG', 'q': 'LONG', 'Q': 'LONG',
                     'S': 'STRING', 'U': 'STRING', 'O': 'STRING'}

def df2Table(df, tableName, parentProject):
    """Creates a new table from data in pandas data frame.
    parameters: df, tableName, parentProject
    """

    #Create columns:
    cols = list()
    for col in df:
        columnType = DTYPE_2_TABLETYPE[df[col].dtype.char]
        if columnType == 'STRING':
            size = min(1000, max(30, df[col].str.len().max()*1.5))  #Determine lenght of longest string
            cols.append(ColumnModel(name=col, columnType=columnType, maximumSize=size, defaultValue=''))
        else:
            cols.append(ColumnModel(name=col, columnType=columnType))
    cols = [syn.store(col) for col in cols]

    #Create Table
    table1 = Table(name=tableName, columns=cols, parent=parentProject)
    table1 = syn.store(table1)

    #Add data to Table
    for i in range(0, df.shape[0]/250+1):
        start =  i*250
        end = min((i+1)*250, df.shape[0])
        print start, end
        rowset1 = RowSet(columns=cols, table=table1,
                         rows=[Row(list(df.ix[j,:])) for j in range(start,end)])
        rowset1 = syn.store(rowset1)

    return table1

class ColumnModel(DictObject):
    """
    """

    @classmethod
    def getURI(cls, id):
        return '/column/%s' % id

    def __init__(self, **kwargs):
        super(ColumnModel, self).__init__(kwargs)

    def postURI(self):
        return '/column'

# RowSet
# org.sagebionetworks.repo.model.table.RowSet
# headers       ARRAY<STRING>  The list of ColumnModels ID that describes the rows of this set.
# etag          STRING         Any RowSet returned from Synapse will contain the current etag of the change set. To update any rows from a RowSet the etag must be provided with the POST.
# tableId       STRING         The ID of the TableEntity than owns these rows
# rows          ARRAY<Row>     The Rows of this set. The index of each row value aligns with the index of each header.

class RowSet(DictObject):
    """
    """

    @classmethod
    def getURI(cls, id):
        return '/column/%s' % id

    def __init__(self, columns=None, table=None, **kwargs):
        if columns:
            kwargs.setdefault('headers',[]).extend([id_of(column) for column in columns])
        if table:
            kwargs['tableId'] = id_of(table)
        super(RowSet, self).__init__(kwargs)

    def postURI(self):
        return '/entity/{id}/table'.format(id=self['tableId'])

# Row
# org.sagebionetworks.repo.model.table.Row
# values        ARRAY<STRING>  The values for each column of this row.
# rowId         INTEGER        The immutable ID issued to a new row.
# versionNumber INTEGER        The version number of this row. Each row version is immutable, so when a row is updated a new version is created.

class Row(DictObject):

    def __init__(self, values, rowId=None, versionNumber=None):
        super(Row, self).__init__()
        self.values = values
        self.rowId = rowId
        self.versionNumber = versionNumber

# limit
# pagesize
# does asRowSet return the whole thing? just parts?
# convert columns back to their natural types?
# import from CSV
# download CSV

class TableQueryResult(object):

    def __init__(self, synapse, query, countOnly=False, isConsistent=True, hard_limit=1000):
        query, limit, offset = query_limit_and_offset(query, hard_limit=hard_limit)
        self.query = query
        self.limit = limit
        self.offset = offset
        self.syn = synapse

        self.countOnly = countOnly
        self.isConsistent = isConsistent
        self.hard_limit = hard_limit
        self.i = -1

        self.rowset = self.syn._queryTable(
            query=self.query + " limit %s offset %s" % (self.limit, self.offset),
            countOnly=self.countOnly,
            isConsistent=self.isConsistent)

    def etag(self):
        return self.rowset.get('etag', None)

    def headers(self):
        return self.rowset.get('headers', None)

    def tableId(self):
        return self.rowset.get('tableId', None)

    def asDataFrame(self):
        raise NotImplementedError

    def asRowSet(self):
        raise NotImplementedError

    def asInteger(self):
        try:
            return int(self.rowset['rows'][0]['values'][0])
        except:
            raise ValueError("asInteger is only valid for queries such as count queries whose first value is an integer.")

    def __iter__(self):
        return self

    def next(self):
        self.i += 1
        if self.i >= len(self.rowset['rows']):
            if len(self.rowset['rows']) < self.limit:
                raise StopIteration()
            else:
                self.offset += self.i
                self.i = 0
                self.rowset = self.syn._queryTable(
                    query=self.query + " limit %s offset %s" % (self.limit, self.offset),
                    countOnly=self.countOnly,
                    isConsistent=self.isConsistent)
        return self.rowset['rows'][self.i]

<commit_msg>Adds missing synapse object for tables.<commit_after>"""
******
Tables
******

Table entity

syn.getColumns

syn.getTableColumns

"""
from synapseclient.exceptions import *
from synapseclient.dict_object import DictObject
from synapseclient.utils import id_of, query_limit_and_offset
from synapseclient.entity import Table

#COLUMN_TYPES = ['STRING', 'DOUBLE', 'LONG', 'BOOLEAN', 'DATE', 'FILEHANDLEID']
DTYPE_2_TABLETYPE = {'?':'BOOLEAN',
                     'd': 'DOUBLE', 'g': 'DOUBLE', 'e': 'DOUBLE', 'f': 'DOUBLE',
                     'b': 'LONG', 'B': 'LONG', 'h': 'LONG', 'H': 'LONG',
                     'i': 'LONG', 'I': 'LONG', 'l': 'LONG', 'L': 'LONG',
                     'm': 'LONG', 'q': 'LONG', 'Q': 'LONG',
                     'S': 'STRING', 'U': 'STRING', 'O': 'STRING'}

def df2Table(df, syn,  tableName, parentProject):
    """Creates a new table from data in pandas data frame.
    parameters: df, tableName, parentProject
    """

    #Create columns:
    print df.shape
    cols = list()
    for col in df:
        columnType = DTYPE_2_TABLETYPE[df[col].dtype.char]
        if columnType == 'STRING':
            size = min(1000, max(30, df[col].str.len().max()*1.5))  #Determine lenght of longest string
            cols.append(ColumnModel(name=col, columnType=columnType, maximumSize=size, defaultValue=''))
        else:
            cols.append(ColumnModel(name=col, columnType=columnType))
    cols = [syn.store(col) for col in cols]

    #Create Table
    table1 = Table(name=tableName, columns=cols, parent=parentProject)
    table1 = syn.store(table1)

    #Add data to Table
    for i in range(0, df.shape[0]/1200+1):
        start =  i*1200
        end = min((i+1)*1200, df.shape[0])
        print start, end
        rowset1 = RowSet(columns=cols, table=table1,
                         rows=[Row(list(df.ix[j,:])) for j in range(start,end)])
        #print len(rowset1.rows)
        rowset1 = syn.store(rowset1)

    return table1

class ColumnModel(DictObject):
    """
    """

    @classmethod
    def getURI(cls, id):
        return '/column/%s' % id

    def __init__(self, **kwargs):
        super(ColumnModel, self).__init__(kwargs)

    def postURI(self):
        return '/column'

# RowSet
# org.sagebionetworks.repo.model.table.RowSet
# headers       ARRAY<STRING>  The list of ColumnModels ID that describes the rows of this set.
# etag          STRING         Any RowSet returned from Synapse will contain the current etag of the change set. To update any rows from a RowSet the etag must be provided with the POST.
# tableId       STRING         The ID of the TableEntity than owns these rows
# rows          ARRAY<Row>     The Rows of this set. The index of each row value aligns with the index of each header.

class RowSet(DictObject):
    """
    """

    @classmethod
    def getURI(cls, id):
        return '/column/%s' % id

    def __init__(self, columns=None, table=None, **kwargs):
        if columns:
            kwargs.setdefault('headers',[]).extend([id_of(column) for column in columns])
        if table:
            kwargs['tableId'] = id_of(table)
        super(RowSet, self).__init__(kwargs)

    def postURI(self):
        return '/entity/{id}/table'.format(id=self['tableId'])

# Row
# org.sagebionetworks.repo.model.table.Row
# values        ARRAY<STRING>  The values for each column of this row.
# rowId         INTEGER        The immutable ID issued to a new row.
# versionNumber INTEGER        The version number of this row. Each row version is immutable, so when a row is updated a new version is created.

class Row(DictObject):

    def __init__(self, values, rowId=None, versionNumber=None):
        super(Row, self).__init__()
        self.values = values
        self.rowId = rowId
        self.versionNumber = versionNumber

# limit
# pagesize
# does asRowSet return the whole thing? just parts?
# convert columns back to their natural types?
# import from CSV
# download CSV

class TableQueryResult(object):

    def __init__(self, synapse, query, countOnly=False, isConsistent=True, hard_limit=1000):
        query, limit, offset = query_limit_and_offset(query, hard_limit=hard_limit)
        self.query = query
        self.limit = limit
        self.offset = offset
        self.syn = synapse

        self.countOnly = countOnly
        self.isConsistent = isConsistent
        self.hard_limit = hard_limit
        self.i = -1

        self.rowset = self.syn._queryTable(
            query=self.query + " limit %s offset %s" % (self.limit, self.offset),
            countOnly=self.countOnly,
            isConsistent=self.isConsistent)

    def etag(self):
        return self.rowset.get('etag', None)

    def headers(self):
        return self.rowset.get('headers', None)

    def tableId(self):
        return self.rowset.get('tableId', None)

    def asDataFrame(self):
        raise NotImplementedError

    def asRowSet(self):
        raise NotImplementedError

    def asInteger(self):
        try:
            return int(self.rowset['rows'][0]['values'][0])
        except:
            raise ValueError("asInteger is only valid for queries such as count queries whose first value is an integer.")

    def __iter__(self):
        return self

    def next(self):
        self.i += 1
        if self.i >= len(self.rowset['rows']):
            if len(self.rowset['rows']) < self.limit:
                raise StopIteration()
            else:
                self.offset += self.i
                self.i = 0
                self.rowset = self.syn._queryTable(
                    query=self.query + " limit %s offset %s" % (self.limit, self.offset),
                    countOnly=self.countOnly,
                    isConsistent=self.isConsistent)
        return self.rowset['rows'][self.i]

<|endoftext|>