<commit_before>import pygame, game, sys, os, utils, animation
util = utils.Utils()

class Menu(object):

	def __init__(self, screen, clock, fps, resolution, version):
		self.screen = screen
		self.clock = clock
		self.fps = fps
		self.resolution = resolution
		self.halfResolution = (self.resolution[0] // 2, self.resolution[1] // 2)
		self.version = version

		self.running = True

		self.img = pygame.image.load("assets/sprites/menu.png").convert_alpha()
		self.imgSmall = pygame.image.load("assets/sprites/menuSmall.png").convert_alpha()

		for anim in os.listdir("assets/characters/player"):
			info = anim[:anim.find(".")].split("+")
			if info[0] == "standingRight":
				self.logo = animation.Animation("assets/characters/player/%s" % anim, 50, 50, float(info[1]), float(info[2]))
				self.splice = self.logo.getSplice()

		self.background = pygame.image.load("assets/sprites/backgrounds/world1.png").convert_alpha()
		self.bgPos = (0, 0)

		self.mediumFont = pygame.font.Font("assets/ARLRDBD.ttf", 30)
		self.bigFont = pygame.font.Font("assets/ARLRDBD.ttf", 72)

		self.mainText = self.bigFont.render("Layer Switcher", 1, (0, 0, 0))
		self.versionText = self.mediumFont.render(self.version, 1, (0, 0, 0))

		self.currentMenu = ""

		self.mainMenu()

		while self.running:
			dt = self.clock.tick(self.fps)
			pygame.display.set_caption("Layer Switcher %3d FPS" % (self.clock.get_fps()), "Layer Switcher")

			mouseTrigger = False

			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					self.leave()

				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						if self.currentMenu == "main":
							self.leave()
						else:
							self.mainMenu()

					if event.key == pygame.K_SPACE:
						self.start()

				if event.type == pygame.MOUSEBUTTONUP:
					if event.button == 1:
						mouseTrigger = True

			self.screen.fill((82, 246, 255))

			mPos = pygame.mouse.get_pos()

			self.bgPos = (
				-util.remap(mPos[0], 0, self.resolution[0], 0, self.background.get_width() - self.resolution[0]),
				-util.remap(mPos[1], 0, self.resolution[1], 0, self.background.get_height() - self.resolution[1])
			)

			self.screen.blit(self.background, self.bgPos)
			self.screen.blit(self.mainText, (self.halfResolution[0] - self.mainText.get_width() // 2, 100))
			self.screen.blit(self.versionText, (5, self.resolution[1] - self.versionText.get_height() - 5))

			if self.currentMenu == "main":
				self.logo.update(dt * 0.001)
				self.screen.blit(self.splice, (self.halfResolution[0] - self.splice.get_width() // 2, 270))

			for opt in Option.group:
				opt.updateAndDraw(self.screen, mPos, mouseTrigger)

			pygame.display.flip()

	def mainMenu(self):
		self.currentMenu = "main"

		Option.group = []

		Option(self.img, self.mediumFont, "Start", (0, self.resolution[1] - 300), self.resolution, self.start)
		Option(self.img, self.mediumFont, "Options", (0, self.resolution[1] - 225), self.resolution, self.options)
		Option(self.img, self.mediumFont, "Quit", (0, self.resolution[1] - 150), self.resolution, self.leave)

	def options(self):
		self.currentMenu = "options"

		Option.group = []

		Option(None, self.mediumFont, "Set FPS:", (0, self.resolution[1] - 385), self.resolution, None)
		Option(self.imgSmall, self.mediumFont, "30", (-125, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(30.))
		Option(self.imgSmall, self.mediumFont, "60", (0, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(60.))
		Option(self.imgSmall, self.mediumFont, "120", (125, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(120.))

		Option(None, self.mediumFont, "Music volume:", (0, self.resolution[1] - 275), self.resolution, None)
		Option(self.imgSmall, self.mediumFont, "-", (-75, self.resolution[1] - 225), self.resolution, self.lowerVolume)
		Option(self.imgSmall, self.mediumFont, "+", (75, self.resolution[1] - 225), self.resolution, self.raiseVolume)

		Option(self.img, self.mediumFont, "Back", (0, self.resolution[1] - 150), self.resolution, self.mainMenu)

	def setFPS(self, fps):
		self.fps = fps

	def lowerVolume(self):
		new = pygame.mixer.music.get_volume() - 0.05
		pygame.mixer.music.set_volume(new)

	def raiseVolume(self):
		new = pygame.mixer.music.get_volume() + 0.05
		pygame.mixer.music.set_volume(new)

	def start(self):
		self.game = game.Game(self.screen, self.clock, self.fps, self.mediumFont, self.resolution, self.halfResolution)

	def leave(self):
		self.running = False
		pygame.quit()
		sys.exit(0)

class Option(object):
	group = []

	def __init__(self, img, font, text, pos, resolution, callback):
		self.text = font.render(text, 1, (0, 0, 0))
		self.textSize = font.size(text)

		if img:
			self.position = pygame.rect.Rect((resolution[0] // 2 - img.get_width() // 2 + pos[0], pos[1]), img.get_size())
			self.callback = callback

			self.img = img
			self.overlay = pygame.Surface(img.get_size(), pygame.SRCALPHA)
			self.overlay.fill((255, 255, 255, 60))
			self.overlay.convert_alpha()

		else:
			self.img = None
			self.position = pygame.rect.Rect((resolution[0] // 2 - self.textSize[0] // 2 + pos[0], pos[1]), self.textSize)

		Option.group.append(self)

	def updateAndDraw(self, screen, mPos, trigger):
		if self.img:
			screen.blit(self.img, self.position.topleft)

		screen.blit(self.text, (self.position.centerx - self.textSize[0] // 2, self.position.centery - self.textSize[1] // 2))

		if mPos[0] in xrange(self.position.left, self.position.right) and mPos[1] in xrange(self.position.top, self.position.bottom) and self.img:
			screen.blit(self.overlay, self.position.topleft)

			if trigger:
				self.callback()
<commit_msg>volume is now a variable and not a mixer.music.get_volume hack<commit_after>import pygame, game, sys, os, utils, animation
util = utils.Utils()

class Menu(object):

	def __init__(self, screen, clock, fps, resolution, version):
		self.screen = screen
		self.clock = clock
		self.fps = fps
		self.resolution = resolution
		self.halfResolution = (self.resolution[0] // 2, self.resolution[1] // 2)
		self.version = version
		self.volume = pygame.mixer.music.get_volume()

		self.running = True

		self.img = pygame.image.load("assets/sprites/menu.png").convert_alpha()
		self.imgSmall = pygame.image.load("assets/sprites/menuSmall.png").convert_alpha()

		for anim in os.listdir("assets/characters/player"):
			info = anim[:anim.find(".")].split("+")
			if info[0] == "standingRight":
				self.logo = animation.Animation("assets/characters/player/%s" % anim, 50, 50, float(info[1]), float(info[2]))
				self.splice = self.logo.getSplice()

		self.background = pygame.image.load("assets/sprites/backgrounds/world1.png").convert_alpha()
		self.bgPos = (0, 0)

		self.mediumFont = pygame.font.Font("assets/ARLRDBD.ttf", 30)
		self.bigFont = pygame.font.Font("assets/ARLRDBD.ttf", 72)

		self.mainText = self.bigFont.render("Layer Switcher", 1, (0, 0, 0))
		self.versionText = self.mediumFont.render(self.version, 1, (0, 0, 0))

		self.currentMenu = ""

		self.mainMenu()

		while self.running:
			dt = self.clock.tick(self.fps)
			pygame.display.set_caption("Layer Switcher %3d FPS" % (self.clock.get_fps()), "Layer Switcher")

			mouseTrigger = False

			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					self.leave()

				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						if self.currentMenu == "main":
							self.leave()
						else:
							self.mainMenu()

					if event.key == pygame.K_SPACE:
						self.start()

				if event.type == pygame.MOUSEBUTTONUP:
					if event.button == 1:
						mouseTrigger = True

			self.screen.fill((82, 246, 255))

			mPos = pygame.mouse.get_pos()

			self.bgPos = (
				-util.remap(mPos[0], 0, self.resolution[0], 0, self.background.get_width() - self.resolution[0]),
				-util.remap(mPos[1], 0, self.resolution[1], 0, self.background.get_height() - self.resolution[1])
			)

			self.screen.blit(self.background, self.bgPos)
			self.screen.blit(self.mainText, (self.halfResolution[0] - self.mainText.get_width() // 2, 100))
			self.screen.blit(self.versionText, (5, self.resolution[1] - self.versionText.get_height() - 5))

			if self.currentMenu == "main":
				self.logo.update(dt * 0.001)
				self.screen.blit(self.splice, (self.halfResolution[0] - self.splice.get_width() // 2, 270))

			for opt in Option.group:
				opt.updateAndDraw(self.screen, mPos, mouseTrigger)

			pygame.display.flip()

	def mainMenu(self):
		self.currentMenu = "main"

		Option.group = []

		Option(self.img, self.mediumFont, "Start", (0, self.resolution[1] - 300), self.resolution, self.start)
		Option(self.img, self.mediumFont, "Options", (0, self.resolution[1] - 225), self.resolution, self.options)
		Option(self.img, self.mediumFont, "Quit", (0, self.resolution[1] - 150), self.resolution, self.leave)

	def options(self):
		self.currentMenu = "options"

		Option.group = []

		Option(None, self.mediumFont, "Set FPS:", (0, self.resolution[1] - 385), self.resolution, None)
		Option(self.imgSmall, self.mediumFont, "30", (-125, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(30.))
		Option(self.imgSmall, self.mediumFont, "60", (0, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(60.))
		Option(self.imgSmall, self.mediumFont, "120", (125, self.resolution[1] - 335), self.resolution, lambda: self.setFPS(120.))

		Option(None, self.mediumFont, "Music volume:", (0, self.resolution[1] - 275), self.resolution, None)
		Option(self.imgSmall, self.mediumFont, "-", (-75, self.resolution[1] - 225), self.resolution, self.lowerVolume)
		Option(self.imgSmall, self.mediumFont, "+", (75, self.resolution[1] - 225), self.resolution, self.raiseVolume)

		Option(self.img, self.mediumFont, "Back", (0, self.resolution[1] - 150), self.resolution, self.mainMenu)

	def setFPS(self, fps):
		self.fps = fps

	def lowerVolume(self):
		self.volume = max(0, self.volume - 0.05)
		pygame.mixer.music.set_volume(self.volume)

	def raiseVolume(self):
		self.volume = min(1, self.volume + 0.05)
		pygame.mixer.music.set_volume(self.volume)

	def start(self):
		self.game = game.Game(self.screen, self.clock, self.fps, self.mediumFont, self.resolution, self.halfResolution)

	def leave(self):
		self.running = False
		pygame.quit()
		sys.exit(0)

class Option(object):
	group = []

	def __init__(self, img, font, text, pos, resolution, callback):
		self.text = font.render(text, 1, (0, 0, 0))
		self.textSize = font.size(text)

		if img:
			self.position = pygame.rect.Rect((resolution[0] // 2 - img.get_width() // 2 + pos[0], pos[1]), img.get_size())
			self.callback = callback

			self.img = img
			self.overlay = pygame.Surface(img.get_size(), pygame.SRCALPHA)
			self.overlay.fill((255, 255, 255, 60))
			self.overlay.convert_alpha()

		else:
			self.img = None
			self.position = pygame.rect.Rect((resolution[0] // 2 - self.textSize[0] // 2 + pos[0], pos[1]), self.textSize)

		Option.group.append(self)

	def updateAndDraw(self, screen, mPos, trigger):
		if self.img:
			screen.blit(self.img, self.position.topleft)

		screen.blit(self.text, (self.position.centerx - self.textSize[0] // 2, self.position.centery - self.textSize[1] // 2))

		if mPos[0] in xrange(self.position.left, self.position.right) and mPos[1] in xrange(self.position.top, self.position.bottom) and self.img:
			screen.blit(self.overlay, self.position.topleft)

			if trigger:
				self.callback()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar

from allink_core.allink_base.utils import AllinkBaseModifierMixin
from allink_core.allink_config.models import AllinkConfig
from allink_apps.blog.models import News, Events, EventsRegistration

class NewsToolbar(AllinkBaseModifierMixin, CMSToolbar):
    model = News
    app_label = News._meta.app_label

if AllinkConfig.get_solo().news_toolbar_enabled:
    toolbar_pool.register(NewsToolbar)

class EventsToolbar(AllinkBaseModifierMixin, CMSToolbar):
    model = Events
    app_label = Events._meta.app_label

if AllinkConfig.get_solo().events_toolbar_enabled:
    toolbar_pool.register(EventsToolbar)

class EventsRegistrationToolbar(CMSToolbar):
    model = EventsRegistration

    def populate(self):
        menu = self.toolbar.get_or_create_menu('form-menu', _('Forms'))

        url = reverse('admin:{}_{}_changelist'.format(self.model._meta.app_label, self.model._meta.model_name))
        menu.add_sideframe_item(self.model.get_verbose_name_plural(), url=url)

if AllinkConfig.get_solo().events_registration_toolbar_enabled:
    toolbar_pool.register(EventsRegistrationToolbar)
<commit_msg>caching<commit_after># -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar

from allink_core.allink_base.utils import AllinkBaseModifierMixin
from allink_core.allink_config.models import AllinkConfig
from allink_apps.blog.models import News, Events, EventsRegistration

config = AllinkConfig.get_solo()

class NewsToolbar(AllinkBaseModifierMixin, CMSToolbar):
    model = News
    app_label = News._meta.app_label

if config.news_toolbar_enabled:
    toolbar_pool.register(NewsToolbar)

class EventsToolbar(AllinkBaseModifierMixin, CMSToolbar):
    model = Events
    app_label = Events._meta.app_label

if config.events_toolbar_enabled:
    toolbar_pool.register(EventsToolbar)

class EventsRegistrationToolbar(CMSToolbar):
    model = EventsRegistration

    def populate(self):
        menu = self.toolbar.get_or_create_menu('form-menu', _('Forms'))

        url = reverse('admin:{}_{}_changelist'.format(self.model._meta.app_label, self.model._meta.model_name))
        menu.add_sideframe_item(self.model.get_verbose_name_plural(), url=url)

if config.events_registration_toolbar_enabled:
    toolbar_pool.register(EventsRegistrationToolbar)
<|endoftext|>


<commit_before>from oscar.apps.shipping.methods import Free

class Repository(object):
    """
    Repository class responsible for returning ShippingMethod
    objects for a given user, basket etc
    """

    def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):
        """
        Return a list of all applicable shipping method objects
        for a given basket.

        We default to returning the Method models that have been defined but
        this behaviour can easily be overridden by subclassing this class
        and overriding this method.
        """
        methods = [Free()]
        return self.add_basket_to_methods(basket, methods)

    def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs):
        return self.get_shipping_methods(user, basket, shipping_addr, **kwargs)[0]

    def add_basket_to_methods(self, basket, methods):
        for method in methods:
            method.set_basket(basket)
        return methods

    def find_by_code(self, code):
        """
        Return the appropriate Method object for the given code
        """
        if code == Free.code:
            return Free()
        return None
<commit_msg>Added exception to handle case where there are no shipping methods available<commit_after>from django.core.exceptions import ImproperlyConfigured
from oscar.apps.shipping.methods import Free

class Repository(object):
    """
    Repository class responsible for returning ShippingMethod
    objects for a given user, basket etc
    """

    def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):
        """
        Return a list of all applicable shipping method objects
        for a given basket.

        We default to returning the Method models that have been defined but
        this behaviour can easily be overridden by subclassing this class
        and overriding this method.
        """
        methods = [Free()]
        return self.add_basket_to_methods(basket, methods)

    def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs):
        methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs)
        if len(methods) == 0:
            raise ImproperlyConfigured("You need to define some shipping methods")
        return methods[0]

    def add_basket_to_methods(self, basket, methods):
        for method in methods:
            method.set_basket(basket)
        return methods

    def find_by_code(self, code):
        """
        Return the appropriate Method object for the given code
        """
        if code == Free.code:
            return Free()
        return None
<|endoftext|>


<commit_before>"""
Creates a colorized kmeans cluster of crime in Washington, DC.
Attempted to add pop-ups but there are too many co-located
points. Data for kmeans is all numeric except for the input
crime labels. All data was normalized and coordinates are
in WGS 84. Data will not load into ArcGIS online - the site
usually crashes.
"""

import os
import time
import numpy as np
import pandas as pd
from conf import settings
from datetime import datetime
from bokeh.charts import Scatter
from sklearn.cluster import KMeans
from collections import OrderedDict
from bokeh.plotting import output_file
from sklearn.preprocessing import Imputer

#Create a timestamp for the output file
def time_stamp():
    """
    Creates mm-dd-yyyy timestamp
    """
    now = time.time()
    return datetime.fromtimestamp(now).strftime("%m%d%Y")

def create_ordered_dict(data_frame, group_by, x_field="X", y_field="Y"):
    """
    puts data into a dicitonary for Bokeh.
    """
    pdict = OrderedDict()

    g = data_frame.groupby(group_by)

    for i in g.groups.keys():
        lat = getattr(g.get_group(i), y_field)
        lng = getattr(g.get_group(i), x_field)
        pdict[i] = zip(lat,lng)
    return pdict

def main():
    """
    This function will
        -load data from a csv
        -impute missing data with the column's mean
        -perform kmneans clustering
        -produce an html scatter plot
    """

    #load data from a CSV to a dataframe
    with open(settings["crime_data"]) as in_data:
        crime_data = pd.DataFrame.from_csv(in_data, sep=',')

    crime_data=crime_data.fillna(value=-999)

    #load all numeric data into an array. The offense column from the crime data
    #is excluded
    as_array = np.asfarray(crime_data[["X","Y"]])

    #number of groups
    n_clusters=40

    #Correct missing data
    imputer = Imputer(missing_values=-999, strategy="mean")
    patched = imputer.fit_transform(as_array)

    #cluster data
    cluster = KMeans(n_clusters=n_clusters)
    cluster.fit(patched)

    #assigned grouped labels to the crime data
    labels = cluster.labels_
    crime_data["labels"]=labels

    pdict = create_ordered_dict(crime_data, "labels")

    crime_data.to_csv(r'C:\users\andrew_woizesko\desktop\knn.csv')
    np.savetxt(r'C:\users\andrew_woizesko\desktop\centers.csv', cluster.cluster_centers_)

#    #location of output graph
#    file_name = os.path.join("..", 'tests', "kmeans_clusters_{0}.html".format(time_stamp()))
#    output_file(file_name)
#
#    #create out graph
#    TOOLS="pan,wheel_zoom,box_zoom,reset"
#    scatter = Scatter(pdict.values(), title="Crime Clusters", filename=file_name, tools=TOOLS)
#    scatter.show()

if __name__ == "__main__":
    main()<commit_msg>un-commented viz<commit_after>"""
Creates a colorized kmeans cluster of crime in Washington, DC.
Attempted to add pop-ups but there are too many co-located
points. Data for kmeans is all numeric except for the input
crime labels. All data was normalized and coordinates are
in WGS 84. Data will not load into ArcGIS online - the site
usually crashes.
"""

import os
import time
import numpy as np
import pandas as pd
from conf import settings
from datetime import datetime
from bokeh.charts import Scatter
from sklearn.cluster import KMeans
from collections import OrderedDict
from bokeh.plotting import output_file
from sklearn.preprocessing import Imputer

#Create a timestamp for the output file
def time_stamp():
    """
    Creates mm-dd-yyyy timestamp
    """
    now = time.time()
    return datetime.fromtimestamp(now).strftime("%m%d%Y")

def create_ordered_dict(data_frame, group_by, x_field="X", y_field="Y"):
    """
    puts data into a dicitonary for Bokeh.
    """
    pdict = OrderedDict()

    g = data_frame.groupby(group_by)

    for i in g.groups.keys():
        lat = getattr(g.get_group(i), y_field)
        lng = getattr(g.get_group(i), x_field)
        pdict[i] = zip(lat,lng)
    return pdict

def main():
    """
    This function will
        -load data from a csv
        -impute missing data with the column's mean
        -perform kmneans clustering
        -produce an html scatter plot
    """

    #load data from a CSV to a dataframe
    with open(settings["crime_data"]) as in_data:
        crime_data = pd.DataFrame.from_csv(in_data, sep=',')

    crime_data=crime_data.fillna(value=-999)

    #load all numeric data into an array. The offense column from the crime data
    #is excluded
    as_array = np.asfarray(crime_data[["X","Y"]])

    #number of groups
    n_clusters=40

    #Correct missing data
    imputer = Imputer(missing_values=-999, strategy="mean")
    patched = imputer.fit_transform(as_array)

    #cluster data
    cluster = KMeans(n_clusters=n_clusters)
    cluster.fit(patched)

    #assigned grouped labels to the crime data
    labels = cluster.labels_
    crime_data["labels"]=labels

    pdict = create_ordered_dict(crime_data, "labels")

    crime_data.to_csv(r'C:\users\andrew_woizesko\desktop\knn.csv')
    np.savetxt(r'C:\users\andrew_woizesko\desktop\centers.csv', cluster.cluster_centers_)

    #location of output graph
    file_name = os.path.join("..", 'tests', "kmeans_clusters_{0}.html".format(time_stamp()))
    output_file(file_name)

    #create out graph
    TOOLS="pan,wheel_zoom,box_zoom,reset"
    scatter = Scatter(pdict.values(), title="Crime Clusters", filename=file_name, tools=TOOLS)
    scatter.show()

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


<commit_before>""" Stores functions for rendering menus with Urwid.
"""

import urwid

class Menu():
    def __init__(self, collections):
        self.collections = collections
        self.main = urwid.Padding(
            self.selection_menu(u'Spaced Repetition', collections, self.choose_slide),
            left = 2, right = 2)

        self.top = urwid.Overlay(self.main,
            urwid.SolidFill(u'\N{MEDIUM SHADE}'),
            align = 'center', width = ('relative', 60),
            valign = 'middle', height = ('relative', 60),
            min_width = 20, min_height = 9)

    def run(self):
        urwid.MainLoop(self.top, palette=[('reversed', 'standout', '')]).run()

    def exit_program(self, button):
        raise urwid.ExitMainLoop()

    # ----------------------------------------
    # Specific menu screens

    def item_chosen(self, button, choice):
        response = urwid.Text([u'You chose ', str(choice), u'\n'])
        done = urwid.Button(u'Ok')

        urwid.connect_signal(done, 'click', self.exit_program)
        self.main.original_widget = urwid.Filler(urwid.Pile([
            response, urwid.AttrMap(done, None, focus_map='reversed')]))

    def choose_slide(self, button, collection):
        self.main.original_widget = urwid.Padding(
            self.selection_menu(
                collection.name,
                collection.slides,
                self.item_chosen))

    def choose_collection(self, button):
        self.main.original_widget = urwid.Padding(
            self.selection_menu(
                'Choose a collection',
                self.collections,
                self.choose_slide))

    # ----------------------------------------
    # Constructors for menu structures

    def selection_menu(self, title, choices, callback):
        body = [urwid.Text(title), urwid.Divider()]

        for c in choices:
            button = urwid.Button(str(c))

            urwid.connect_signal(button, 'click', callback, c)
            body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        return urwid.ListBox(urwid.SimpleFocusListWalker(body))
<commit_msg>Add support for navigation menus and dialogue menus.<commit_after>""" Stores functions for rendering menus with Urwid.
"""

import urwid
from collection import Collection

class Menu():
    def __init__(self, collections):
        self.collections = collections
        options = [
            ('New Collection', self.new_collection),
            ('Study Collection', self.choose_collection),
            ('Edit Collection', self.choose_collection)]

        self.main = urwid.Padding(
            self.router_menu(u'Spaced Repetition', options),
            left = 2, right = 2)

        self.top = urwid.Overlay(self.main,
            urwid.SolidFill(u'\N{MEDIUM SHADE}'),
            align = 'center', width = ('relative', 60),
            valign = 'middle', height = ('relative', 60),
            min_width = 20, min_height = 9)

    def run(self):
        """ Runs the menu system """
        urwid.MainLoop(self.top, palette=[('reversed', 'standout', '')]).run()

    def exit(self, button):
        """ Exits the menu system """
        raise urwid.ExitMainLoop()

    # ----------------------------------------
    # Specific menu screens

    def main(self):
        options = [
            ('New Collection', self.new_collection),
            ('Study Collection', self.choose_collection),
            ('Edit Collection', self.choose_collection)]

        self.main.original_widget = urwid.Padding(
            self.router_menu(u'Spaced Repetition', options))

    def item_chosen(self, button, choice):
        response = urwid.Text([u'You chose ', str(choice), u'\n'])
        done = urwid.Button(u'Ok')

        urwid.connect_signal(done, 'click', self.exit)
        self.main.original_widget = urwid.Filler(urwid.Pile([
            response, urwid.AttrMap(done, None, focus_map='reversed')]))

    def choose_slide(self, button, collection):
        self.main.original_widget = urwid.Padding(
            self.selection_menu(
                collection.name,
                collection.slides,
                self.item_chosen))

    def choose_collection(self, button):
        self.main.original_widget = urwid.Padding(
            self.selection_menu(
                'Choose a collection',
                self.collections,
                self.choose_slide))

    def new_collection(self, button):
        """ Render the menu for creating a new Collection """

        def do_new_collection(button, dialogue_menu):
            """ Create a new collection with the data from the
                'new_collection' menu.
            """

            # TODO: Rewrite this function to create a new Collection. This is
            # just a stand-in.
            fields = dialogue_menu.get_fields()

            self.item_chosen(button,
                "\nName: " + fields['Name']
                + "\nDescription: " + fields['Description'])

        menu = DialogueMenu(
                'Choose a collection',
                ['Name', 'Description'],
                do_new_collection,
                self.main)

        self.main.original_widget = urwid.Padding(menu.get_widget())

    # ----------------------------------------
    # Constructors for menu structures

    def selection_menu(self, title, choices, callback):
        body = [urwid.Text(title), urwid.Divider()]

        for c in choices:
            button = urwid.Button(str(c), callback, c)

            body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        return urwid.ListBox(urwid.SimpleFocusListWalker(body))

    def router_menu(self, title, choices):
        body = [urwid.Text(title), urwid.Divider()]

        for c in choices:
            button = urwid.Button(str(c[0]), c[1])

            body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        return urwid.ListBox(urwid.SimpleFocusListWalker(body))

class DialogueMenu:
    # TODO: Turn this class into a functional Urwid Widget?

    def __init__(self, title, field_labels, forward, back):
        """ Variables:
            title           string      Title of the menu.
            field_labels    array       Array of strings -- labels for the
                                        edit widgets which make up the menu.
            forward         function    Called when 'OK' button is pressed.
            back            function    Called when 'Cancel' button is
                                        pressed.
        """

        self._field_widgets = []

        self.body = [urwid.Text(title), urwid.Divider()]
        ok = urwid.Button("OK", forward, self)
        cancel = urwid.Button("Cancel", back, self)

        # Add Edit widgets (fields)
        for field in field_labels:
            widget = self._dialogue_box(field)

            self.body.append(urwid.AttrMap(
                widget, None, focus_map='reversed'))
            self._field_widgets.append(widget)

        # Add OK and Cancel buttons
        self.body.append(urwid.AttrMap(ok, None, focus_map='reversed'))
        self.body.append(urwid.AttrMap(cancel, None, focus_map='reversed'))

    def get_widget(self):
        """ Returns a renderable widget representing the Dialogue Menu. """
        return urwid.ListBox(urwid.SimpleFocusListWalker(self.body))

    def get_fields(self):
        """ Returns the contents of all the dialogue boxes in a dictionary
            with the form, {"label", "contents"}
        """

        fields = {}
        for widget in self._field_widgets:
            label = widget.caption
            contents = widget.get_edit_text()
            fields[label] = contents

        return fields

    def _dialogue_box(self, query):
        # Constructs a widget for a dialogue box.
        return urwid.Edit(('I say', query))

<|endoftext|>


<commit_before>"""distutils.command.build

Implements the Distutils 'build' command."""

# created 1999/03/08, Greg Ward

__revision__ = "$Id$"

import sys, os
from distutils.core import Command
from distutils.util import get_platform

def show_compilers ():
    from distutils.ccompiler import show_compilers
    show_compilers()

class build (Command):

    description = "build everything needed to install"

    user_options = [
        ('build-base=', 'b',
         "base directory for build library"),
        ('build-purelib=', None,
         "build directory for platform-neutral distributions"),
        ('build-platlib=', None,
         "build directory for platform-specific distributions"),
        ('build-lib=', None,
         "build directory for all distribution (defaults to either " +
         "build-purelib or build-platlib"),
        ('build-scripts=', None,
         "build directory for scripts"),
        ('build-temp=', 't',
         "temporary build directory"),
        ('compiler=', 'c',
         "specify the compiler type"),
        ('debug', 'g',
         "compile extensions and libraries with debugging information"),
        ('force', 'f',
         "forcibly build everything (ignore file timestamps)"),
        ]

    boolean_options = ['debug', 'force']

    help_options = [
        ('help-compiler', None,
         "list available compilers", show_compilers),
        ]

    def initialize_options (self):
        self.build_base = 'build'
        # these are decided only after 'build_base' has its final value
        # (unless overridden by the user or client)
        self.build_purelib = None
        self.build_platlib = None
        self.build_lib = None
        self.build_temp = None
        self.build_scripts = None
        self.compiler = None
        self.debug = None
        self.force = 0

    def finalize_options (self):

        plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])

        # 'build_purelib' and 'build_platlib' just default to 'lib' and
        # 'lib.<plat>' under the base build directory.  We only use one of
        # them for a given distribution, though --
        if self.build_purelib is None:
            self.build_purelib = os.path.join(self.build_base, 'lib')
        if self.build_platlib is None:
            self.build_platlib = os.path.join(self.build_base,
                                              'lib' + plat_specifier)

        # 'build_lib' is the actual directory that we will use for this
        # particular module distribution -- if user didn't supply it, pick
        # one of 'build_purelib' or 'build_platlib'.
        if self.build_lib is None:
            if self.distribution.ext_modules:
                self.build_lib = self.build_platlib
            else:
                self.build_lib = self.build_purelib

        # 'build_temp' -- temporary directory for compiler turds,
        # "build/temp.<plat>"
        if self.build_temp is None:
            self.build_temp = os.path.join(self.build_base,
                                           'temp' + plat_specifier)
        if self.build_scripts is None:
            self.build_scripts = os.path.join(self.build_base, 'scripts')

    # finalize_options ()

    def run (self):

        # Run all relevant sub-commands.  This will be some subset of:
        #  - build_py      - pure Python modules
        #  - build_clib    - standalone C libraries
        #  - build_ext     - Python extensions
        #  - build_scripts - (Python) scripts
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

    # -- Predicates for the sub-command list ---------------------------

    def has_pure_modules (self):
        return self.distribution.has_pure_modules()

    def has_c_libraries (self):
        return self.distribution.has_c_libraries()

    def has_ext_modules (self):
        return self.distribution.has_ext_modules()

    def has_scripts (self):
        return self.distribution.has_scripts()

    sub_commands = [('build_py',      has_pure_modules),
                    ('build_clib',    has_c_libraries),
                    ('build_ext',     has_ext_modules),
                    ('build_scripts', has_scripts),
                   ]

# class build
<commit_msg>Fix for<commit_after>"""distutils.command.build

Implements the Distutils 'build' command."""

# created 1999/03/08, Greg Ward

__revision__ = "$Id$"

import sys, os
from distutils.core import Command
from distutils.util import get_platform

def show_compilers ():
    from distutils.ccompiler import show_compilers
    show_compilers()

class build (Command):

    description = "build everything needed to install"

    user_options = [
        ('build-base=', 'b',
         "base directory for build library"),
        ('build-purelib=', None,
         "build directory for platform-neutral distributions"),
        ('build-platlib=', None,
         "build directory for platform-specific distributions"),
        ('build-lib=', None,
         "build directory for all distribution (defaults to either " +
         "build-purelib or build-platlib"),
        ('build-scripts=', None,
         "build directory for scripts"),
        ('build-temp=', 't',
         "temporary build directory"),
        ('compiler=', 'c',
         "specify the compiler type"),
        ('debug', 'g',
         "compile extensions and libraries with debugging information"),
        ('force', 'f',
         "forcibly build everything (ignore file timestamps)"),
        ]

    boolean_options = ['debug', 'force']

    help_options = [
        ('help-compiler', None,
         "list available compilers", show_compilers),
        ]

    def initialize_options (self):
        self.build_base = 'build'
        # these are decided only after 'build_base' has its final value
        # (unless overridden by the user or client)
        self.build_purelib = None
        self.build_platlib = None
        self.build_lib = None
        self.build_temp = None
        self.build_scripts = None
        self.compiler = None
        self.debug = None
        self.force = 0

    def finalize_options (self):

        plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])

        # 'build_purelib' and 'build_platlib' just default to 'lib' and
        # 'lib.<plat>' under the base build directory.  We only use one of
        # them for a given distribution, though --
        if self.build_purelib is None:
            self.build_purelib = os.path.join(self.build_base, 'lib')
        if self.build_platlib is None:
            self.build_platlib = os.path.join(self.build_base,
                                              'lib' + plat_specifier)

        # 'build_lib' is the actual directory that we will use for this
        # particular module distribution -- if user didn't supply it, pick
        # one of 'build_purelib' or 'build_platlib'.
        if self.build_lib is None:
            if self.distribution.ext_modules:
                self.build_lib = self.build_platlib
            else:
                self.build_lib = self.build_purelib

        # 'build_temp' -- temporary directory for compiler turds,
        # "build/temp.<plat>"
        if self.build_temp is None:
            self.build_temp = os.path.join(self.build_base,
                                           'temp' + plat_specifier)
        if self.build_scripts is None:
            self.build_scripts = os.path.join(self.build_base,
                                              'scripts-' + sys.version[0:3])

    # finalize_options ()

    def run (self):

        # Run all relevant sub-commands.  This will be some subset of:
        #  - build_py      - pure Python modules
        #  - build_clib    - standalone C libraries
        #  - build_ext     - Python extensions
        #  - build_scripts - (Python) scripts
        for cmd_name in self.get_sub_commands():
            self.run_command(cmd_name)

    # -- Predicates for the sub-command list ---------------------------

    def has_pure_modules (self):
        return self.distribution.has_pure_modules()

    def has_c_libraries (self):
        return self.distribution.has_c_libraries()

    def has_ext_modules (self):
        return self.distribution.has_ext_modules()

    def has_scripts (self):
        return self.distribution.has_scripts()

    sub_commands = [('build_py',      has_pure_modules),
                    ('build_clib',    has_c_libraries),
                    ('build_ext',     has_ext_modules),
                    ('build_scripts', has_scripts),
                   ]

# class build
<|endoftext|>


<commit_before>import ConfigParser
import StringIO

import pytest

import boosh

from boosh.exceptions import MissingOptionError

def test_config():
    parser = ConfigParser.RawConfigParser()
    parser.add_section('gateway foo')
    parser.set('gateway foo', 'hostname', "foo.example.org")
    parser.set('gateway foo', 'user', "jsmith")

    parser.add_section('gateway bar')
    parser.set('gateway bar', 'hostname', "bar.example.org")
    parser.set('gateway bar', 'user', "alice")

    parser.add_section('profile foo')
    parser.set('profile foo', 'regions', "us-west-1, us-east-1")

    parser.add_section('profile bar')
    parser.set('profile bar', 'regions', "us-west-2, sa-east-1")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)

    config = boosh.Config(buf)
    assert len(config.profiles) == 2
    assert len(config.gateways) == 2

def test_config_boolean():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing_true')
    parser.set('gateway testing_true', 'hostname', "foo.example.org")
    parser.set('gateway testing_true', 'use_netcat', "true")

    parser.add_section('gateway testing_false')
    parser.set('gateway testing_false', 'hostname', "foo.example.org")
    parser.set('gateway testing_false', 'use_netcat', "false")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    assert config.gateways['testing_true'].use_netcat == True
    assert config.gateways['testing_false'].use_netcat == False

def test_config_string():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing')
    parser.set('gateway testing', 'hostname', "foo.example.org")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    assert config.gateways['testing'].hostname == "foo.example.org"

def test_config_multistring():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('profile testing')
    parser.set('profile testing', 'regions', "us-west-1, us-east-1")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    profile = config.profiles['testing']
    assert profile.regions == ['us-west-1', 'us-east-1']

def test_config_missing_multistring():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('profile testing')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    with pytest.raises(MissingOptionError):
        boosh.Config(buf)

def test_config_missing_string():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    with pytest.raises(MissingOptionError):
        boosh.Config(buf)

def test_bad_section_names():
    parser = ConfigParser.RawConfigParser()
    parser.add_section(' profile')
    parser.add_section('profile ')
    parser.add_section('testing section')
    parser.add_section(' ')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)

    config = boosh.Config(buf)
    assert len(config.profiles) == 0
    assert len(config.gateways) == 0
    assert len(config.groups) == 0
<commit_msg>Add missing multistring test<commit_after>import ConfigParser
import StringIO

import pytest

import boosh

from boosh.exceptions import MissingOptionError

def test_config():
    parser = ConfigParser.RawConfigParser()
    parser.add_section('gateway foo')
    parser.set('gateway foo', 'hostname', "foo.example.org")
    parser.set('gateway foo', 'user', "jsmith")

    parser.add_section('gateway bar')
    parser.set('gateway bar', 'hostname', "bar.example.org")
    parser.set('gateway bar', 'user', "alice")

    parser.add_section('profile foo')
    parser.set('profile foo', 'regions', "us-west-1, us-east-1")

    parser.add_section('profile bar')
    parser.set('profile bar', 'regions', "us-west-2, sa-east-1")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)

    config = boosh.Config(buf)
    assert len(config.profiles) == 2
    assert len(config.gateways) == 2

def test_config_boolean():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing_true')
    parser.set('gateway testing_true', 'hostname', "foo.example.org")
    parser.set('gateway testing_true', 'use_netcat', "true")

    parser.add_section('gateway testing_false')
    parser.set('gateway testing_false', 'hostname', "foo.example.org")
    parser.set('gateway testing_false', 'use_netcat', "false")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    assert config.gateways['testing_true'].use_netcat == True
    assert config.gateways['testing_false'].use_netcat == False

def test_config_string():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing')
    parser.set('gateway testing', 'hostname', "foo.example.org")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    assert config.gateways['testing'].hostname == "foo.example.org"

def test_config_multistring():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('profile testing')
    parser.set('profile testing', 'regions', "us-west-1, us-east-1")

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    config = boosh.Config(buf)

    profile = config.profiles['testing']
    assert profile.regions == ['us-west-1', 'us-east-1']

def test_config_missing_multistring():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('profile testing')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    with pytest.raises(MissingOptionError):
        boosh.Config(buf)

def test_config_missing_string():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('gateway testing')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    with pytest.raises(MissingOptionError):
        boosh.Config(buf)

def test_config_missing_multistring():
    parser = ConfigParser.RawConfigParser()

    parser.add_section('profile testing')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)
    with pytest.raises(MissingOptionError):
        boosh.Config(buf)

def test_bad_section_names():
    parser = ConfigParser.RawConfigParser()
    parser.add_section(' profile')
    parser.add_section('profile ')
    parser.add_section('testing section')
    parser.add_section(' ')

    buf = StringIO.StringIO()
    parser.write(buf)
    buf.seek(0)

    config = boosh.Config(buf)
    assert len(config.profiles) == 0
    assert len(config.gateways) == 0
    assert len(config.groups) == 0
<|endoftext|>


<commit_before>#encoding: utf-8
import urllib2
from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger
from django.template.response import TemplateResponse
from django.views.defaults import page_not_found
from common.login_required_mixin import LoginRequiredMixin
from reducer.forms import ReduceURLForm
from django.views.generic import View, TemplateView, RedirectView
from reducer.models import Link, Owner

class HomeTemplateView(View):
    template_name = 'home.html'

    def get(self, request, *args, **kwargs):
        cxt = self.get_context_data()
        return TemplateResponse(
            request=self.request,
            template=self.template_name,
            context=cxt,
            **kwargs
        )

    def post(self, request, *args, **kwargs):
        cxt = self.get_context_data()
        req = request.POST
        authenticated = request.user.is_authenticated()
        if authenticated:
            req = req.copy()
            req[u'user'] = request.user.pk

        form = ReduceURLForm(req)
        #Não deixar cadastrar URL repetida economia de disco/memoria
        if form.is_valid():
            link = Link.objects.filter(url=form.cleaned_data['url'])
            link = link[0] if link else None
            if not link:
                link = form.save()

            if authenticated:
                owner, created = Owner.objects.get_or_create(link=link)
                owner.owners.add(request.user)

            cxt['link'] = link.to_dict()
        else:
            cxt['link'] = '500'
        #TODO - Se a url já estiver cadastrada o dono não muda e as urls existente só
        #TODO - aparece para a primeira pessoa, pensar como corrigir isso
        return TemplateResponse(
            request=self.request,
            template=self.template_name,
            context=cxt,
            **kwargs
        )

    def get_context_data(self, **kwargs):
        cxt = {}
        cxt['form_url'] = ReduceURLForm
        return cxt

class MyLinksTemplateView(LoginRequiredMixin, TemplateView):
    template_name = 'my-links.html'
    def get(self, request, *args, **kwargs):
        links = Link.objects.filter(owner__owners=request.user)
        paginator = Paginator(links, 2)

        page = request.GET.get('page')
        try:
            links = paginator.page(page)
        except PageNotAnInteger:
            links = paginator.page(1)
        except (EmptyPage, InvalidPage):
            links = paginator.page(paginator.num_pages)

        cxt = {'links': links}
        return self.render_to_response(cxt)

class GoToRedirectView(RedirectView):
    def get(self, request, *args, **kwargs):
        url_hash = kwargs.get('url_hash')
        try:
            link = Link.objects.decode(url_hash)
            self.url = urllib2.unquote(link)
            return super(GoToRedirectView, self).get(request, *args, **kwargs)
        except Link.DoesNotExist:
            return page_not_found(request)
<commit_msg>Aumentando a qtde de links por paginas para 10<commit_after>#encoding: utf-8
import urllib2
from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger
from django.template.response import TemplateResponse
from django.views.defaults import page_not_found
from common.login_required_mixin import LoginRequiredMixin
from reducer.forms import ReduceURLForm
from django.views.generic import View, TemplateView, RedirectView
from reducer.models import Link, Owner

class HomeTemplateView(View):
    template_name = 'home.html'

    def get(self, request, *args, **kwargs):
        cxt = self.get_context_data()
        return TemplateResponse(
            request=self.request,
            template=self.template_name,
            context=cxt,
            **kwargs
        )

    def post(self, request, *args, **kwargs):
        cxt = self.get_context_data()
        req = request.POST
        authenticated = request.user.is_authenticated()
        if authenticated:
            req = req.copy()
            req[u'user'] = request.user.pk

        form = ReduceURLForm(req)
        #Não deixar cadastrar URL repetida economia de disco/memoria
        if form.is_valid():
            link = Link.objects.filter(url=form.cleaned_data['url'])
            link = link[0] if link else None
            if not link:
                link = form.save()

            if authenticated:
                owner, created = Owner.objects.get_or_create(link=link)
                owner.owners.add(request.user)

            cxt['link'] = link.to_dict()
        else:
            cxt['link'] = '500'
        #TODO - Se a url já estiver cadastrada o dono não muda e as urls existente só
        #TODO - aparece para a primeira pessoa, pensar como corrigir isso
        return TemplateResponse(
            request=self.request,
            template=self.template_name,
            context=cxt,
            **kwargs
        )

    def get_context_data(self, **kwargs):
        cxt = {}
        cxt['form_url'] = ReduceURLForm
        return cxt

class MyLinksTemplateView(LoginRequiredMixin, TemplateView):
    template_name = 'my-links.html'
    def get(self, request, *args, **kwargs):
        links = Link.objects.filter(owner__owners=request.user)
        paginator = Paginator(links, 10)

        page = request.GET.get('page')
        try:
            links = paginator.page(page)
        except PageNotAnInteger:
            links = paginator.page(1)
        except (EmptyPage, InvalidPage):
            links = paginator.page(paginator.num_pages)

        cxt = {'links': links}
        return self.render_to_response(cxt)

class GoToRedirectView(RedirectView):
    def get(self, request, *args, **kwargs):
        url_hash = kwargs.get('url_hash')
        try:
            link = Link.objects.decode(url_hash)
            self.url = urllib2.unquote(link)
            return super(GoToRedirectView, self).get(request, *args, **kwargs)
        except Link.DoesNotExist:
            return page_not_found(request)
<|endoftext|>


<commit_before>import os
import pytest
from numpy import testing
from tardis.io import atomic

@pytest.fixture(scope="module")
def default_atom_h5_path():
    return atomic.default_atom_h5_path

@pytest.fixture(scope="module")
def chianti_he_db_h5_path():
    return os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'data', 'chianti_he_db.h5')

def test_data_path():
    data_path = atomic.data_path('test')
    assert data_path.split('/')[-3:] == ['tardis', 'data', 'test']

def test_read_basic_atom_data(default_atom_h5_path):
    data = atomic.read_basic_atom_data(default_atom_h5_path)
    assert data['atomic_number'][13] == 14
    assert data['symbol'][13] == "Si"
    testing.assert_almost_equal(data['mass'][13], 28.085, decimal=4)

def test_read_ionization_data(default_atom_h5_path):
    data = atomic.read_ionization_data(default_atom_h5_path)
    assert data['atomic_number'][0] == 1
    assert data['ion_number'][0] == 1
    testing.assert_almost_equal(data['ionization_energy'][0], 13.59844, decimal=4)

def test_read_levels_data(default_atom_h5_path):
    data = atomic.read_levels_data(default_atom_h5_path)
    assert data['atomic_number'][4] == 14
    assert data['ion_number'][4] == 0
    assert data['level_number'][4] == 4
    testing.assert_almost_equal(data['energy'][4], 1.90865, decimal=4)
    assert data['g'][4] == 1
    assert data['metastable'][4] == False

def test_read_lines_data(default_atom_h5_path):
    data = atomic.read_lines_data(default_atom_h5_path)
    assert data['line_id'][0] == 8
    assert data['atomic_number'][0] == 14
    assert data['ion_number'][0] == 5
    testing.assert_almost_equal(data['wavelength'][0], 66.772, decimal=4)
    testing.assert_almost_equal(data['f_ul'][0], 0.02703, decimal=4)
    testing.assert_almost_equal(data['f_lu'][0], 0.04054, decimal=4)
    assert data['level_number_lower'][0] == 0.0
    assert data['level_number_upper'][0] == 36.0

def test_read_synpp_refs(chianti_he_db_h5_path):
    data = atomic.read_synpp_refs(chianti_he_db_h5_path)
    assert data['atomic_number'][0] == 1
    assert data['ion_number'][0] == 0
    testing.assert_almost_equal(data['wavelength'][0], 6562.7973633, decimal=4)
    assert data['line_id'][0] == 564995

def test_read_zeta_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_zeta_data(chianti_he_db_h5_path)
    testing.assert_almost_equal(data[2000][1][1], 0.339, decimal=4)
    testing.assert_almost_equal(data[2000][1][2], 0.000, decimal=4)

    with pytest.raises(ValueError):
        atomic.read_zeta_data(None)

    with pytest.raises(IOError):
        atomic.read_zeta_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_zeta_data(default_atom_h5_path)

def test_read_collision_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_collision_data(chianti_he_db_h5_path)
    assert data[0]['atomic_number'][0] == 2
    assert data[0]['ion_number'][0] == 0
    assert data[0]['level_number_upper'][0] == 18
    assert data[0]['level_number_lower'][0] == 2
    assert data[0]['g_ratio'][0] == 1.0
    testing.assert_almost_equal(data[0]['delta_e'][0], 35484.251143, decimal=4)
    assert data[1][0] == 2000.0
    assert data[1][1] == 4000.0

    with pytest.raises(ValueError):
        atomic.read_zeta_data(None)

    with pytest.raises(IOError):
        atomic.read_zeta_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_zeta_data(default_atom_h5_path)

def test_read_macro_atom_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_macro_atom_data(chianti_he_db_h5_path)
    assert data[0]['atomic_number'][0] == 2
    assert data[0]['ion_number'][0] == 0
    assert data[0]['source_level_number'][0] == 0.0
    assert data[0]['destination_level_number'][0] == 48.0
    assert data[0]['transition_type'][0] == 1
    assert data[0]['transition_probability'][0] == 0.0
    assert data[0]['transition_line_id'][0] == 564957

    assert data[1]['count_down'][0] == 0
    assert data[1]['count_up'][0] == 7
    assert data[1]['count_total'][0] == 7

    with pytest.raises(ValueError):
        atomic.read_macro_atom_data(None)

    with pytest.raises(IOError):
        atomic.read_macro_atom_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_macro_atom_data(default_atom_h5_path)

def test_atom_levels():
    atom_data = atomic.AtomData.from_hdf5(atomic.default_atom_h5_path)
    with pytest.raises(Exception):
        raise Exception('test the atom_data thoroughly')

def test_atomic_symbol():
    assert atomic.atomic_number2symbol[14] == 'Si'

def test_atomic_symbol_reverse():
    assert atomic.symbol2atomic_number['Si'] == 14

def test_atomic_reprepare(atomic_data_fname):
    atom_data = atomic.AtomData.from_hdf5(atomic_data_fname)
    atom_data.prepare_atom_data([14])
    assert len(atom_data.lines) > 0
    # Fix for new behavior of prepare_atom_data
    # Consider doing only one prepare_atom_data and check
    # len(atom_data.lines) == N where N is known
    atom_data = atomic.AtomData.from_hdf5(atomic_data_fname)
    atom_data.prepare_atom_data([20])
    assert len(atom_data.lines) > 0

<commit_msg>fix paths in test_atomic<commit_after>import os
import pytest
from numpy import testing
from tardis.io import atomic

@pytest.fixture(scope="module")
def default_atom_h5_path():
    return atomic.data_path('atom_data.h5')

@pytest.fixture(scope="module")
def chianti_he_db_h5_path():
    return atomic.data_path('chianti_he_db.h5')

def test_data_path():
    data_path = atomic.data_path('test')
    assert data_path.split('/')[-3:] == ['tardis', 'data', 'test']

def test_read_basic_atom_data(default_atom_h5_path):
    data = atomic.read_basic_atom_data(default_atom_h5_path)
    assert data['atomic_number'][13] == 14
    assert data['symbol'][13] == "Si"
    testing.assert_almost_equal(data['mass'][13], 28.085, decimal=4)

def test_read_ionization_data(default_atom_h5_path):
    data = atomic.read_ionization_data(default_atom_h5_path)
    assert data['atomic_number'][0] == 1
    assert data['ion_number'][0] == 1
    testing.assert_almost_equal(data['ionization_energy'][0], 13.59844, decimal=4)

def test_read_levels_data(default_atom_h5_path):
    data = atomic.read_levels_data(default_atom_h5_path)
    assert data['atomic_number'][4] == 14
    assert data['ion_number'][4] == 0
    assert data['level_number'][4] == 4
    testing.assert_almost_equal(data['energy'][4], 1.90865, decimal=4)
    assert data['g'][4] == 1
    assert data['metastable'][4] == False

def test_read_lines_data(default_atom_h5_path):
    data = atomic.read_lines_data(default_atom_h5_path)
    assert data['line_id'][0] == 8
    assert data['atomic_number'][0] == 14
    assert data['ion_number'][0] == 5
    testing.assert_almost_equal(data['wavelength'][0], 66.772, decimal=4)
    testing.assert_almost_equal(data['f_ul'][0], 0.02703, decimal=4)
    testing.assert_almost_equal(data['f_lu'][0], 0.04054, decimal=4)
    assert data['level_number_lower'][0] == 0.0
    assert data['level_number_upper'][0] == 36.0

def test_read_synpp_refs(chianti_he_db_h5_path):
    data = atomic.read_synpp_refs(chianti_he_db_h5_path)
    assert data['atomic_number'][0] == 1
    assert data['ion_number'][0] == 0
    testing.assert_almost_equal(data['wavelength'][0], 6562.7973633, decimal=4)
    assert data['line_id'][0] == 564995

def test_read_zeta_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_zeta_data(chianti_he_db_h5_path)
    testing.assert_almost_equal(data[2000][1][1], 0.339, decimal=4)
    testing.assert_almost_equal(data[2000][1][2], 0.000, decimal=4)

    with pytest.raises(ValueError):
        atomic.read_zeta_data(None)

    with pytest.raises(IOError):
        atomic.read_zeta_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_zeta_data(default_atom_h5_path)

def test_read_collision_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_collision_data(chianti_he_db_h5_path)
    assert data[0]['atomic_number'][0] == 2
    assert data[0]['ion_number'][0] == 0
    assert data[0]['level_number_upper'][0] == 18
    assert data[0]['level_number_lower'][0] == 2
    assert data[0]['g_ratio'][0] == 1.0
    testing.assert_almost_equal(data[0]['delta_e'][0], 35484.251143, decimal=4)
    assert data[1][0] == 2000.0
    assert data[1][1] == 4000.0

    with pytest.raises(ValueError):
        atomic.read_zeta_data(None)

    with pytest.raises(IOError):
        atomic.read_zeta_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_zeta_data(default_atom_h5_path)

def test_read_macro_atom_data(default_atom_h5_path, chianti_he_db_h5_path):
    data = atomic.read_macro_atom_data(chianti_he_db_h5_path)
    assert data[0]['atomic_number'][0] == 2
    assert data[0]['ion_number'][0] == 0
    assert data[0]['source_level_number'][0] == 0.0
    assert data[0]['destination_level_number'][0] == 48.0
    assert data[0]['transition_type'][0] == 1
    assert data[0]['transition_probability'][0] == 0.0
    assert data[0]['transition_line_id'][0] == 564957

    assert data[1]['count_down'][0] == 0
    assert data[1]['count_up'][0] == 7
    assert data[1]['count_total'][0] == 7

    with pytest.raises(ValueError):
        atomic.read_macro_atom_data(None)

    with pytest.raises(IOError):
        atomic.read_macro_atom_data('fakepath')

    with pytest.raises(ValueError):
        atomic.read_macro_atom_data(default_atom_h5_path)

def test_atom_levels():
    atom_data = atomic.AtomData.from_hdf5(atomic.default_atom_h5_path)
    with pytest.raises(Exception):
        raise Exception('test the atom_data thoroughly')

def test_atomic_symbol():
    assert atomic.atomic_number2symbol[14] == 'Si'

def test_atomic_symbol_reverse():
    assert atomic.symbol2atomic_number['Si'] == 14

def test_atomic_reprepare(atomic_data_fname):
    atom_data = atomic.AtomData.from_hdf5(atomic_data_fname)
    atom_data.prepare_atom_data([14])
    assert len(atom_data.lines) > 0
    # Fix for new behavior of prepare_atom_data
    # Consider doing only one prepare_atom_data and check
    # len(atom_data.lines) == N where N is known
    atom_data = atomic.AtomData.from_hdf5(atomic_data_fname)
    atom_data.prepare_atom_data([20])
    assert len(atom_data.lines) > 0

<|endoftext|>


<commit_before>#!/bin/python
# this script uses pandocfilters: https://github.com/jgm/pandocfilters
# the walk function in particular is a modified version of the one there. see the pandocfilters license (3-clause BSD) at: https://github.com/jgm/pandocfilters/blob/master/LICENSE

import json, sys
from pandocfilters import Str, Space
import pandocfilters
import collections

# Below, (a, [b]) means that the tag a implies tag b; so if you have a
# page with tag a, it will automatically also be applied the tag b.
# Note that the order here is important.  Let's say we also have
#    (b, [c])
# then doing tag a should also imply tag c, since the implication chain
# goes a -> b -> c.  In other words, tag implication should be
# transitive, in that a -> b and b -> c together mean a -> c.  This
# means though that you should put (a, [b]) before (b, [c]), since then
# the first will be applied, leaving you with the tags a and b, and then
# the second will be applied, leaving you with tags a, b, and c. (This
# is an OrderedDict so that the above works.)
tag_implications = collections.OrderedDict([
    ("hakyll", ["haskell"]),
    ("python", ["programming"]),
    ("latex", ["linux"]),
    ("qs", ["quantified-self"]),
    ("lesswrong", ["rationality"]),
    ("logic", ["math"]),
    ("physics", ["science"]),
    ("atmospheric-sciences", ["science"]),
    ("astronomy", ["science"]),
    ("chemistry", ["science"]),
    ("analysis", ["math"]),
    ("haskell", ["programming"]),
    ("depression", ["psychology"]),
])

tag_synonyms = {
    "effective-altruism": ["ea", "effective altruism", "effectivealtruism"],
    "university-of-washington": ["uw", "uwashington", "university of washington"],
    "set-theory": ["set theory"],
    "lesswrong": ["lw", "less-wrong", "less wrong"],
    "cognito-mentoring": ["cm", "cognito mentoring", "cognito"],
    "math": ["maths", "mathematics"],
    "link-collection": ["link collection", "resources", "links"],
    "atmopsheric-sciences": ["atmos"],
    "chemistry": ["chem"],
    "computer-science": ["cs", "computer science"],
}

def imply_tags(tags, tag_implications):
    '''
    Take a list of tags along with a dictionary of tag implications.
    Return a new list of tags that includes all the implciations.
    '''
    result = list(tags)
    for key in tag_implications:
        if key in result:
            result.extend(tag_implications.get(key))
    return list(set(result))

def standardize_tags(tags, tag_synonyms):
    '''
    Take a list of tags ("tags") along with a dictionary of tag synonyms
    and return a new list of tags, where all synonymous tags are
    standardized according to tag_synonyms.  For instance, if
    tag_synonyms contains the line
        "university-of-washington": ["uw", "uwashington"],
    and if tags contains "uw" or "uwashington", then this will be
    replaced by "university-of-washington".
    '''
    result = []
    for tag in tags:
        canonical = [key for key, value in tag_synonyms.items() if tag in value]
        if not canonical:
            canonical = [tag]
        result.extend(canonical)
    return result

def stringify(x):
    """Walks the tree x and returns concatenated string content,
    leaving out all formatting.
    """
    result = []

    def go(key, val, format, meta):
        if key == 'Str':
            result.append(val)
        elif key == 'Code':
            result.append(val[1])
        elif key == 'Math':
            result.append(val[1])
        elif key == 'LineBreak':
            result.append(" ")
        elif key == 'Space':
            result.append(" ")

    walk(x, go, "", {})
    #return ''.join(result)
    return result

def gogo(key, val, f, meta):
    if key == 'MetaInLines':
        result = meta.get("tags", {}).get('t', {})
        if 'MetaInLines' in result:
            return Str(val + "yo")
    #elif key == 'Code':
        #return Str(val)
    #elif key == 'Math':
        #return Str(val)
    #elif key == 'LineBreak':
        #return Str(val)
    #elif key == 'Space':
        #return Str(val)

def caps(key, val, f, meta):
    if key == 'Str':
        return Str(val.upper())

def do_nothing(key, val, f, meta):
    pass

def walk(x, action, format, meta):
    """Walk a tree, applying an action to every object.
    Returns a modified tree.
    """
    if isinstance(x, list):
        #print "list!"
        array = []
        if isinstance(x[0], dict) and 't' in x[0]:
            res = action(x[0]['t'], x[0]['c'], format, meta)
            if res is None:
                array.append(pandocfilters.walk(x[0], do_nothing, format, meta))
            elif isinstance(res, list):
                for z in res:
                    array.append(pandocfilters.walk(z, do_nothing, format, meta))
            else:
                array.append(pandocfilters.walk(res, do_nothing, format, meta))
        else:
            array.append(pandocfilters.walk(x[0], do_nothing, format, meta))

        for item in x[1:]:
            if isinstance(item, dict) and 't' in item:
                res = action(item['t'], item['c'], format, meta)
                if res is None:
                    array.append(pandocfilters.walk(item, action, format, meta))
                elif isinstance(res, list):
                    for z in res:
                        array.append(pandocfilters.walk(z, action, format, meta))
                else:
                    array.append(pandocfilters.walk(res, action, format, meta))
            else:
                array.append(pandocfilters.walk(item, action, format, meta))
        return array
    elif isinstance(x, dict):
        #print "dict!"
        obj = {}
        for k in x:
            obj[k] = pandocfilters.walk(x[k], action, format, meta)
        return obj
    else:
        return x

def listify(x):
    '''
    Take a YAML-JSON list or string of comma-delimited tags,
    and return a cleaned list.
    '''
    if x['t'] == 'MetaInlines':
        w = [i.strip(',') for i in stringify(x) if i is not ' ']
        return w
    elif x['t'] == 'MetaList':
        return stringify(x)

def intersperse(iterable, delimiter):
    '''See http://stackoverflow.com/a/5656097/3422337 '''
    it = iter(iterable)
    yield next(it)
    for x in it:
        yield delimiter
        yield x

def pack_tags(tags):
    '''
    Take a list of tags ("tags") and return a YAML-JSON list of the tags
    '''
    result = []
    for tag in tags:
        tag_dict = {'t': 'MetaInlines', 'c': [Str(tag)]}
        result.append(tag_dict)
    return result
    #return list(intersperse([Str(i) for i in tags], Space()))

def load_json(filepath):
    with open(filepath, 'r') as f:
        x = f.next()
        data = json.loads(x)

def organize_tags(data, tag_synonyms, tag_implications):
    '''
    Takes the filepath of a JSON file (str filepath) and returns
    a JSON tree of the file with its tags organized according to
    tag_synonyms and tag_implications.
    '''
    tags = data[0]['unMeta'].get('tags', {})
    w = listify(tags)
    #print w
    w = standardize_tags(w, tag_synonyms)
    #print w
    w = imply_tags(w, tag_implications)
    tags['c'] = pack_tags(w)
    tags['t'] = 'MetaList'
    #array = []
    #altered = walk(data, caps, "", data[0]['unMeta'])
    json.dump(data, sys.stdout)

#organize_tags("hello.json", tag_synonyms, tag_implications)

    #if len(sys.argv) > 1:
        #format = sys.argv[1]
    #else:
        #format = ""
    #print altered
    #print json.dumps(altered, indent=2)

<commit_msg>return tags list too<commit_after>#!/bin/python
# this script uses pandocfilters: https://github.com/jgm/pandocfilters
# the walk function in particular is a modified version of the one there. see the pandocfilters license (3-clause BSD) at: https://github.com/jgm/pandocfilters/blob/master/LICENSE

import json, sys
from pandocfilters import Str, Space
import pandocfilters
import collections

# Below, (a, [b]) means that the tag a implies tag b; so if you have a
# page with tag a, it will automatically also be applied the tag b.
# Note that the order here is important.  Let's say we also have
#    (b, [c])
# then doing tag a should also imply tag c, since the implication chain
# goes a -> b -> c.  In other words, tag implication should be
# transitive, in that a -> b and b -> c together mean a -> c.  This
# means though that you should put (a, [b]) before (b, [c]), since then
# the first will be applied, leaving you with the tags a and b, and then
# the second will be applied, leaving you with tags a, b, and c. (This
# is an OrderedDict so that the above works.)
tag_implications = collections.OrderedDict([
    ("hakyll", ["haskell"]),
    ("python", ["programming"]),
    ("latex", ["linux"]),
    ("qs", ["quantified-self"]),
    ("lesswrong", ["rationality"]),
    ("logic", ["math"]),
    ("physics", ["science"]),
    ("atmospheric-sciences", ["science"]),
    ("astronomy", ["science"]),
    ("chemistry", ["science"]),
    ("analysis", ["math"]),
    ("haskell", ["programming"]),
    ("depression", ["psychology"]),
])

tag_synonyms = {
    "effective-altruism": ["ea", "effective altruism", "effectivealtruism"],
    "university-of-washington": ["uw", "uwashington", "university of washington"],
    "set-theory": ["set theory"],
    "lesswrong": ["lw", "less-wrong", "less wrong"],
    "cognito-mentoring": ["cm", "cognito mentoring", "cognito"],
    "math": ["maths", "mathematics"],
    "link-collection": ["link collection", "resources", "links"],
    "atmopsheric-sciences": ["atmos"],
    "chemistry": ["chem"],
    "computer-science": ["cs", "computer science"],
}

def imply_tags(tags, tag_implications):
    '''
    Take a list of tags along with a dictionary of tag implications.
    Return a new list of tags that includes all the implciations.
    '''
    result = list(tags)
    for key in tag_implications:
        if key in result:
            result.extend(tag_implications.get(key))
    return list(set(result))

def standardize_tags(tags, tag_synonyms):
    '''
    Take a list of tags ("tags") along with a dictionary of tag synonyms
    and return a new list of tags, where all synonymous tags are
    standardized according to tag_synonyms.  For instance, if
    tag_synonyms contains the line
        "university-of-washington": ["uw", "uwashington"],
    and if tags contains "uw" or "uwashington", then this will be
    replaced by "university-of-washington".
    '''
    result = []
    for tag in tags:
        canonical = [key for key, value in tag_synonyms.items() if tag in value]
        if not canonical:
            canonical = [tag]
        result.extend(canonical)
    return result

def stringify(x):
    """Walks the tree x and returns concatenated string content,
    leaving out all formatting.
    """
    result = []

    def go(key, val, format, meta):
        if key == 'Str':
            result.append(val)
        elif key == 'Code':
            result.append(val[1])
        elif key == 'Math':
            result.append(val[1])
        elif key == 'LineBreak':
            result.append(" ")
        elif key == 'Space':
            result.append(" ")

    walk(x, go, "", {})
    #return ''.join(result)
    return result

def gogo(key, val, f, meta):
    if key == 'MetaInLines':
        result = meta.get("tags", {}).get('t', {})
        if 'MetaInLines' in result:
            return Str(val + "yo")
    #elif key == 'Code':
        #return Str(val)
    #elif key == 'Math':
        #return Str(val)
    #elif key == 'LineBreak':
        #return Str(val)
    #elif key == 'Space':
        #return Str(val)

def caps(key, val, f, meta):
    if key == 'Str':
        return Str(val.upper())

def do_nothing(key, val, f, meta):
    pass

def walk(x, action, format, meta):
    """Walk a tree, applying an action to every object.
    Returns a modified tree.
    """
    if isinstance(x, list):
        #print "list!"
        array = []
        if isinstance(x[0], dict) and 't' in x[0]:
            res = action(x[0]['t'], x[0]['c'], format, meta)
            if res is None:
                array.append(pandocfilters.walk(x[0], do_nothing, format, meta))
            elif isinstance(res, list):
                for z in res:
                    array.append(pandocfilters.walk(z, do_nothing, format, meta))
            else:
                array.append(pandocfilters.walk(res, do_nothing, format, meta))
        else:
            array.append(pandocfilters.walk(x[0], do_nothing, format, meta))

        for item in x[1:]:
            if isinstance(item, dict) and 't' in item:
                res = action(item['t'], item['c'], format, meta)
                if res is None:
                    array.append(pandocfilters.walk(item, action, format, meta))
                elif isinstance(res, list):
                    for z in res:
                        array.append(pandocfilters.walk(z, action, format, meta))
                else:
                    array.append(pandocfilters.walk(res, action, format, meta))
            else:
                array.append(pandocfilters.walk(item, action, format, meta))
        return array
    elif isinstance(x, dict):
        #print "dict!"
        obj = {}
        for k in x:
            obj[k] = pandocfilters.walk(x[k], action, format, meta)
        return obj
    else:
        return x

def listify(x):
    '''
    Take a YAML-JSON list or string of comma-delimited tags,
    and return a cleaned list.
    '''
    if x['t'] == 'MetaInlines':
        w = [i.strip(',') for i in stringify(x) if i is not ' ']
        return w
    elif x['t'] == 'MetaList':
        return stringify(x)

def intersperse(iterable, delimiter):
    '''See http://stackoverflow.com/a/5656097/3422337 '''
    it = iter(iterable)
    yield next(it)
    for x in it:
        yield delimiter
        yield x

def pack_tags(tags):
    '''
    Take a list of tags ("tags") and return a YAML-JSON list of the tags
    '''
    result = []
    for tag in tags:
        tag_dict = {'t': 'MetaInlines', 'c': [Str(tag)]}
        result.append(tag_dict)
    return result
    #return list(intersperse([Str(i) for i in tags], Space()))

def load_json(filepath):
    with open(filepath, 'r') as f:
        x = f.next()
        data = json.loads(x)

def organize_tags(data, tag_synonyms, tag_implications):
    '''
    Takes the filepath of a JSON file (str filepath) and returns
    a JSON tree of the file with its tags organized according to
    tag_synonyms and tag_implications.
    '''
    tags = data[0]['unMeta'].get('tags', {})
    w = listify(tags)
    #print w
    w = standardize_tags(w, tag_synonyms)
    #print w
    w = imply_tags(w, tag_implications)
    keep_tags = list(w)
    tags['c'] = pack_tags(w)
    tags['t'] = 'MetaList'
    #array = []
    #altered = walk(data, caps, "", data[0]['unMeta'])
    #return json.dump(data, sys.stdout)
    return {'json_dump': json.dumps(data, separators=(',',':')),
            'tags': keep_tags}

#organize_tags("hello.json", tag_synonyms, tag_implications)

    #if len(sys.argv) > 1:
        #format = sys.argv[1]
    #else:
        #format = ""
    #print altered
    #print json.dumps(altered, indent=2)

<|endoftext|>


<commit_before>import math

def countup(n):
    if n == 10:
        print "Blastoff!"
    else:
        print n
        return countup(n+1)

def main():
    return countup(int(raw_input("Pick an integer less than 10: ")))

#main()

def countup_from(start, end):
    if start == end:
        print "Finished"
    else:
        print start
        return countup_from(start + 1, end)

def countdown_from(start, end):
    if start == end:
        print "Finished"
    else:
        print start
        return countdown_from(start - 1, end)

def countup_from_back_to(start, start_changing, end, times): #doesn't work
    if times > 0 and start_changing == start:
        print start
    elif start_changing == end:
        print end
        return countup_from_back_to(start, start_changing - 1, end, times + 1)
    else:
        print start_changing
        return countup_from_back_to(start, start_changing + 1, end, times + 1)

def adder(running_total=0):
    n = raw_input("Next number: ")
    if n == "":
        print "The sum is {}".format(running_total)
    else:
        n = float(n)
        running_total += n
        print "Running Total: {}".format(running_total)
        return adder(running_total)

#adder()

def biggest(biggest_num=None):
    n = raw_input("Next: ")
    if n == "":
        print "The biggest number is {}".format(biggest_num)
    else:
        n = float(n)
        if n > biggest_num:
            biggest_num = n
        return biggest(biggest_num)

#biggest()

def smallest(smallest_num=float("inf")):
    n = raw_input("Next: ")
    if n == "":
        print "The smallest number is {}".format(smallest_num)
    else:
        n = float(n)
        if n < smallest_num:
            smallest_num = n
        return smallest(smallest_num)

#smallest()

def power(x, nth, result):
    if nth == 0:
        print result
    else:
        if result == 0:
            result = x
            return power(x, nth - 1, result)
        else:
            result = result * x
            return power(x, nth - 1, result)

#power(2, 3, 0)

def power(x, n):
    if n == 0:
        return (0,1)
    else:
        x = x*
        return power(x, n-1)

<commit_msg>power done yay<commit_after>import math

def countup(n):
    if n == 10:
        print "Blastoff!"
    else:
        print n
        return countup(n+1)

def main():
    return countup(int(raw_input("Pick an integer less than 10: ")))

#main()

def countup_from(start, end):
    if start == end:
        print "Finished"
    else:
        print start
        return countup_from(start + 1, end)

def countdown_from(start, end):
    if start == end:
        print "Finished"
    else:
        print start
        return countdown_from(start - 1, end)

def countup_from_back_to(start, start_changing, end, times): #doesn't work
    if times > 0 and start_changing == start:
        print start
    elif start_changing == end:
        print end
        return countup_from_back_to(start, start_changing - 1, end, times + 1)
    else:
        print start_changing
        return countup_from_back_to(start, start_changing + 1, end, times + 1)

def adder(running_total=0):
    n = raw_input("Next number: ")
    if n == "":
        print "The sum is {}".format(running_total)
    else:
        n = float(n)
        running_total += n
        print "Running Total: {}".format(running_total)
        return adder(running_total)

#adder()

def biggest(biggest_num=None):
    n = raw_input("Next: ")
    if n == "":
        print "The biggest number is {}".format(biggest_num)
    else:
        n = float(n)
        if n > biggest_num:
            biggest_num = n
        return biggest(biggest_num)

#biggest()

def smallest(smallest_num=float("inf")):
    n = raw_input("Next: ")
    if n == "":
        print "The smallest number is {}".format(smallest_num)
    else:
        n = float(n)
        if n < smallest_num:
            smallest_num = n
        return smallest(smallest_num)

#smallest()

def power(x, nth, result):
    if nth == 0:
        print result
    else:
        if result == 0:
            result = x
            return power(x, nth - 1, result)
        else:
            result = result * x
            return power(x, nth - 1, result)

#power(2, 3, 0)

def power(x, n):
    if n == 0:
        x = x*n + 1
        return x
    else:
        return x * power(x, n-1)

print power(2, 2)

<|endoftext|>