<commit_before>import re
import tweepy
from random import choice
from itertools import cycle
from google_language import get_entities
from models.corpus import update_corpus

def tweet_maker(the_tweet):
    foods = cycle((
        'spaghetti',
        'meatballs',
        'marinara sauce',
        'steak pizzaiola',
        'baked ziti',
        'pecorino romano',
        'oregano',
        'basil',
        'mozzarella',
        'bolognese',
        'parmesean'
    ))
    the_new_tweet = the_tweet.text
    entities = get_entities(the_tweet.text)
    for word, entity_type in entities.items():
        update_corpus(word, entity_type)
        the_new_tweet = the_new_tweet.replace(
            word,
            choice(
                feed_me(next(foods), entity_type)
        ))
    return replace_url(the_new_tweet)

def replace_url(in_string):
    url = re.compile("http.+(\s|$)")
    return url.sub(
        "https://www.youtube.com/watch?v=zWHu95io9B4 ",
        in_string
    )

def feed_me(subject, entity):
    return {
        'UNKNOWN':[
            f'{subject}',
            f'some kind of {subject}',
        ],
        'PERSON':[
            f'{subject} man',
        ],
        'LOCATION':[
            f'{subject} land',
            f'{subject} city',
        ],
        'ORGANIZATION':[
            f'{subject.title()} Conservancy',
            f'Department of {subject.title()}',
            f'{subject.title()} Association',
        ],
        'EVENT':[
            f'{subject.title()} Day',
            f'war of {subject.title()}',
        ],
        'WORK_OF_ART':[
            f'Mona {subject.title()}',
            f'Thinking {subject.title()}',
            f'{subject.title()} Descending a Staircase',
        ],
        'CONSUMER_GOOD':[
            f'{subject}',
        ],
        'OTHER':[
            f'{subject}',
        ],
    }.get(entity, f'{subject}')

if __name__ == '__main__':
    print(tweet_maker(input('Enter some text:')))

<commit_msg>makes replacement slightly less aggressive<commit_after>import re
import tweepy
from random import choice
from google_language import get_entities
from models.corpus import update_corpus

def tweet_maker(the_tweet):
    foods = (
        'spaghetti',
        'meatballs',
        'marinara sauce',
        'steak pizzaiola',
        'baked ziti',
        'pecorino romano',
        'oregano',
        'basil',
        'mozzarella',
        'bolognese',
        'parmesean'
    )
    the_new_tweet = the_tweet.text
    entities = get_entities(the_tweet.text)
    for word, entity_type in entities.items():
        update_corpus(word, entity_type)
        the_new_tweet = the_new_tweet.replace(
            word, choice(feed_me(choice(foods), word, entity_type))
        )
    return replace_url(the_new_tweet)

def replace_url(in_string):
    url = re.compile("http.+(\s|$)")
    return url.sub(
        "https://www.youtube.com/watch?v=zWHu95io9B4 ",
        in_string
    )

def feed_me(food, origin, entity):
    return {
        'UNKNOWN':[
            origin,
        ],
        'PERSON':[
            f'{food} man',
        ],
        'LOCATION':[
            f'{food} land',
            f'{food} city',
        ],
        'ORGANIZATION':[
            f'{food.title()} Conservancy',
            f'Department of {food.title()}',
            f'{food.title()} Association',
        ],
        'EVENT':[
            f'{food.title()} Day',
            f'war of {food.title()}',
        ],
        'WORK_OF_ART':[
            origin,
        ],
        'CONSUMER_GOOD':[
            f'{food}',
        ],
        'OTHER':[
            origin,
        ],
    }.get(entity, f'{food}')

if __name__ == '__main__':
    print(tweet_maker(input('Enter some text:')))

<|endoftext|>


<commit_before>VERSION = (0, 0, 1)
<commit_msg>complexified the version schema to agree to PEP386<commit_after>VERSION = (0, 0, 1, 'alpha', 0)

# meaning =  (major, minor, micro, stage, release)

def get_version():
    '''
    Version Schema agrees to PEP 386.

    'stage' and 'release' are only reserved for special occasions.
    At least the former will remain being 'alpha' before version 1.0.
    '''

    v = '%s.%s' % (VERSION[0], VERSION[1])
    if VERSION[2]:
        v = '%s.%s' % (v, VERSION[2])
    if VERSION[3] != 'final' and VERSION[4] != 0:
            v = '%s%s%s' % (v, VERSION[3][0], VERSION[4])
    return v

<|endoftext|>


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

import argparse
import csv
import os
import re
import time

import malaffinity
import praw
import requests

wait_between_requests = 2
retry_after_failed_request = 5
search_comment_body = False

regex = "myanimelist\.net/(?:profile|animelist)/([a-z0-9_-]+)"
regex = re.compile(regex, re.I)

# Set the pearson stuff up.
# Too lazy to rename everything and update docs. Sorry
pearson = malaffinity.MALAffinity(round=2)

def create_reddit_instance():
    return praw.Reddit("reddit")

def get_comment_stream():
    reddit = create_reddit_instance()

    return reddit.subreddit("anime").stream.comments()

def get_comments_from_submission(submission_id):
    reddit = create_reddit_instance()

    # https://www.reddit.com/r/redditdev/comments/5to97v/slug/ddoeedj/
    comments = requests.request(
        "GET",
        "http://apiv2.pushshift.io/reddit/get/comment_ids/{}"
            .format(submission_id)
    )
    comments = comments.json()
    comments = comments["data"]

    return reddit.info(comments)

def handle_comment(comment):
    if not comment.author:
        return

    author_name = comment.author.name

    print("Processing User: {}".format(author_name))

    if author_name in processed:
        print("- Already processed. Skipping...")
        return

    processed.add(author_name)

    text = comment.author_flair_text

    if not text:
        print("- No flair text.", end=" ")

        # Search the comment body if the var is True
        if search_comment_body and comment.body:
            # Just set text to the comment body to avoid having to
            # rewrite this whole section
            print("Searching comment body...")
            text = comment.body

        else:
            print("Skipping...")
            return

    match = regex.search(text)

    if not match:
        print("- Can't find MAL username. Skipping...")
        return

    username = match.group(1)

    # Halt so MAL doesn't get angry if we make too many calls to their
    # server in a short amount of time.
    time.sleep(wait_between_requests)

    # Two attempts, then give up. Adjust max tries here.
    # TODO: Better way of doing this?
    for _ in range(2):
        try:
            affinity, shared = pearson.calculate_affinity(username)

        except malaffinity.MALRateLimitExceededError:
            print("- MAL's blocking us. Halting for a few seconds...")
            # TODO: Fix unnecessary waiting on two failed requests.
            time.sleep(retry_after_failed_request)

        except:
            print("- Affinity can't be calculated. Skipping...")
            return

        else:
            break

    affinities[author_name] = {
        "reddit": author_name,
        "mal": username,
        "affinity": affinity,
        "shared": shared
    }

    print("- Calculated affinity: {}%".format(affinity))

    return

def main(comments):
    global processed
    global affinities

    processed  = set()
    affinities = {}

    # Open the affinities file if it exists.
    if os.path.isfile("affinities.csv"):
        with open("affinities.csv", "r") as file:
            reader = csv.DictReader(file)

            for row in reader:
                user = row["reddit"]
                processed.add(user)

                affinities[user] = row

    start_time = time.time()

    while True:
        try:
            for comment in comments:
                handle_comment(comment)
            # Will only get called if using comments from a submission.
            # If processing from comment stream, KeyboardInterrupt
            # is the only way out.
            print("\n\n" + "Processed all users. Breaking loop...")
            break

        except KeyboardInterrupt:
            print("\n\n" + "KeyboardInterrupt. Breaking loop...")
            break

        except Exception as e:
            print("Error: {}".format(e))
            time.sleep(30)

    end_time = time.time()

    runtime = round(end_time - start_time)

    # Is "affinities" a word?
    print("Script runtime: {} seconds".format(runtime))
    print("Total affinities calculated: {}".format( len(affinities) ))

    print("\n" + "Dumping to file...")

    # Nicely write data to CSV.
    with open("affinities.csv", "w") as file:
        headers = ["reddit", "mal", "affinity", "shared"]

        writer = csv.DictWriter(file, fieldnames=headers, lineterminator="\n")
        writer.writeheader()

        affinities_sorted = sorted(
            affinities.items(),
            key = lambda x: float( x[1]["affinity"] ),
            reverse = True
        )

        for user, data in affinities_sorted:
            writer.writerow(data)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="/r/anime soulmate finder")

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        "-c", "--stream",
        help="use the comment stream as the comment source",
        action="store_true"
    )
    group.add_argument(
        "-s", "--submission",
        help="use the comments in a submission as the comment source"
    )

    parser.add_argument(
        "-b", "--search-comment-body",
        help="search the comment body for a mal url as well as the user's flair",
        action="store_true"
    )

    parser.add_argument("mal_username")

    args = parser.parse_args()

    # Set pearson stuff up.
    pearson.init(args.mal_username)

    # Choose either comment stream or comments from submission.
    if args.stream:
        comments = get_comment_stream()
    elif args.submission:
        comments = get_comments_from_submission(args.submission)

    # Change the `search_comment_body` global.
    search_comment_body = args.search_comment_body

    # Run it.
    main(comments)
<commit_msg>Only display 'processing' message for users not already processed<commit_after>#!/usr/bin/env python3

import argparse
import csv
import os
import re
import time

import malaffinity
import praw
import requests

wait_between_requests = 2
retry_after_failed_request = 5
search_comment_body = False

regex = "myanimelist\.net/(?:profile|animelist)/([a-z0-9_-]+)"
regex = re.compile(regex, re.I)

# Set the pearson stuff up.
# Too lazy to rename everything and update docs. Sorry
pearson = malaffinity.MALAffinity(round=2)

def create_reddit_instance():
    return praw.Reddit("reddit")

def get_comment_stream():
    reddit = create_reddit_instance()

    return reddit.subreddit("anime").stream.comments()

def get_comments_from_submission(submission_id):
    reddit = create_reddit_instance()

    # https://www.reddit.com/r/redditdev/comments/5to97v/slug/ddoeedj/
    comments = requests.request(
        "GET",
        "http://apiv2.pushshift.io/reddit/get/comment_ids/{}"
            .format(submission_id)
    )
    comments = comments.json()
    comments = comments["data"]

    return reddit.info(comments)

def handle_comment(comment):
    if not comment.author:
        return

    author_name = comment.author.name

    if author_name in processed:
        return

    processed.add(author_name)

    # stdout's too time taxing. Might as well save some
    # time and only display this only when this script comes across
    # a user that hasn't already been processed.
    print("Processing User: {}".format(author_name))

    text = comment.author_flair_text

    if not text:
        print("- No flair text.", end=" ")

        # Search the comment body if the var is True
        if search_comment_body and comment.body:
            # Just set text to the comment body to avoid having to
            # rewrite this whole section
            print("Searching comment body...")
            text = comment.body

        else:
            print("Skipping...")
            return

    match = regex.search(text)

    if not match:
        print("- Can't find MAL username. Skipping...")
        return

    username = match.group(1)

    # Halt so MAL doesn't get angry if we make too many calls to their
    # server in a short amount of time.
    time.sleep(wait_between_requests)

    # Two attempts, then give up. Adjust max tries here.
    # TODO: Better way of doing this?
    for _ in range(2):
        try:
            affinity, shared = pearson.calculate_affinity(username)

        except malaffinity.MALRateLimitExceededError:
            print("- MAL's blocking us. Halting for a few seconds...")
            # TODO: Fix unnecessary waiting on two failed requests.
            time.sleep(retry_after_failed_request)

        except:
            print("- Affinity can't be calculated. Skipping...")
            return

        else:
            break

    affinities[author_name] = {
        "reddit": author_name,
        "mal": username,
        "affinity": affinity,
        "shared": shared
    }

    print("- Calculated affinity: {}%".format(affinity))

    return

def main(comments):
    global processed
    global affinities

    processed  = set()
    affinities = {}

    # Open the affinities file if it exists.
    if os.path.isfile("affinities.csv"):
        with open("affinities.csv", "r") as file:
            reader = csv.DictReader(file)

            for row in reader:
                user = row["reddit"]
                processed.add(user)

                affinities[user] = row

    start_time = time.time()

    while True:
        try:
            for comment in comments:
                handle_comment(comment)
            # Will only get called if using comments from a submission.
            # If processing from comment stream, KeyboardInterrupt
            # is the only way out.
            print("\n\n" + "Processed all users. Breaking loop...")
            break

        except KeyboardInterrupt:
            print("\n\n" + "KeyboardInterrupt. Breaking loop...")
            break

        except Exception as e:
            print("Error: {}".format(e))
            time.sleep(30)

    end_time = time.time()

    runtime = round(end_time - start_time)

    # Is "affinities" a word?
    print("Script runtime: {} seconds".format(runtime))
    print("Total affinities calculated: {}".format( len(affinities) ))

    print("\n" + "Dumping to file...")

    # Nicely write data to CSV.
    with open("affinities.csv", "w") as file:
        headers = ["reddit", "mal", "affinity", "shared"]

        writer = csv.DictWriter(file, fieldnames=headers, lineterminator="\n")
        writer.writeheader()

        affinities_sorted = sorted(
            affinities.items(),
            key = lambda x: float( x[1]["affinity"] ),
            reverse = True
        )

        for user, data in affinities_sorted:
            writer.writerow(data)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="/r/anime soulmate finder")

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        "-c", "--stream",
        help="use the comment stream as the comment source",
        action="store_true"
    )
    group.add_argument(
        "-s", "--submission",
        help="use the comments in a submission as the comment source"
    )

    parser.add_argument(
        "-b", "--search-comment-body",
        help="search the comment body for a mal url as well as the user's flair",
        action="store_true"
    )

    parser.add_argument("mal_username")

    args = parser.parse_args()

    # Set pearson stuff up.
    pearson.init(args.mal_username)

    # Choose either comment stream or comments from submission.
    if args.stream:
        comments = get_comment_stream()
    elif args.submission:
        comments = get_comments_from_submission(args.submission)

    # Change the `search_comment_body` global.
    search_comment_body = args.search_comment_body

    # Run it.
    main(comments)
<|endoftext|>


<commit_before>version_info = (0, 6, 6)
__version__ = '.'.join(map(str, version_info[:3])) + ''.join(version_info[3:])
<commit_msg>version bump<commit_after>version_info = (0, 7, 0)
__version__ = '.'.join(map(str, version_info[:3])) + ''.join(version_info[3:])
<|endoftext|>


<commit_before>from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.label import Label

from kivy.properties import *
from kivy.uix.screenmanager import Screen

import rules
import game
import human_player
import ai_genome
import ai_factory

import checkbox_list as cb_l

from defines import *

import pdb

def create_player(player_type_widget, player_name, max_depth):
    if player_type_widget.val == 'Computer':
        # TODO: This doesn't really belong here.
        genome = ai_genome.AIGenome(player_name)
        genome.max_depth = max_depth
        # TODO: configure openings book usage

        aif = ai_factory.AIFactory()
        p = aif.create_player(genome)
    else:
        p = human_player.HumanPlayer(player_name)
    return p

class SetupScreen(Screen):

    def __init__(self, *args, **kwargs):
        super(SetupScreen, self).__init__(*args, **kwargs)

    def load_file(self, filename):
        if filename:
            self.set_GUI_from_file(filename)
        else:
            self.ids.start_button.text = "Start Game"

    def start_game(self, unused=None):
        g = self.set_up_game_from_GUI()
        self.app.start_game(g, self.size)

    def set_up_game_from_GUI(self):
        bs = int(self.ids.bs_id.val)
        rstr = self.ids.rules_id.val
        r = rules.Rules(bs, rstr)

        max_depth = int(self.ids.max_depth_id.val)
        player1 = create_player(self.ids.black_type_id, self.ids.black_name_id.text, max_depth)
        player2 = create_player(self.ids.white_type_id, self.ids.white_name_id.text, max_depth)

        g = self.app.games_mgr.create_game(r, player1, player2)
        return g

    def set_GUI_from_game(self, g):
        self.ids.black_name_id.text = g.get_player_name(BLACK)
        self.ids.white_name_id.text = g.get_player_name(WHITE)
        self.ids.bs_id.set_active(g.rules.size)
        self.ids.rules_id.set_active(g.rules.type_str)

    def set_GUI_from_file(self, filename):
        f = open(filename)
        # TODO
        #g = self.app.games_mgr.create_game(r, player1, player2)
        g = game.Game(None, None, None) # Hmmm. TODO
        g.configure_from_str(f.read())
        self.ids.start_button.text = "Resume"
        self.set_GUI_from_game(g)
<commit_msg>Added TODO<commit_after>from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.label import Label

from kivy.properties import *
from kivy.uix.screenmanager import Screen

import rules
import game
import human_player
import ai_genome
import ai_factory

import checkbox_list as cb_l

from defines import *

import pdb

def create_player(player_type_widget, player_name, max_depth):
    if player_type_widget.val == 'Computer':
        # TODO: This doesn't really belong here.
        genome = ai_genome.AIGenome(player_name)
        genome.max_depth = max_depth
        # TODO: configure openings book usage

        aif = ai_factory.AIFactory()
        p = aif.create_player(genome)
    else:
        p = human_player.HumanPlayer(player_name)
    return p

class SetupScreen(Screen):

    def __init__(self, *args, **kwargs):
        super(SetupScreen, self).__init__(*args, **kwargs)

    def load_file(self, filename):
        if filename:
            self.set_GUI_from_file(filename)
        else:
            self.ids.start_button.text = "Start Game"

    def start_game(self, unused=None):
        g = self.set_up_game_from_GUI()
        self.app.start_game(g, self.size)

    def set_up_game_from_GUI(self):
        bs = int(self.ids.bs_id.val)
        rstr = self.ids.rules_id.val
        r = rules.Rules(bs, rstr)

        max_depth = int(self.ids.max_depth_id.val)
        player1 = create_player(self.ids.black_type_id, self.ids.black_name_id.text, max_depth)
        player2 = create_player(self.ids.white_type_id, self.ids.white_name_id.text, max_depth)

        g = self.app.games_mgr.create_game(r, player1, player2)
        return g

    def set_GUI_from_game(self, g):
        self.ids.black_name_id.text = g.get_player_name(BLACK)
        self.ids.white_name_id.text = g.get_player_name(WHITE)
        self.ids.bs_id.set_active(g.rules.size)
        self.ids.rules_id.set_active(g.rules.type_str)
        # TODO: Player type, AI Parameters?

    def set_GUI_from_file(self, filename):
        f = open(filename)
        # TODO
        #g = self.app.games_mgr.create_game(r, player1, player2)
        g = game.Game(None, None, None) # Hmmm. TODO
        g.configure_from_str(f.read())
        self.ids.start_button.text = "Resume"
        self.set_GUI_from_game(g)
<|endoftext|>


<commit_before>#----------------------------------------------------------------------
# Copyright (c) 2008 Board of Trustees, Princeton University
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------

import re

from sfa.util.faults import SfaAPIError

# for convenience and smoother translation - we should get rid of these functions eventually
def get_leaf(hrn): return Xrn(hrn).get_leaf()
def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn
def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)

class Xrn:

    ########## basic tools on HRNs
    # split a HRN-like string into pieces
    # this is like split('.') except for escaped (backslashed) dots
    # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
    @staticmethod
    def hrn_split(hrn):
        return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]

    # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
    @staticmethod
    def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]

    # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
    @staticmethod
    def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]

    # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
    @staticmethod
    def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))

    # e.g. escape ('a.b') -> 'a\.b'
    @staticmethod
    def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)

    # e.g. unescape ('a\.b') -> 'a.b'
    @staticmethod
    def unescape(token): return token.replace('\\.','.')

    # Return the HRN authority chain from top to bottom.
    # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']
    @staticmethod
    def hrn_auth_chain(hrn):
        parts = Xrn.hrn_auth_list(hrn)
        chain = []
        for i in range(len(parts)):
            chain.append('.'.join(parts[:i+1]))
        # Include the HRN itself?
        #chain.append(hrn)
        return chain

    # Is the given HRN a true authority over the namespace of the other
    # child HRN?
    # A better alternative than childHRN.startswith(parentHRN)
    # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,
    # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False
    # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True
    @staticmethod
    def hrn_is_auth_for_hrn(parenthrn, hrn):
        if parenthrn == hrn:
            return True
        for auth in Xrn.hrn_auth_chain(hrn):
            if parenthrn == auth:
                return True
        return False

    ########## basic tools on URNs
    URN_PREFIX = "urn:publicid:IDN"
    URN_PREFIX_lower = "urn:publicid:idn"

    @staticmethod
    def is_urn (text):
        return text.lower().startswith(Xrn.URN_PREFIX_lower)

    @staticmethod
    def urn_full (urn):
        if Xrn.is_urn(urn): return urn
        else: return Xrn.URN_PREFIX+urn
    @staticmethod
    def urn_meaningful (urn):
        if Xrn.is_urn(urn): return urn[len(Xrn.URN_PREFIX):]
        else: return urn
    @staticmethod
    def urn_split (urn):
        return Xrn.urn_meaningful(urn).split('+')

    ####################
    # the local fields that are kept consistent
    # self.urn
    # self.hrn
    # self.type
    # self.path
    # provide either urn, or (hrn + type)
    def __init__ (self, xrn, type=None, id=None):
        if not xrn: xrn = ""
        # user has specified xrn : guess if urn or hrn
        self.id = id
        if Xrn.is_urn(xrn):
            self.hrn=None
            self.urn=xrn
            if id:
                self.urn = "%s-%s" % (self.urn, str(id))
            self.urn_to_hrn()
            if type:
                self.type=type
                self.hrn_to_urn()
        else:
            self.urn=None
            self.hrn=xrn
            self.type=type
            self.hrn_to_urn()

        self._normalize()
# happens all the time ..
#        if not type:
#            debug_logger.debug("type-less Xrn's are not safe")

    def __repr__ (self):
        result="<XRN u=%s h=%s"%(self.urn,self.hrn)
        if hasattr(self,'leaf'): result += " leaf=%s"%self.leaf
        if hasattr(self,'authority'): result += " auth=%s"%self.authority
        result += ">"
        return result

    def get_urn(self): return self.urn
    def get_hrn(self): return self.hrn
    def get_type(self): return self.type
    def get_hrn_type(self): return (self.hrn, self.type)

    def _normalize(self):
        if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
        if not hasattr(self,'leaf'):
            self.leaf=Xrn.hrn_split(self.hrn)[-1]
        # self.authority keeps a list
        if not hasattr(self,'authority'):
            self.authority=Xrn.hrn_auth_list(self.hrn)

    def get_leaf(self):
        self._normalize()
        return self.leaf

    def get_authority_hrn(self):
        self._normalize()
        return '.'.join( self.authority )

    def get_authority_urn(self):
        self._normalize()
        return ':'.join( [Xrn.unescape(x) for x in self.authority] )

    def set_authority(self, authority):
        """
        update the authority section of an existing urn
        """
        authority_hrn = self.get_authority_hrn()
        if not authority_hrn.startswith(authority+"."):
            self.hrn = authority + "." + self.hrn
            self.hrn_to_urn()
        self._normalize()

    def urn_to_hrn(self):
        """
        compute tuple (hrn, type) from urn
        """

#        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
        if not Xrn.is_urn(self.urn):
            raise SfaAPIError, "Xrn.urn_to_hrn"

        parts = Xrn.urn_split(self.urn)
        type=parts.pop(2)
        # Remove the authority name (e.g. '.sa')
        if type == 'authority':
            name = parts.pop()
            # Drop the sa. This is a bad hack, but its either this
            # or completely change how record types are generated/stored
            if name != 'sa':
                type = type + "+" + name
            name =""
        else:
            name = parts.pop(len(parts)-1)
        # convert parts (list) into hrn (str) by doing the following
        # 1. remove blank parts
        # 2. escape dots inside parts
        # 3. replace ':' with '.' inside parts
        # 3. join parts using '.'
        hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part])
        # dont replace ':' in the name section
        if name:
            parts = name.split(':')
            if len(parts) > 1:
                self.id = ":".join(parts[1:])
                name = parts[0]
            hrn += '.%s' % Xrn.escape(name)

        self.hrn=str(hrn)
        self.type=str(type)

    def hrn_to_urn(self):
        """
        compute urn from (hrn, type)
        """

#        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
        if Xrn.is_urn(self.hrn):
            raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn

        if self.type and self.type.startswith('authority'):
            self.authority = Xrn.hrn_auth_list(self.hrn)
            leaf = self.get_leaf()
            #if not self.authority:
            #    self.authority = [self.hrn]
            type_parts = self.type.split("+")
            self.type = type_parts[0]
            name = 'sa'
            if len(type_parts) > 1:
                name = type_parts[1]
            auth_parts = [part for part in [self.get_authority_urn(), leaf] if part]
            authority_string = ":".join(auth_parts)
        else:
            self.authority = Xrn.hrn_auth_list(self.hrn)
            name = Xrn.hrn_leaf(self.hrn)
            # separate name from id
            name_parts = name.split("-")
            name = name_parts[0]
            authority_string = self.get_authority_urn()

        if self.type == None:
            urn = "+".join(['',authority_string,Xrn.unescape(name)])
        else:
            urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])

        if hasattr(self, 'id') and self.id:
            urn = "%s-%s" % (urn, self.id)

        self.urn = Xrn.URN_PREFIX + urn

    def dump_string(self):
        result="-------------------- XRN\n"
        result += "URN=%s\n"%self.urn
        result += "HRN=%s\n"%self.hrn
        result += "TYPE=%s\n"%self.type
        result += "LEAF=%s\n"%self.get_leaf()
        result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
        result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
        return result

<commit_msg>fix bug<commit_after>#----------------------------------------------------------------------
# Copyright (c) 2008 Board of Trustees, Princeton University
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------

import re

from sfa.util.faults import SfaAPIError

# for convenience and smoother translation - we should get rid of these functions eventually
def get_leaf(hrn): return Xrn(hrn).get_leaf()
def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn
def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)

class Xrn:

    ########## basic tools on HRNs
    # split a HRN-like string into pieces
    # this is like split('.') except for escaped (backslashed) dots
    # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
    @staticmethod
    def hrn_split(hrn):
        return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]

    # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
    @staticmethod
    def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]

    # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
    @staticmethod
    def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]

    # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
    @staticmethod
    def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))

    # e.g. escape ('a.b') -> 'a\.b'
    @staticmethod
    def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)

    # e.g. unescape ('a\.b') -> 'a.b'
    @staticmethod
    def unescape(token): return token.replace('\\.','.')

    # Return the HRN authority chain from top to bottom.
    # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']
    @staticmethod
    def hrn_auth_chain(hrn):
        parts = Xrn.hrn_auth_list(hrn)
        chain = []
        for i in range(len(parts)):
            chain.append('.'.join(parts[:i+1]))
        # Include the HRN itself?
        #chain.append(hrn)
        return chain

    # Is the given HRN a true authority over the namespace of the other
    # child HRN?
    # A better alternative than childHRN.startswith(parentHRN)
    # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,
    # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False
    # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True
    @staticmethod
    def hrn_is_auth_for_hrn(parenthrn, hrn):
        if parenthrn == hrn:
            return True
        for auth in Xrn.hrn_auth_chain(hrn):
            if parenthrn == auth:
                return True
        return False

    ########## basic tools on URNs
    URN_PREFIX = "urn:publicid:IDN"
    URN_PREFIX_lower = "urn:publicid:idn"

    @staticmethod
    def is_urn (text):
        return text.lower().startswith(Xrn.URN_PREFIX_lower)

    @staticmethod
    def urn_full (urn):
        if Xrn.is_urn(urn): return urn
        else: return Xrn.URN_PREFIX+urn
    @staticmethod
    def urn_meaningful (urn):
        if Xrn.is_urn(urn): return urn[len(Xrn.URN_PREFIX):]
        else: return urn
    @staticmethod
    def urn_split (urn):
        return Xrn.urn_meaningful(urn).split('+')

    ####################
    # the local fields that are kept consistent
    # self.urn
    # self.hrn
    # self.type
    # self.path
    # provide either urn, or (hrn + type)
    def __init__ (self, xrn, type=None, id=None):
        if not xrn: xrn = ""
        # user has specified xrn : guess if urn or hrn
        self.id = id
        self.type = type

        if Xrn.is_urn(xrn):
            self.hrn=None
            self.urn=xrn
            self.urn_to_hrn()
            if id:
                self.hrn_to_urn()
        else:
            self.urn=None
            self.hrn=xrn
            self.type=type
            self.hrn_to_urn()

        self._normalize()
# happens all the time ..
#        if not type:
#            debug_logger.debug("type-less Xrn's are not safe")

    def __repr__ (self):
        result="<XRN u=%s h=%s"%(self.urn,self.hrn)
        if hasattr(self,'leaf'): result += " leaf=%s"%self.leaf
        if hasattr(self,'authority'): result += " auth=%s"%self.authority
        result += ">"
        return result

    def get_urn(self): return self.urn
    def get_hrn(self): return self.hrn
    def get_type(self): return self.type
    def get_hrn_type(self): return (self.hrn, self.type)

    def _normalize(self):
        if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
        if not hasattr(self,'leaf'):
            self.leaf=Xrn.hrn_split(self.hrn)[-1]
        # self.authority keeps a list
        if not hasattr(self,'authority'):
            self.authority=Xrn.hrn_auth_list(self.hrn)

    def get_leaf(self):
        self._normalize()
        return self.leaf

    def get_authority_hrn(self):
        self._normalize()
        return '.'.join( self.authority )

    def get_authority_urn(self):
        self._normalize()
        return ':'.join( [Xrn.unescape(x) for x in self.authority] )

    def set_authority(self, authority):
        """
        update the authority section of an existing urn
        """
        authority_hrn = self.get_authority_hrn()
        if not authority_hrn.startswith(authority+"."):
            self.hrn = authority + "." + self.hrn
            self.hrn_to_urn()
        self._normalize()

    def urn_to_hrn(self):
        """
        compute tuple (hrn, type) from urn
        """

#        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
        if not Xrn.is_urn(self.urn):
            raise SfaAPIError, "Xrn.urn_to_hrn"

        parts = Xrn.urn_split(self.urn)
        type=parts.pop(2)
        # Remove the authority name (e.g. '.sa')
        if type == 'authority':
            name = parts.pop()
            # Drop the sa. This is a bad hack, but its either this
            # or completely change how record types are generated/stored
            if name != 'sa':
                type = type + "+" + name
            name =""
        else:
            name = parts.pop(len(parts)-1)
        # convert parts (list) into hrn (str) by doing the following
        # 1. remove blank parts
        # 2. escape dots inside parts
        # 3. replace ':' with '.' inside parts
        # 3. join parts using '.'
        hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part])
        # dont replace ':' in the name section
        if name:
            parts = name.split(':')
            if len(parts) > 1:
                self.id = ":".join(parts[1:])
                name = parts[0]
            hrn += '.%s' % Xrn.escape(name)

        self.hrn=str(hrn)
        self.type=str(type)

    def hrn_to_urn(self):
        """
        compute urn from (hrn, type)
        """

#        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
        if Xrn.is_urn(self.hrn):
            raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn

        if self.type and self.type.startswith('authority'):
            self.authority = Xrn.hrn_auth_list(self.hrn)
            leaf = self.get_leaf()
            #if not self.authority:
            #    self.authority = [self.hrn]
            type_parts = self.type.split("+")
            self.type = type_parts[0]
            name = 'sa'
            if len(type_parts) > 1:
                name = type_parts[1]
            auth_parts = [part for part in [self.get_authority_urn(), leaf] if part]
            authority_string = ":".join(auth_parts)
        else:
            self.authority = Xrn.hrn_auth_list(self.hrn)
            name = Xrn.hrn_leaf(self.hrn)
            # separate name from id
            authority_string = self.get_authority_urn()

        if self.type == None:
            urn = "+".join(['',authority_string,Xrn.unescape(name)])
        else:
            urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])

        if hasattr(self, 'id') and self.id:
            urn = "%s-%s" % (urn, self.id)

        self.urn = Xrn.URN_PREFIX + urn

    def dump_string(self):
        result="-------------------- XRN\n"
        result += "URN=%s\n"%self.urn
        result += "HRN=%s\n"%self.hrn
        result += "TYPE=%s\n"%self.type
        result += "LEAF=%s\n"%self.get_leaf()
        result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
        result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
        return result

<|endoftext|>


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

import curses
import Pyro4

hardcoded_fire = u"""
 (                     )  (    (                )       (    (   (
 )\ )       *   )   ( /(  )\ ) )\ )    *   ) ( /(       )\ ) )\ ))\ )
(()/(   ( ` )  /(   )\())(()/((()/(  ` )  /( )\())(    (()/((()/(()/((
 /(_))  )\ ( )(_)) ((_)\  /(_))/(_))  ( )(_)|(_)\ )\    /(_))/(_))(_))\\
(_)) _ ((_|_(_())    ((_)(_))_(_))_| (_(_()) _((_|(_)  (_))_(_))(_))((_)
| _ \ | | |_   _|   / _ \| |_ | |_   |_   _|| || | __| | |_ |_ _| _ \ __|
|  _/ |_| | | |    | (_) | __|| __|    | |  | __ | _|  | __| | ||   / _|
|_|  \___/  |_|     \___/|_|  |_|      |_|  |_||_|___| |_|  |___|_|_\___|
ZMIENIC NA PUT OUT THE FIRE - od gościa z samolotu.
"""

print(hardcoded_fire)

class Player:
    """
    The player
    """
    def __init__(self, name, room, items = []):
        self.name = name
        self.room = room
        self.items = items

    def drop(self, index):
        self.items.pop(index)

<commit_msg>put OUT the fire<commit_after>#!/usr/bin/env python3.3

import curses
import Pyro4

hardcoded_fire = u"""
 (                     )                           )       (    (   (
 )\ )       *   )   ( /(         *   )    *   ) ( /(       )\ ) )\ ))\ )
(()/(   ( ` )  /(   )\())    ( ` )  /(  ` )  /( )\())(    (()/((()/(()/((
 /(_))  )\ ( )(_)) ((_)\     )\ ( )(_))  ( )(_)|(_)\ )\    /(_))/(_))(_))\\
(_)) _ ((_|_(_())    ((_) _ ((_|_(_())  (_(_()) _((_|(_)  (_))_(_))(_))((_)
| _ \ | | |_   _|   / _ \| | | |_   _|  |_   _|| || | __| | |_ |_ _| _ \ __|
|  _/ |_| | | |    | (_) | |_| | | |      | |  | __ | _|  | __| | ||   / _|
|_|  \___/  |_|     \___/ \___/  |_|      |_|  |_||_|___| |_|  |___|_|_\___|
"""

print(hardcoded_fire)

class Player:
    """
    The player
    """
    def __init__(self, name, room, items = []):
        self.name = name
        self.room = room
        self.items = items

    def drop(self, index):
        self.items.pop(index)

<|endoftext|>


<commit_before>import pygame
from game_engine import GameEngine
from input_engine import InputEngine
from event_engine import EventEngine

class Game:
    """
    Container and manager for GameEngine instances

    @author: James Heslin (PROGRAM_IX)
    """

    def __init__(self, width, height):
        """
        Constructs a new Game, whose screen has the specified width and height

        @type width: int
        @param width: Width of the screen

        @type height: int
        @param height: Height of the screen

        @author: James Heslin (PROGRAM_IX)
        """
        self.width = width
        self.height = height
        self.screen = None
        self.engine = None
        self.engines = []

    def start(self):
        """
        Set up the GameEngine and run the game

        @author: James Heslin (PROGRAM_IX)
        """
        pygame.init()
        self.i_e = InputEngine()
        self.e_e = EventEngine(self.i_e)
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption("PyStroke")
        self.engines = [GameEngine(self.screen, self.e_e)] # add others here
        self.engine = self.engines[0]
        self.run()

    def run(self):
        """
        Runs the GameEngine, switches to another GameEngine, or quits, based on
        returned flags from GameEngine

        @author: James Heslin (PROGRAM_IX)
        """
        while self.engine.run() == 0:
            if self.engines.index(self.engine) < len(self.engines) - 1:
                self.engine = self.engines[self.engines.index(self.engine) + 1]
            else:
                self.engine = self.engines[0]
        pygame.quit()
        raise SystemExit

def main():
    """
    Default running parameters for Game

    @author: James Heslin (PROGRAM_IX)
    """
    g = Game(800, 600)
    g.start()

if __name__ == "__main__":
    main()
<commit_msg>Moved InputEngine and EventEngine declarations to __init__<commit_after>import pygame
from game_engine import GameEngine
from input_engine import InputEngine
from event_engine import EventEngine

class Game:
    """
    Container and manager for GameEngine instances

    @author: James Heslin (PROGRAM_IX)
    """

    def __init__(self, width, height):
        """
        Constructs a new Game, whose screen has the specified width and height

        @type width: int
        @param width: Width of the screen

        @type height: int
        @param height: Height of the screen

        @author: James Heslin (PROGRAM_IX)
        """
        self.width = width
        self.height = height
        self.screen = None
        self.engine = None
        self.engines = []
        self.i_e = InputEngine()
        self.e_e = EventEngine(self.i_e)

    def start(self):
        """
        Set up the GameEngine and run the game

        @author: James Heslin (PROGRAM_IX)
        """
        pygame.init()
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption("PyStroke")
        self.engines = [GameEngine(self.screen, self.e_e)] # add others here
        self.engine = self.engines[0]
        self.run()

    def run(self):
        """
        Runs the GameEngine, switches to another GameEngine, or quits, based on
        returned flags from GameEngine

        @author: James Heslin (PROGRAM_IX)
        """
        while self.engine.run() == 0:
            if self.engines.index(self.engine) < len(self.engines) - 1:
                self.engine = self.engines[self.engines.index(self.engine) + 1]
            else:
                self.engine = self.engines[0]
        pygame.quit()
        raise SystemExit

def main():
    """
    Default running parameters for Game

    @author: James Heslin (PROGRAM_IX)
    """
    g = Game(800, 600)
    g.start()

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


<commit_before>__author__ = 'Patrick'

import pygame
import sys
from pygame.locals import *
from random import randint, choice

interval = 150
square_size = 16
spaces = 30
fps = []
images = ["./images/redsquare.png", "./images/redcircle.png",
          "./images/bluesquare.png", "./images/bluecircle.png",
          "./images/greensquare.png", "./images/greencircle.png",
          "./images/yellowsquare.png", "./images/yellowcircle.png"]

class Segment(pygame.sprite.Sprite):
    """Parent class for Head and Body"""
    def __init__(self):
        super(Segment, self).__init__()
        self.rect = pygame.Rect(0, 0, square_size, square_size)
        self.old_x = -1
        self.old_y = 0
        self.color = (0, 0, 0)

class Head(Segment):
    """The snake's head. Collision detection!"""
    def __init__(self):
        super(Head, self).__init__()
        global square_size
        self.image = pygame.Surface((square_size, square_size))
        self.image.fill(0)
        self.image.set_colorkey(0)
        pygame.draw.circle(self.image, (0, 255, 0), (16/2, 16/2), 16 / 2)
        self.x, self.y = 0, 0
        self.vector_x = 1
        self.vector_y = 0
        self.color = (0, 255, 0)

    def update(self):
        self.old_x, self.old_y = self.x, self.y
        self.x += self.vector_x
        self.y += self.vector_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)

class Body(Segment):
    """The Snake's body. Don't bite yourself."""
    def __init__(self, parent, art):
        super(Body, self).__init__()
        global square_size
        self.image = art
        self.image.set_colorkey((255, 0, 181))
        self.parent = parent
        self.x, self.y = parent.old_x, parent.old_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)
        self.color = (0, 127, 0)

    def update(self):
        self.old_x, self.old_y = self.x, self.y
        self.x, self.y = self.parent.old_x, self.parent.old_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)

class Snake(pygame.sprite.OrderedUpdates):
    """The snake. Eat the food. Get Bigger. Don't die."""
    def __init__(self):
        super(Snake, self).__init__()
        self.head = Head()
        self.add(self.head)
        self.body = []
        self.timer = 0
        self.food = Food()
        self.add(self.food)

    def update(self, time):
        self.timer += time
        global interval
        if self.timer >= interval:
            super(Snake, self).update()
            self.timer -= interval
            for b in self.body:
                if b.x == self.head.x and b.y == self.head.y:
                    self.quit("Yow!\nGame over, man.")
            if self.food.x == self.head.x and self.food.y == self.head.y:
                try:
                    self.body.append(Body(self.body[-1], self.food.image))
                except IndexError:
                    self.body.append(Body(self.head, self.food.image))
                self.add(self.body[-1])
                self.remove(self.food)
                self.food = Food()
                self.add(self.food)
            if self.head.x < 0 or self.head.x > 29 or\
               self.head.y < 0 or self.head.y > 29:
                self.quit("Watch the walls!\nGame over, man.")

    @staticmethod
    def quit(message):
        print(message)
        print("FPS: %f" % ((sum(fps) / len(fps))))
        pygame.quit()
        sys.exit()

class Food(pygame.sprite.Sprite):
    """Thing to eat. Yum."""
    def __init__(self):
        super(Food, self).__init__()
        self.x = randint(0, spaces - 1)
        self.y = randint(0, spaces - 1)
        spawn_y = self.y * square_size
        spawn_x = self.x * square_size
        self.rect = pygame.Rect(spawn_x, spawn_y, square_size, square_size)
        self.image = pygame.image.load(choice(images)).convert()
        self.image.set_colorkey((255, 0, 181))

pygame.init()
display = pygame.display.set_mode((square_size * spaces, square_size * spaces))
clock = pygame.time.Clock()
game = True
snake = Snake()

while game:
    time_elapsed = clock.tick()
    fps.append(clock.get_fps())
    for e in pygame.event.get():
        if e.type == QUIT:
            Snake.quit("You quit!")
        elif e.type == KEYDOWN:
            if snake.head.vector_x == 0:
                if e.key == K_RIGHT or e.key == K_d:
                    snake.head.vector_x = 1
                    snake.head.vector_y = 0
                elif e.key == K_LEFT or e.key == K_a:
                    snake.head.vector_x = -1
                    snake.head.vector_y = 0
            elif snake.head.vector_y == 0:
                if e.key == K_UP or e.key == K_w:
                    snake.head.vector_y = -1
                    snake.head.vector_x = 0
                elif e.key == K_DOWN or e.key == K_s:
                    snake.head.vector_y = 1
                    snake.head.vector_x = 0
    snake.update(time_elapsed)
    display.fill(0)
    pygame.display.update(snake.draw(display))<commit_msg>Added recursive collision code.<commit_after>__author__ = 'Patrick'

import pygame
import sys
from pygame.locals import *
from random import randint, choice

interval = 150
square_size = 16
half_square = square_size / 2
square_center = (half_square, half_square)
spaces = 20
images = ["./images/redsquare.png", "./images/redcircle.png",
          "./images/bluesquare.png", "./images/bluecircle.png",
          "./images/greensquare.png", "./images/greencircle.png",
          "./images/yellowsquare.png", "./images/yellowcircle.png"]
color_key = (255, 0, 181)

class Segment(pygame.sprite.Sprite):
    """Parent class for Head and Body"""
    def __init__(self):
        super(Segment, self).__init__()
        self.old_x = None
        self.old_y = None
        self.child = None
        self.parent = None

    def is_colliding_with(self, other):

        return (self.x, self.y) == (other.x, other.y)

class Head(Segment):
    """The snake's head. Collision detection!"""
    def __init__(self):
        super(Head, self).__init__()
        global square_size
        global half_square
        self.image = pygame.Surface((square_size, square_size))
        self.image.fill(0)
        self.image.set_colorkey(0)
        pygame.draw.circle(self.image, (0, 255, 0), square_center, half_square)
        self.x, self.y = 0, 0
        self.vector_x = 1
        self.vector_y = 0

    def update(self):
        self.old_x, self.old_y = self.x, self.y
        self.x += self.vector_x
        self.y += self.vector_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)

    def is_colliding_with_body(self):
        if self.child:
            return self._collision_helper(self.child)

    def _collision_helper(self, child):
        if child:
            return child.is_colliding_with(self) or self._collision_helper(child.child)
        else:
            return False

class Body(Segment):
    """The Snake's body. Don't bite yourself."""
    def __init__(self, parent, art):
        super(Body, self).__init__()
        global square_size
        self.image = art
        self.image.set_colorkey(color_key)
        self.parent = parent
        self.parent.child = self
        self.x, self.y = parent.old_x, parent.old_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)
        self.color = (0, 127, 0)

    def update(self):
        self.old_x, self.old_y = self.x, self.y
        self.x, self.y = self.parent.old_x, self.parent.old_y
        self.rect.topleft = (self.x * square_size, self.y * square_size)

class Snake(pygame.sprite.OrderedUpdates):
    """The snake. Eat the food. Get Bigger. Don't die."""
    def __init__(self):
        super(Snake, self).__init__()
        self.head = Head()
        self.add(self.head)
        self.timer = 0
        self.food = Food()
        self.add(self.food)

    def update(self, time):
        self.timer += time
        global interval
        if self.timer >= interval:
            super(Snake, self).update()
            self.timer -= interval
            if self.head.is_colliding_with_body():
                    self.quit("Yow!\nGame over, man.")
            if (self.food.x, self.food.y) == (self.head.x, self.head.y):
                self.add(Body(self._find_tail(self.head), self.food.image))
                self.remove(self.food)
                self.food = Food()
                self.add(self.food)
            if self.head.x < 0 or self.head.x > (spaces - 1) or\
               self.head.y < 0 or self.head.y > (spaces - 1):
                self.quit("Watch the walls!\nGame over, man.")

    @staticmethod
    def quit(message):
        print(message)
        pygame.quit()
        sys.exit()

    def _find_tail(self, segment):
        if segment.child:
            return self._find_tail(segment.child)
        else:
            return segment

class Food(pygame.sprite.Sprite):
    """Thing to eat. Yum."""
    def __init__(self):
        super(Food, self).__init__()
        self.x = randint(0, spaces - 1)
        self.y = randint(0, spaces - 1)
        spawn_y = self.y * square_size
        spawn_x = self.x * square_size
        self.rect = pygame.Rect(spawn_x, spawn_y, square_size, square_size)
        self.image = pygame.image.load(choice(images)).convert()
        self.image.set_colorkey(color_key)

pygame.init()
display = pygame.display.set_mode((square_size * spaces, square_size * spaces))
clock = pygame.time.Clock()
snake = Snake()

while True:
    time_elapsed = clock.tick()
    for e in pygame.event.get():
        if e.type == QUIT:
            Snake.quit("You quit!")
        elif e.type == KEYDOWN:
            if snake.head.vector_x == 0:
                if e.key == K_RIGHT or e.key == K_d:
                    snake.head.vector_x = 1
                    snake.head.vector_y = 0
                elif e.key == K_LEFT or e.key == K_a:
                    snake.head.vector_x = -1
                    snake.head.vector_y = 0
            elif snake.head.vector_y == 0:
                if e.key == K_UP or e.key == K_w:
                    snake.head.vector_y = -1
                    snake.head.vector_x = 0
                elif e.key == K_DOWN or e.key == K_s:
                    snake.head.vector_y = 1
                    snake.head.vector_x = 0
    snake.update(time_elapsed)
    display.fill(0)
    pygame.display.update(snake.draw(display))<|endoftext|>


<commit_before>import pygame, logging
from time import time, sleep
from random import randint
import eggs
from bullet import Bullet
from player import Shooter
from assets import *
from target import Target

PLAYING_GAME = False
WINDOW_SIZE = (640,480)

def update_score(window, score):
    font = pygame.font.SysFont(None, 30, bold=False)
    window.blit(font.render("Score: {}".format(int(score)), True, (255,0,0)), (25, WINDOW_SIZE[1] - 30))

def update_level(window, level):
    font = pygame.font.SysFont(None, 25, bold=True)
    window.blit(font.render("Level: {}".format(int(level)+1), True, (0,255,0)), (8.7*WINDOW_SIZE[0]/10, WINDOW_SIZE[1] - 30))

def update_lives(window, lives):
    font = pygame.font.SysFont(None, 30, bold=False)
    window.blit(font.render("Lives Remaining: {}".format(int(lives)), True, (0,0,255)), (4.5*WINDOW_SIZE[0]/10, WINDOW_SIZE[1] - 30))

def initialise(menu, options):
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.init()
    init_sounds()
    window = pygame.display.set_mode(WINDOW_SIZE)

    exit_code = play(window, options) # Run main game loop
    for key, value in Sounds.items():
        value.stop()

    logging.debug("Game Exited with code {}".format(exit_code))
    if exit_code != "QUIT": sleep(1)

    pygame.quit()
    menu.deiconify()
    return exit_code

def play(window, options):
    window_rect = window.get_rect()
    options["Textures"].load_texture_pack(options["Textures"].pack)
    player = Shooter(window=window, texture=options["Textures"])
    player.set_position(WINDOW_SIZE[0]/2, WINDOW_SIZE[1]*0.83)
    player.options = options
    player_group = pygame.sprite.Group()
    player_group.add(player)

    target_group = generate_targets(player, WINDOW_SIZE, Levels)
    bullet_group = pygame.sprite.Group()

    clock = pygame.time.Clock()
    FPS = player.options["Difficulty"]

    timeouts = {
        "Target Movement":[FPS*0.5,FPS*0.5],
        "Powerup":[FPS*100, FPS*100]
    }
    init_sounds()
    Sounds["main"].play(loops=-1) #Start background music

    logging.info("Game Started.")
    PLAYING_GAME = True
    while PLAYING_GAME:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                logging.critical("Exiting Game...")
                PLAYING_GAME = False
                return "QUIT"

            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                temp = Bullet(player, player.options["Textures"])
                Sounds["shot"].play()
                bullet_group.add(temp)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_KP_PLUS:
                player.OP = True
                Sounds["main"].stop()
                Sounds["OP"].play(loops=-1)

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            if player.powerup == "SPEED": player.move(player.speed * 1.5)
            else: player.move(player.speed)

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            if player.powerup == "SPEED": player.move(-player.speed*1.5)
            else: player.move(-player.speed)

        if keys[pygame.K_KP4] and keys[pygame.K_KP5] and keys[pygame.K_KP6] and player.OP:
            temp = Bullet(player, player.options["Textures"])
            bullet_group.add(temp)

        if keys[pygame.K_r] and [pygame.K_9] and [pygame.K_k] and player.OP:
            eggs.r9k(window)

        for sprite in bullet_group:
            sprite.update()
            if sprite.rect.y < 0 or (sprite.rect.y > player.rect.y and sprite.type == "TARGET"):
                bullet_group.remove(sprite)

        for bullet in bullet_group:
            hit_list = pygame.sprite.spritecollide(bullet, target_group, False)
            for target in hit_list:
                if bullet.type != "TARGET":
                    target_group.remove(target)
                    bullet_group.remove(bullet)
                    player.score += 1

            hit_list = pygame.sprite.spritecollide(bullet, player_group, False)
            for player in hit_list:
                if bullet.type == "TARGET":
                    bullet_group.remove(bullet)
                    logging.info("You were hit by a target's bullet!")
                    if not player.OP: player.lives -= 1
                    if player.lives <= 0:
                        return "LIVES"

        if timeouts["Target Movement"][0] <=0:
            drop_targets = False
            for target in target_group:
                target.move()
                if target.rect.x <= 30 or target.rect.x >=WINDOW_SIZE[0] - 30:
                    drop_targets = True

                if target.rect.y >= player.rect.y + 35:
                    PLAYING_GAME = False
                    return "PLAYER COLLISION"

            if drop_targets:
                logging.debug("The targets are moving down a level!")
                for target in target_group:
                    target.drop()

            timeouts["Target Movement"][0] = timeouts["Target Movement"][1]

        for target in target_group:
            if target.type == "SHOOTER":
                if randint(0,600) > 1: continue
                temp = Bullet(target, player.options["Textures"])
                temp.type="TARGET"
                temp.image = pygame.transform.scale(player.options["Textures"].get_texture("TARGET_BULLET"), (temp.width, temp.height))
                x,y = temp.rect.x, temp.rect.y
                temp.rect = temp.image.get_rect()
                temp.set_position(x,y)
                temp.speed = -1 #So it shoots down!
                bullet_group.add(temp)

        if len(target_group) == 0: #If all current players are gone.
            player.level += 1
            Sounds["main"].set_volume(0.5)
            target_group = generate_targets(player, WINDOW_SIZE, Levels)
            target_group.draw(window)
            bullet_group.empty()
            pygame.display.update()
            sleep(0.75)
            Sounds["main"].set_volume(1.0)

        if player.OP:
            player.change_colour((255,96,0)) #override colour change if changed before

        update_score(window, player.score)
        update_level(window, player.level)
        update_lives(window, player.lives)

        bullet_group.draw(window)
        target_group.draw(window)
        player_group.draw(window)

        for key, value in timeouts.items():
            value[0] -= 1

        pygame.display.update()
        clock.tick(FPS)<commit_msg>Bullets are now on top of targets<commit_after>import pygame, logging
from time import time, sleep
from random import randint
import eggs
from bullet import Bullet
from player import Shooter
from assets import *
from target import Target

PLAYING_GAME = False
WINDOW_SIZE = (640,480)

def update_score(window, score):
    font = pygame.font.SysFont(None, 30, bold=False)
    window.blit(font.render("Score: {}".format(int(score)), True, (255,0,0)), (25, WINDOW_SIZE[1] - 30))

def update_level(window, level):
    font = pygame.font.SysFont(None, 25, bold=True)
    window.blit(font.render("Level: {}".format(int(level)+1), True, (0,255,0)), (8.7*WINDOW_SIZE[0]/10, WINDOW_SIZE[1] - 30))

def update_lives(window, lives):
    font = pygame.font.SysFont(None, 30, bold=False)
    window.blit(font.render("Lives Remaining: {}".format(int(lives)), True, (0,0,255)), (4.5*WINDOW_SIZE[0]/10, WINDOW_SIZE[1] - 30))

def initialise(menu, options):
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.init()
    init_sounds()
    window = pygame.display.set_mode(WINDOW_SIZE)

    exit_code = play(window, options) # Run main game loop
    for key, value in Sounds.items():
        value.stop()

    logging.debug("Game Exited with code {}".format(exit_code))
    if exit_code != "QUIT": sleep(1)

    pygame.quit()
    menu.deiconify()
    return exit_code

def play(window, options):
    window_rect = window.get_rect()
    options["Textures"].load_texture_pack(options["Textures"].pack)
    player = Shooter(window=window, texture=options["Textures"])
    player.set_position(WINDOW_SIZE[0]/2, WINDOW_SIZE[1]*0.83)
    player.options = options
    player_group = pygame.sprite.Group()
    player_group.add(player)

    target_group = generate_targets(player, WINDOW_SIZE, Levels)
    bullet_group = pygame.sprite.Group()

    clock = pygame.time.Clock()
    FPS = player.options["Difficulty"]

    timeouts = {
        "Target Movement":[FPS*0.5,FPS*0.5],
        "Powerup":[FPS*100, FPS*100]
    }
    init_sounds()
    Sounds["main"].play(loops=-1) #Start background music

    logging.info("Game Started.")
    PLAYING_GAME = True
    while PLAYING_GAME:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                logging.critical("Exiting Game...")
                PLAYING_GAME = False
                return "QUIT"

            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                temp = Bullet(player, player.options["Textures"])
                Sounds["shot"].play()
                bullet_group.add(temp)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_KP_PLUS:
                player.OP = True
                Sounds["main"].stop()
                Sounds["OP"].play(loops=-1)

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            if player.powerup == "SPEED": player.move(player.speed * 1.5)
            else: player.move(player.speed)

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            if player.powerup == "SPEED": player.move(-player.speed*1.5)
            else: player.move(-player.speed)

        if keys[pygame.K_KP4] and keys[pygame.K_KP5] and keys[pygame.K_KP6] and player.OP:
            temp = Bullet(player, player.options["Textures"])
            bullet_group.add(temp)

        if keys[pygame.K_r] and [pygame.K_9] and [pygame.K_k] and player.OP:
            eggs.r9k(window)

        for sprite in bullet_group:
            sprite.update()
            if sprite.rect.y < 0 or (sprite.rect.y > player.rect.y and sprite.type == "TARGET"):
                bullet_group.remove(sprite)

        for bullet in bullet_group:
            hit_list = pygame.sprite.spritecollide(bullet, target_group, False)
            for target in hit_list:
                if bullet.type != "TARGET":
                    target_group.remove(target)
                    bullet_group.remove(bullet)
                    player.score += 1

            hit_list = pygame.sprite.spritecollide(bullet, player_group, False)
            for player in hit_list:
                if bullet.type == "TARGET":
                    bullet_group.remove(bullet)
                    logging.info("You were hit by a target's bullet!")
                    if not player.OP: player.lives -= 1
                    if player.lives <= 0:
                        return "LIVES"

        if timeouts["Target Movement"][0] <=0:
            drop_targets = False
            for target in target_group:
                target.move()
                if target.rect.x <= 30 or target.rect.x >=WINDOW_SIZE[0] - 30:
                    drop_targets = True

                if target.rect.y >= player.rect.y + 35:
                    PLAYING_GAME = False
                    return "PLAYER COLLISION"

            if drop_targets:
                logging.debug("The targets are moving down a level!")
                for target in target_group:
                    target.drop()

            timeouts["Target Movement"][0] = timeouts["Target Movement"][1]

        for target in target_group:
            if target.type == "SHOOTER":
                if randint(0,600) > 1: continue
                temp = Bullet(target, player.options["Textures"])
                temp.type="TARGET"
                temp.image = pygame.transform.scale(player.options["Textures"].get_texture("TARGET_BULLET"), (temp.width, temp.height))
                x,y = temp.rect.x, temp.rect.y
                temp.rect = temp.image.get_rect()
                temp.set_position(x,y)
                temp.speed = -1 #So it shoots down!
                bullet_group.add(temp)

        if len(target_group) == 0: #If all current players are gone.
            player.level += 1
            Sounds["main"].set_volume(0.5)
            target_group = generate_targets(player, WINDOW_SIZE, Levels)
            target_group.draw(window)
            bullet_group.empty()
            pygame.display.update()
            sleep(0.75)
            Sounds["main"].set_volume(1.0)

        if player.OP:
            player.change_colour((255,96,0)) #override colour change if changed before

        update_score(window, player.score)
        update_level(window, player.level)
        update_lives(window, player.lives)

        target_group.draw(window)
        bullet_group.draw(window)
        player_group.draw(window)

        for key, value in timeouts.items():
            value[0] -= 1

        pygame.display.update()
        clock.tick(FPS)<|endoftext|>


<commit_before>import copy
import logging

from django.apps import apps

from share import disambiguation

logger = logging.getLogger(__name__)

class GraphParsingException(Exception):
    pass

class CyclicalDependency(GraphParsingException):
    pass

class UnresolvableReference(GraphParsingException):
    pass

class ChangeNode:

    @classmethod
    def from_jsonld(self, ld_graph, disambiguate=True, extra_namespace=None):
        return ChangeNode(ld_graph, disambiguate=disambiguate, extra_namespace=extra_namespace)

    @property
    def model(self):
        if self.is_merge:
            return apps.get_model('share', self.relations['into']['@type'].lower())
        return apps.get_model('share', self.type.lower())

    @property
    def instance(self):
        return self.__instance

    @property
    def is_blank(self):
        # JSON-LD Blank Node ids start with "_:"
        return self.is_merge or (isinstance(self.id, str) and self.id.startswith('_:'))

    @property
    def is_merge(self):
        return self.type.lower() == 'mergeaction'

    @property
    def refs(self):
        return self.__refs

    @property
    def change(self):
        if self.is_merge:
            return {**self.attrs, **self.relations, **self._reverse_relations}

        if self.is_blank:
            ret = {**self.attrs, **self.relations}
            if self.extra:
                ret['extra'] = self.extra
            return ret

        if not self.instance:
            raise UnresolvableReference('@id: {!r}, @type: {!r}'.format(self.id, self.type))

        ret = {k: v for k, v in self.attrs.items() if getattr(self.instance, k) != v}
        if self.__extra_namespace:
            ret['extra'] = {
                k: v for k, v in self.extra.items()
                if not (self.instance.extra and self.instance.extra.get(self.__extra_namespace))
                or self.instance.extra.data[self.__extra_namespace].get(k) != v
            }

            if not ret['extra']:
                del ret['extra']

        return ret

    def __init__(self, node, disambiguate=True, extra_namespace=None):
        self.__raw = node
        self.__change = None
        self.__instance = None
        self.__extra_namespace = None
        node = copy.deepcopy(self.__raw)

        self.id = str(node.pop('@id'))
        self.type = node.pop('@type').lower()
        self.extra = node.pop('extra', {})

        self.__refs = [(self.id, self.type)]

        # JSON-LD variables are all prefixed with '@'s
        self.context = {k: node.pop(k) for k in tuple(node.keys()) if k[0] == '@'}
        # Any nested data type is a relation in the current JSON-LD schema
        self.relations = {k: node.pop(k) for k, v in tuple(node.items()) if isinstance(v, dict)}
        self.related = tuple(self.relations.values())
        self._reverse_relations = {k: tuple(node.pop(k)) for k, v in tuple(node.items()) if isinstance(v, (list, tuple))}

        if self.is_merge:
            self.related += sum(self._reverse_relations.values(), tuple())

        self.attrs = node

        if disambiguate:
            self._disambiguate()

    def update_relations(self, mapper):
        for v in self.relations.values():
            node = mapper[(v['@id'], v['@type'].lower())]
            v['@id'] = node.id
            v['@type'] = node.type

    def _disambiguate(self):
        if self.is_merge:
            return None
        self.__instance = disambiguation.disambiguate(self.id, {
            **self.attrs,
            **{k: v['@id'] for k, v in self.relations.items() if not str(v['@id']).startswith('_:')}
        }, self.model)
        if self.__instance:
            self.id = self.__instance.pk
            self.__refs.append((self.id, self.type))

class ChangeGraph:

    @classmethod
    def from_jsonld(self, ld_graph, disambiguate=True, extra_namespace=None):
        nodes = [ChangeNode.from_jsonld(obj, disambiguate=disambiguate, extra_namespace=extra_namespace) for obj in ld_graph['@graph']]
        return ChangeGraph(nodes, disambiguate=disambiguate)

    @property
    def nodes(self):
        return self.__nodes

    def __init__(self, nodes, parse=True, disambiguate=True):
        self.__nodes = nodes
        self.__map = {ref: n for n in nodes for ref in n.refs}
        self.__sorter = NodeSorter(self)

        # TODO This could probably be more efficiant
        if disambiguate:
            for n in self.__nodes:
                n._disambiguate()
            for n in self.__nodes:
                n.update_relations(self.__map)

        if parse:
            self.__nodes = self.__sorter.sorted()

    def get_node(self, id, type):
        try:
            return self.__map[(id, type.lower())]
        except KeyError:
            if str(id).startswith('_:'):
                raise UnresolvableReference('Unresolvable reference @id: {!r}, @type: {!r}'.format(id, type))
        return None  # External reference to an already existing object

class NodeSorter:

    def __init__(self, graph):
        self.__sorted = []
        self.__graph = graph
        self.__visted = set()
        self.__visiting = set()
        self.__nodes = list(graph.nodes)

    def sorted(self):
        if not self.__nodes:
            return self.__sorted

        while self.__nodes:
            n = self.__nodes.pop(0)
            self.__visit(n)

        return self.__sorted

    def __visit(self, node):
        if node in self.__visiting:
            raise CyclicalDependency()

        if node in self.__visted:
            return

        self.__visiting.add(node)
        for relation in node.related:
            n = self.__graph.get_node(relation['@id'], relation['@type'])
            if n:
                self.__visit(n)

        self.__visted.add(node)
        self.__sorted.append(node)
        self.__visiting.remove(node)
<commit_msg>Wierd case with merges<commit_after>import copy
import logging

from django.apps import apps

from share import disambiguation

logger = logging.getLogger(__name__)

class GraphParsingException(Exception):
    pass

class CyclicalDependency(GraphParsingException):
    pass

class UnresolvableReference(GraphParsingException):
    pass

class ChangeNode:

    @classmethod
    def from_jsonld(self, ld_graph, disambiguate=True, extra_namespace=None):
        return ChangeNode(ld_graph, disambiguate=disambiguate, extra_namespace=extra_namespace)

    @property
    def model(self):
        if self.is_merge:
            return apps.get_model('share', self.relations['into']['@type'].lower())
        return apps.get_model('share', self.type.lower())

    @property
    def instance(self):
        return self.__instance

    @property
    def is_blank(self):
        # JSON-LD Blank Node ids start with "_:"
        return self.is_merge or (isinstance(self.id, str) and self.id.startswith('_:'))

    @property
    def is_merge(self):
        return self.type.lower() == 'mergeaction'

    @property
    def refs(self):
        return self.__refs

    @property
    def change(self):
        if self.is_merge:
            return {**self.attrs, **self.relations, **self._reverse_relations}

        if self.is_blank:
            ret = {**self.attrs, **self.relations}
            if self.extra:
                ret['extra'] = self.extra
            return ret

        if not self.instance:
            raise UnresolvableReference('@id: {!r}, @type: {!r}'.format(self.id, self.type))

        ret = {k: v for k, v in self.attrs.items() if getattr(self.instance, k) != v}
        if self.__extra_namespace:
            ret['extra'] = {
                k: v for k, v in self.extra.items()
                if not (self.instance.extra and self.instance.extra.get(self.__extra_namespace))
                or self.instance.extra.data[self.__extra_namespace].get(k) != v
            }

            if not ret['extra']:
                del ret['extra']

        return ret

    def __init__(self, node, disambiguate=True, extra_namespace=None):
        self.__raw = node
        self.__change = None
        self.__instance = None
        self.__extra_namespace = None
        node = copy.deepcopy(self.__raw)

        self.id = str(node.pop('@id'))
        self.type = node.pop('@type').lower()
        self.extra = node.pop('extra', {})

        self.__refs = [(self.id, self.type)]

        # JSON-LD variables are all prefixed with '@'s
        self.context = {k: node.pop(k) for k in tuple(node.keys()) if k[0] == '@'}
        # Any nested data type is a relation in the current JSON-LD schema
        self.relations = {k: node.pop(k) for k, v in tuple(node.items()) if isinstance(v, dict)}
        self.related = tuple(self.relations.values())
        self._reverse_relations = {k: tuple(node.pop(k)) for k, v in tuple(node.items()) if isinstance(v, (list, tuple))}

        if self.is_merge:
            self.related += sum(self._reverse_relations.values(), tuple())

        self.attrs = node

        if disambiguate:
            self._disambiguate()

    def update_relations(self, mapper):
        for v in self.relations.values():
            try:
                node = mapper[(v['@id'], v['@type'].lower())]
                v['@id'] = node.id
                v['@type'] = node.type
            except KeyError:
                pass

    def _disambiguate(self):
        if self.is_merge:
            return None
        self.__instance = disambiguation.disambiguate(self.id, {
            **self.attrs,
            **{k: v['@id'] for k, v in self.relations.items() if not str(v['@id']).startswith('_:')}
        }, self.model)
        if self.__instance:
            self.id = self.__instance.pk
            self.__refs.append((self.id, self.type))

class ChangeGraph:

    @classmethod
    def from_jsonld(self, ld_graph, disambiguate=True, extra_namespace=None):
        nodes = [ChangeNode.from_jsonld(obj, disambiguate=disambiguate, extra_namespace=extra_namespace) for obj in ld_graph['@graph']]
        return ChangeGraph(nodes, disambiguate=disambiguate)

    @property
    def nodes(self):
        return self.__nodes

    def __init__(self, nodes, parse=True, disambiguate=True):
        self.__nodes = nodes
        self.__map = {ref: n for n in nodes for ref in n.refs}
        self.__sorter = NodeSorter(self)

        # TODO This could probably be more efficiant
        if disambiguate:
            for n in self.__nodes:
                n._disambiguate()
            for n in self.__nodes:
                n.update_relations(self.__map)

        if parse:
            self.__nodes = self.__sorter.sorted()

    def get_node(self, id, type):
        try:
            return self.__map[(id, type.lower())]
        except KeyError:
            if str(id).startswith('_:'):
                raise UnresolvableReference('Unresolvable reference @id: {!r}, @type: {!r}'.format(id, type))
        return None  # External reference to an already existing object

class NodeSorter:

    def __init__(self, graph):
        self.__sorted = []
        self.__graph = graph
        self.__visted = set()
        self.__visiting = set()
        self.__nodes = list(graph.nodes)

    def sorted(self):
        if not self.__nodes:
            return self.__sorted

        while self.__nodes:
            n = self.__nodes.pop(0)
            self.__visit(n)

        return self.__sorted

    def __visit(self, node):
        if node in self.__visiting:
            raise CyclicalDependency()

        if node in self.__visted:
            return

        self.__visiting.add(node)
        for relation in node.related:
            n = self.__graph.get_node(relation['@id'], relation['@type'])
            if n:
                self.__visit(n)

        self.__visted.add(node)
        self.__sorted.append(node)
        self.__visiting.remove(node)
<|endoftext|>


<commit_before>#!/usr/bin/env python2
import rospy

from geometry_msgs.msg import Twist, Vector3
from std_msgs.msg import Empty

PUB_RATE = 50

def forward(time, cmd_vel):
    """Move forward for time seconds"""
    rate = rospy.Rate(PUB_RATE)
    end = rospy.get_time() + time

    while rospy.get_time() < end:
        cmd_vel.publish(Twist(Vector3(1,0,0), Vector3(0,0,0)))
        rate.sleep()
        yield

def turn(time, dir, cmd_vel):
    """Turn in dir (+/- 1) for time seconds"""
    rate = rospy.Rate(PUB_RATE)
    end = rospy.get_time() + time

    while rospy.get_time() < end:
        cmd_vel.publish(Twist(Vector3(0,0,0), Vector3(0,0,dir)))
        rate.sleep()
        yield

def run_auto(takeoff, land, cmd_vel):
    rospy.sleep(2)

    takeoff.publish(Empty())
    print 'Takeoff'

    rospy.sleep(2)
    yield

    for i in forward(3, cmd_vel): pass

    for i in turn(1, 1, cmd_vel): pass

    for i in forward(3, cmd_vel): pass

    rospy.sleep(1)
    yield

    land.publish(Empty())
    print 'Land'

def main():
    takeoff = rospy.Publisher('ardrone/takeoff', Empty, queue_size=1)
    land = rospy.Publisher('ardrone/land', Empty, queue_size=1)
    cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=10)

    rospy.init_node('ar_prescripted', anonymous=True)

    step = run_auto(takeoff, land, cmd_vel)
    while not rospy.is_shutdown():
        try:
            next(step)
        except StopIteration:
            break

if __name__ == '__main__':
    main()
<commit_msg>prescripted flight switched to just publish, didn't need to repeat commands<commit_after>#!/usr/bin/env python2
import rospy

from geometry_msgs.msg import Twist, Vector3
from std_msgs.msg import Empty

PUB_RATE = 50

def run_auto(takeoff, land, cmd_vel):
    rospy.sleep(2)

    takeoff.publish(Empty())
    print 'Takeoff'

    rospy.sleep(2)
    yield

    cmd_vel.publish(Twist(Vector3(1,0,0), Vector3(0,0,0)))
    rospy.sleep(3)
    yield

    cmd_vel.publish(Twist(Vector3(0,0,0), Vector3(0,0,1)))
    rospy.sleep(1.5)
    yield

    cmd_vel.publish(Twist(Vector3(1,0,0), Vector3(0,0,0)))
    rospy.sleep(3)
    yield

    cmd_vel.publish(Twist(Vector3(0,0,0), Vector3(0,0,0)))
    rospy.sleep(1)
    yield

    land.publish(Empty())
    print 'Land'

def main():
    takeoff = rospy.Publisher('ardrone/takeoff', Empty, queue_size=1)
    land = rospy.Publisher('ardrone/land', Empty, queue_size=1)
    cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=10)

    rospy.init_node('ar_prescripted', anonymous=True)

    step = run_auto(takeoff, land, cmd_vel)
    while not rospy.is_shutdown():
        try:
            next(step)
        except StopIteration:
            break

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


<commit_before>from __future__ import division
import math
import torch
import torch.optim as optim

class SharedRMSprop(optim.RMSprop):
    """Implements RMSprop algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=1e-2,
                 alpha=0.99,
                 eps=1e-8,
                 weight_decay=0,
                 momentum=0,
                 centered=False):
        super(SharedRMSprop, self).__init__(params, lr, alpha, eps,
                                            weight_decay, momentum, centered)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['grad_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['square_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['momentum_buffer'] = p.data.new().resize_as_(
                    p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['square_avg'].share_memory_()
                state['step'].share_memory_()
                state['grad_avg'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                square_avg = state['square_avg']
                alpha = group['alpha']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                square_avg.mul_(alpha).addcmul_(1 - alpha, grad, grad)

                if group['centered']:
                    grad_avg = state['grad_avg']
                    grad_avg.mul_(alpha).add_(1 - alpha, grad)
                    avg = square_avg.addcmul(
                        -1, grad_avg, grad_avg).sqrt().add_(group['eps'])
                else:
                    avg = square_avg.sqrt().add_(group['eps'])

                if group['momentum'] > 0:
                    buf = state['momentum_buffer']
                    buf.mul_(group['momentum']).addcdiv_(grad, avg)
                    p.data.add_(-group['lr'], buf)
                else:
                    p.data.addcdiv_(-group['lr'], grad, avg)

        return loss

class SharedAdam(optim.Adam):
    """Implements Adam algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=1e-3,
                 betas=(0.9, 0.999),
                 eps=1e-3,
                 weight_decay=0):
        super(SharedAdam, self).__init__(params, lr, betas, eps, weight_decay)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['exp_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['exp_avg_sq'] = p.data.new().resize_as_(p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'].share_memory_()
                state['exp_avg'].share_memory_()
                state['exp_avg_sq'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                beta1, beta2 = group['betas']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                # Decay the first and second moment running average coefficient
                exp_avg.mul_(beta1).add_(1 - beta1, grad)
                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)

                denom = exp_avg_sq.sqrt().add_(group['eps'])

                bias_correction1 = 1 - beta1**state['step'][0]
                bias_correction2 = 1 - beta2**state['step'][0]
                step_size = group['lr'] * \
                    math.sqrt(bias_correction2) / bias_correction1

                p.data.addcdiv_(-step_size, exp_avg, denom)

        return loss

sample_lr = [
    0.0001, 0.00009, 0.00008, 0.00007, 0.00006, 0.00005, 0.00004, 0.00003,
    0.00002, 0.00001, 0.000009, 0.000008, 0.000007, 0.000006, 0.000005,
    0.000004, 0.000003, 0.000002, 0.000001
]

class SharedLrSchedAdam(optim.Adam):
    """Implements Adam algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=1e-3,
                 betas=(0.9, 0.999),
                 eps=1e-3,
                 weight_decay=0):
        super(SharedLrSchedAdam, self).__init__(params, lr, betas, eps,
                                                weight_decay)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['exp_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['exp_avg_sq'] = p.data.new().resize_as_(p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'].share_memory_()
                state['exp_avg'].share_memory_()
                state['exp_avg_sq'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        lr = sample_lr[int(state['step'][0] // 40000000)]
        group['lr'] = lr

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                beta1, beta2 = group['betas']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                # Decay the first and second moment running average coefficient
                exp_avg.mul_(beta1).add_(1 - beta1, grad)
                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)

                denom = exp_avg_sq.sqrt().add_(group['eps'])

                bias_correction1 = 1 - beta1**state['step'][0]
                bias_correction2 = 1 - beta2**state['step'][0]
                step_size = group['lr'] * \
                    math.sqrt(bias_correction2) / bias_correction1
                p.data.addcdiv_(-step_size, exp_avg, denom)

        return loss
<commit_msg>update<commit_after>from __future__ import division
import math
import torch
import torch.optim as optim

class SharedRMSprop(optim.RMSprop):
    """Implements RMSprop algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=7e-4,
                 alpha=0.99,
                 eps=0.1,
                 weight_decay=0,
                 momentum=0,
                 centered=False):
        super(SharedRMSprop, self).__init__(params, lr, alpha, eps,
                                            weight_decay, momentum, centered)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['grad_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['square_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['momentum_buffer'] = p.data.new().resize_as_(
                    p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['square_avg'].share_memory_()
                state['step'].share_memory_()
                state['grad_avg'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                square_avg = state['square_avg']
                alpha = group['alpha']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                square_avg.mul_(alpha).addcmul_(1 - alpha, grad, grad)

                if group['centered']:
                    grad_avg = state['grad_avg']
                    grad_avg.mul_(alpha).add_(1 - alpha, grad)
                    avg = square_avg.addcmul(
                        -1, grad_avg, grad_avg).sqrt().add_(group['eps'])
                else:
                    avg = square_avg.sqrt().add_(group['eps'])

                if group['momentum'] > 0:
                    buf = state['momentum_buffer']
                    buf.mul_(group['momentum']).addcdiv_(grad, avg)
                    p.data.add_(-group['lr'], buf)
                else:
                    p.data.addcdiv_(-group['lr'], grad, avg)

        return loss

class SharedAdam(optim.Adam):
    """Implements Adam algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=1e-3,
                 betas=(0.9, 0.999),
                 eps=1e-3,
                 weight_decay=0):
        super(SharedAdam, self).__init__(params, lr, betas, eps, weight_decay)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['exp_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['exp_avg_sq'] = p.data.new().resize_as_(p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'].share_memory_()
                state['exp_avg'].share_memory_()
                state['exp_avg_sq'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                beta1, beta2 = group['betas']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                # Decay the first and second moment running average coefficient
                exp_avg.mul_(beta1).add_(1 - beta1, grad)
                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)

                denom = exp_avg_sq.sqrt().add_(group['eps'])

                bias_correction1 = 1 - beta1**state['step'][0]
                bias_correction2 = 1 - beta2**state['step'][0]
                step_size = group['lr'] * \
                    math.sqrt(bias_correction2) / bias_correction1

                p.data.addcdiv_(-step_size, exp_avg, denom)

        return loss

sample_lr = [
    0.0001, 0.00009, 0.00008, 0.00007, 0.00006, 0.00005, 0.00004, 0.00003,
    0.00002, 0.00001, 0.000009, 0.000008, 0.000007, 0.000006, 0.000005,
    0.000004, 0.000003, 0.000002, 0.000001
]

class SharedLrSchedAdam(optim.Adam):
    """Implements Adam algorithm with shared states.
    """

    def __init__(self,
                 params,
                 lr=1e-3,
                 betas=(0.9, 0.999),
                 eps=1e-3,
                 weight_decay=0):
        super(SharedLrSchedAdam, self).__init__(params, lr, betas, eps,
                                                weight_decay)

        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'] = torch.zeros(1)
                state['exp_avg'] = p.data.new().resize_as_(p.data).zero_()
                state['exp_avg_sq'] = p.data.new().resize_as_(p.data).zero_()

    def share_memory(self):
        for group in self.param_groups:
            for p in group['params']:
                state = self.state[p]
                state['step'].share_memory_()
                state['exp_avg'].share_memory_()
                state['exp_avg_sq'].share_memory_()

    def step(self, closure=None):
        """Performs a single optimization step.
        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            loss = closure()

        lr = sample_lr[int(state['step'][0] // 40000000)]
        group['lr'] = lr

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad.data
                state = self.state[p]

                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                beta1, beta2 = group['betas']

                state['step'] += 1

                if group['weight_decay'] != 0:
                    grad = grad.add(group['weight_decay'], p.data)

                # Decay the first and second moment running average coefficient
                exp_avg.mul_(beta1).add_(1 - beta1, grad)
                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)

                denom = exp_avg_sq.sqrt().add_(group['eps'])

                bias_correction1 = 1 - beta1**state['step'][0]
                bias_correction2 = 1 - beta2**state['step'][0]
                step_size = group['lr'] * \
                    math.sqrt(bias_correction2) / bias_correction1
                p.data.addcdiv_(-step_size, exp_avg, denom)

        return loss
<|endoftext|>