<commit_before>import json, socket

import requests

from CommandTemplate import CommandTemplate
import GlobalStore
from IrcMessage import IrcMessage

class Command(CommandTemplate):
	triggers = ['location']
	helptext = "Retrieves the country a user is from (or at least it tries to, no promises). Arguments are a user name, and optionally a channel name (which is mainly useful in PMs)"

	def execute(self, message):
		"""
		:type message: IrcMessage
		"""

		#First check for the presence of the API key
		if not GlobalStore.commandhandler.apikeys.has_section('locatorhq') or not GlobalStore.commandhandler.apikeys.has_option('locatorhq', 'key') or not GlobalStore.commandhandler.apikeys.has_option('locatorhq', 'username'):
			message.bot.say(message.source, u"I'm sorry, my owner hasn't filled in the required API key for this module. Please poke them to add it")
			return

		replytext = u""
		userAddress = u""

		#no parameters added. Look up location of this user
		if message.messagePartsLength == 0:
			userAddress = message.user
		#Allow for any user address to be entered
		elif u'@' in message.messageParts[0]:
			userAddress = message.messageParts[0]
		#A username was provided. Convert that to a full user address
		else:
			#Check if a channel name was provided as well
			if message.messagePartsLength < 2 and message.isPrivateMessage:
				#If no channel was specified, and we're not in a channel currently, we can't really do anything. Inform the user of that
				replytext = u"If you use this script in a private message, you have to provide the channel to look in as the second parameter, " \
							u"otherwise I don't know where to look"
			else:
				channelname = message.source
				#A channel name was provided, only search that channel
				if message.messagePartsLength >= 2:
					channelname = message.messageParts[1]
					if not channelname.startswith('#'):
						channelname = '#' + channelname
				if channelname not in message.bot.channelsUserList:
					replytext = u"That is not a channel I'm familiar with, sorry"
				else:
					nickToMatch = message.messageParts[0].lower() + '!'  #Add an exclamation mark to make sure the match is the full nick, not just the start
					replytext = u"I'm sorry, but I don't know who you're talking about..."  #Set it in advance, in case we don't find a match
					for channelUserAddress in message.bot.channelsUserList[channelname]:
						if channelUserAddress.lower().startswith(nickToMatch):
							userAddress = channelUserAddress
							break

		if userAddress != u"":
			username = userAddress.split("!", 1)[0]
			if username == userAddress:
				username = u'that user'

			#Try to turn the hostname into an IP address. Take off parts from the front until we have one or run out of parts
			userIp = ""
			userHostname = userAddress.split('@', 1)[1]
			userHostnameParts = userHostname.split('.')
			while userIp == "" and len(userHostnameParts) > 1:
				try:
					userIp = socket.gethostbyname(".".join(userHostnameParts))
				except socket.gaierror:
					userHostnameParts.pop(0)

			if userIp == "":
				replytext = u"I'm sorry, I couldn't determine the IP address of {username}".format(username=username)
			else:
				params = {'key': GlobalStore.commandhandler.apikeys.get('locatorhq', 'key'),
						  'user': GlobalStore.commandhandler.apikeys.get('locatorhq', 'username'), 'ip': userIp, 'format': 'json'}
				apiReturn = requests.get("http://api.locatorhq.com", params=params)

				try:
					data = json.loads(apiReturn.text)
				except ValueError:
					#If there's an error message in the API output, it's not valid JSON. Check if we know what's wrong
					print "[location] ERROR, API returned: '{}'".format(apiReturn.text)
					error = apiReturn.text.lower()
					if error == 'no data':
						replytext = u"I'm sorry, I can't find any country data for {username}".format(username=username)
					elif "server too busy" in error:
						replytext = u"The location lookup API is a bit busy, please try again in a little while"
					else:
						#Unknown error, vague error report
						replytext = u"Sorry, an error occurred. Tell my owner to check the debug output, the exact error is in there"
				else:
					if 'countryName' not in data or data['countryName'] == '-':
						replytext = u"I'm sorry, but I can't seem to determine which country {username} is from".format(username=username)
					else:
						if username == message.bot.nickname.lower():
							replytext = u"I'm right here for you! And by 'here' I mean {country}".format(country=data['countryName'])
						else:
							replytext = u"{username} appears to be from {country}".format(username=username, country=data['countryName'])

		message.bot.say(message.source, replytext)
<commit_msg>[Location] Don't say people are  from the country 'None', that's rude<commit_after>import json, socket

import requests

from CommandTemplate import CommandTemplate
import GlobalStore
from IrcMessage import IrcMessage

class Command(CommandTemplate):
	triggers = ['location']
	helptext = "Retrieves the country a user is from (or at least it tries to, no promises). Arguments are a user name, and optionally a channel name (which is mainly useful in PMs)"

	def execute(self, message):
		"""
		:type message: IrcMessage
		"""

		#First check for the presence of the API key
		if not GlobalStore.commandhandler.apikeys.has_section('locatorhq') or not GlobalStore.commandhandler.apikeys.has_option('locatorhq', 'key') or not GlobalStore.commandhandler.apikeys.has_option('locatorhq', 'username'):
			message.bot.say(message.source, u"I'm sorry, my owner hasn't filled in the required API key for this module. Please poke them to add it")
			return

		replytext = u""
		userAddress = u""

		#no parameters added. Look up location of this user
		if message.messagePartsLength == 0:
			userAddress = message.user
		#Allow for any user address to be entered
		elif u'@' in message.messageParts[0]:
			userAddress = message.messageParts[0]
		#A username was provided. Convert that to a full user address
		else:
			#Check if a channel name was provided as well
			if message.messagePartsLength < 2 and message.isPrivateMessage:
				#If no channel was specified, and we're not in a channel currently, we can't really do anything. Inform the user of that
				replytext = u"If you use this script in a private message, you have to provide the channel to look in as the second parameter, " \
							u"otherwise I don't know where to look"
			else:
				channelname = message.source
				#A channel name was provided, only search that channel
				if message.messagePartsLength >= 2:
					channelname = message.messageParts[1]
					if not channelname.startswith('#'):
						channelname = '#' + channelname
				if channelname not in message.bot.channelsUserList:
					replytext = u"That is not a channel I'm familiar with, sorry"
				else:
					nickToMatch = message.messageParts[0].lower() + '!'  #Add an exclamation mark to make sure the match is the full nick, not just the start
					replytext = u"I'm sorry, but I don't know who you're talking about..."  #Set it in advance, in case we don't find a match
					for channelUserAddress in message.bot.channelsUserList[channelname]:
						if channelUserAddress.lower().startswith(nickToMatch):
							userAddress = channelUserAddress
							break

		if userAddress != u"":
			username = userAddress.split("!", 1)[0]
			if username == userAddress:
				username = u'that user'

			#Try to turn the hostname into an IP address. Take off parts from the front until we have one or run out of parts
			userIp = ""
			userHostname = userAddress.split('@', 1)[1]
			userHostnameParts = userHostname.split('.')
			while userIp == "" and len(userHostnameParts) > 1:
				try:
					userIp = socket.gethostbyname(".".join(userHostnameParts))
				except socket.gaierror:
					userHostnameParts.pop(0)

			if userIp == "":
				replytext = u"I'm sorry, I couldn't determine the IP address of {username}".format(username=username)
			elif userIp == "127.0.0.1":
				replytext = u"That's on my server! And I'm right here"
			else:
				params = {'key': GlobalStore.commandhandler.apikeys.get('locatorhq', 'key'),
						  'user': GlobalStore.commandhandler.apikeys.get('locatorhq', 'username'), 'ip': userIp, 'format': 'json'}
				apiReturn = requests.get("http://api.locatorhq.com", params=params)

				try:
					data = json.loads(apiReturn.text)
				except ValueError:
					#If there's an error message in the API output, it's not valid JSON. Check if we know what's wrong
					print "[location] ERROR, API returned: '{}'".format(apiReturn.text)
					error = apiReturn.text.lower()
					if error == 'no data':
						replytext = u"I'm sorry, I can't find any country data for {username}".format(username=username)
					elif "server too busy" in error:
						replytext = u"The location lookup API is a bit busy, please try again in a little while"
					else:
						#Unknown error, vague error report
						replytext = u"Sorry, an error occurred. Tell my owner to check the debug output, the exact error is in there"
				else:
					if 'countryName' not in data or data['countryName'] in ['-', 'None', None]:
						replytext = u"I'm sorry, but I can't seem to determine which country {username} is from".format(username=username)
					else:
						if username == message.bot.nickname.lower():
							replytext = u"I'm right here for you! And by 'here' I mean {country}".format(country=data['countryName'])
						else:
							replytext = u"{username} appears to be from {country}".format(username=username, country=data['countryName'])

		message.bot.say(message.source, replytext)
<|endoftext|>


<commit_before>"""
Multi-page TIFF parser

"""

from donomo.archive       import models, operations
from donomo.archive.utils import image
from django.conf          import settings

import glob
import os

DEFAULT_INPUTS  = (
    models.AssetClass.UPLOAD,
    )

DEFAULT_OUTPUTS = (
    models.AssetClass.DOCUMENT,
    models.AssetClass.PAGE_ORIGINAL,
    models.AssetClass.PAGE_IMAGE,
    models.AssetClass.PAGE_THUMBNAIL,
    )

DEFAULT_ACCEPTED_MIME_TYPES = (
    models.MimeType.TIFF,
    )

##############################################################################

def handle_work_item(processor, item):

    """ Pick up a (possibly) multipage TIFF upload and turn it into a
        document having (possibly) multiple individual pages.

    """

    new_work    = []
    asset       = item['Asset-Instance']
    local_path  = item['Local-Path']
    work_dir    = os.path.dirname(local_path)
    page_prefix = os.path.join(work_dir, 'page-')

    os.system( 'tiffsplit %r %r' % (local_path, page_prefix) )

    document = operations.create_document(
        owner = asset.owner,
        title = 'Uploaded on %s (%s)' % (
            asset.date_created,
            asset.producer.process ))

    position = 1
    all_page_files = glob.glob('%s*.tif*' % page_prefix)
    all_page_files.sort()
    for page_tiff_path in all_page_files:
        new_work.extend(
            handle_page(
                processor,
                asset,
                document,
                page_tiff_path,
                position ))
        position += 1

    if document is not None:
        new_work.append(
            document.assets.get(
                asset_class__name = AssetClass.DOCUMENT,
                mime_type__name   = MimeType.BINARY ))

    return new_work

##############################################################################

def handle_page(
    processor,
    parent_asset,
    document,
    tiff_original_path,
    position ):

    """ Convert the given TIFF file (representing a s single page) whose path
        is given to a JPEG (via RGBA).  Also create two thumbnails.

    """

    # Stuff we'll need later
    page     = operations.create_page(document, position)
    base_name    = os.path.splitext(tiff_original_path)[0]
    rgba_path    = '%s.rgba' % base_name
    jpeg_path    = '%s.jpeg' % base_name
    thumb_path   = '%s-thumbnail.jpeg' % base_name

    # Convert original TIFF to RGBA
    # TODO use convert instead of tiff2rgba
    os.system('tiff2rgba %r %r' % (tiff_original_path, rgba_path))

    # Save the original as JPEG
    image.save(
        image.load(rgba_path),
        jpeg_path)

    # Save the thumbnail as JPEG
    image.save(
        image.thumbnail(
            image.load(rgba_path),
            settings.THUMBNAIL_SIZE),
        thumb_path)

    # Put the assets into the work queue
    return [

        # The oginal full-res page as a TIFF
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_ORIGINAL,
            file_name    = tiff_original_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.TIFF ),

        # The full-res page as a JPEG
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_IMAGE,
            file_name    = jpeg_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.JPEG ),

        # The thumbnail as a JPEG
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_THUMBNAIL,
            file_name    = thumb_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.JPEG ),
        ]

##############################################################################

def redo_page(
    processor,
    parent_asset,
    tiff_original_path,
    position ):

    """ Re-convert the given TIFF file (representing a s single page) to a
        JPEG and a thumbnail.
    """
    try:
        original = parent_asset.children.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_ORIGINAL)

        image = parent_asset.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_IMAGE)

        thumbnail = parent_asset.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_THUMBNAIL)

    except Asset.DoesNotExist:
        logging.debug("Skipping deleted page")
        return

    # Stuff we'll need later
    base_name    = os.path.splitext(tiff_original_path)[0]
    rgba_path    = '%s.rgba' % base_name
    jpeg_path    = '%s.jpeg' % base_name
    thumb_path   = '%s-thumbnail.jpeg' % base_name

    # Convert original TIFF to RGBA
    # TODO use convert instead of tiff2rgba
    os.system('tiff2rgba %r %r' % (tiff_original_path, rgba_path))

    # Save the original as JPEG
    image.save(
        image.load(rgba_path),
        jpeg_path)

    # Save the thumbnail as JPEG
    image.save(
        image.thumbnail(
            image.load(rgba_path),
            settings.THUMBNAIL_SIZE),
        thumb_path)

    # Upload the new asset files
    operations.upload_asset_file( original,  pdf_orig_path )
    operations.upload_asset_file( image,     jpeg_path     )
    operations.upload_asset_file( thumbnail, thumb_path    )

    # Put the assets into the work queue
    return [ original, image, thumbnail ]

##############################################################################
<commit_msg>fixing syntax error<commit_after>"""
Multi-page TIFF parser

"""

from donomo.archive       import models, operations
from donomo.archive.utils import image
from django.conf          import settings

import glob
import os

DEFAULT_INPUTS  = (
    models.AssetClass.UPLOAD,
    )

DEFAULT_OUTPUTS = (
    models.AssetClass.DOCUMENT,
    models.AssetClass.PAGE_ORIGINAL,
    models.AssetClass.PAGE_IMAGE,
    models.AssetClass.PAGE_THUMBNAIL,
    )

DEFAULT_ACCEPTED_MIME_TYPES = (
    models.MimeType.TIFF,
    )

##############################################################################

def handle_work_item(processor, item):

    """ Pick up a (possibly) multipage TIFF upload and turn it into a
        document having (possibly) multiple individual pages.

    """

    new_work    = []
    asset       = item['Asset-Instance']
    local_path  = item['Local-Path']
    work_dir    = os.path.dirname(local_path)
    page_prefix = os.path.join(work_dir, 'page-')

    os.system( 'tiffsplit %r %r' % (local_path, page_prefix) )

    document = operations.create_document(
        owner = asset.owner,
        title = 'Uploaded on %s (%s)' % (
            asset.date_created,
            asset.producer.process ))

    position = 1
    all_page_files = glob.glob('%s*.tif*' % page_prefix)
    all_page_files.sort()
    for page_tiff_path in all_page_files:
        new_work.extend(
            handle_page(
                processor,
                asset,
                document,
                page_tiff_path,
                position ))
        position += 1

    if document is not None:
        new_work.append(
            document.assets.get(
                asset_class__name = models.AssetClass.DOCUMENT,
                mime_type__name   = models.MimeType.BINARY ))

    return new_work

##############################################################################

def handle_page(
    processor,
    parent_asset,
    document,
    tiff_original_path,
    position ):

    """ Convert the given TIFF file (representing a s single page) whose path
        is given to a JPEG (via RGBA).  Also create two thumbnails.

    """

    # Stuff we'll need later
    page     = operations.create_page(document, position)
    base_name    = os.path.splitext(tiff_original_path)[0]
    rgba_path    = '%s.rgba' % base_name
    jpeg_path    = '%s.jpeg' % base_name
    thumb_path   = '%s-thumbnail.jpeg' % base_name

    # Convert original TIFF to RGBA
    # TODO use convert instead of tiff2rgba
    os.system('tiff2rgba %r %r' % (tiff_original_path, rgba_path))

    # Save the original as JPEG
    image.save(
        image.load(rgba_path),
        jpeg_path)

    # Save the thumbnail as JPEG
    image.save(
        image.thumbnail(
            image.load(rgba_path),
            settings.THUMBNAIL_SIZE),
        thumb_path)

    # Put the assets into the work queue
    return [

        # The oginal full-res page as a TIFF
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_ORIGINAL,
            file_name    = tiff_original_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.TIFF ),

        # The full-res page as a JPEG
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_IMAGE,
            file_name    = jpeg_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.JPEG ),

        # The thumbnail as a JPEG
        operations.create_asset_from_file(
            owner        = document.owner,
            producer     = processor,
            asset_class  = models.AssetClass.PAGE_THUMBNAIL,
            file_name    = thumb_path,
            related_page = page,
            parent       = parent_asset,
            child_number = page.position,
            mime_type    = models.MimeType.JPEG ),
        ]

##############################################################################

def redo_page(
    processor,
    parent_asset,
    tiff_original_path,
    position ):

    """ Re-convert the given TIFF file (representing a s single page) to a
        JPEG and a thumbnail.
    """
    try:
        original = parent_asset.children.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_ORIGINAL)

        image = parent_asset.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_IMAGE)

        thumbnail = parent_asset.get(
            child_number = position,
            asset_class = models.AssetClass.PAGE_THUMBNAIL)

    except Asset.DoesNotExist:
        logging.debug("Skipping deleted page")
        return

    # Stuff we'll need later
    base_name    = os.path.splitext(tiff_original_path)[0]
    rgba_path    = '%s.rgba' % base_name
    jpeg_path    = '%s.jpeg' % base_name
    thumb_path   = '%s-thumbnail.jpeg' % base_name

    # Convert original TIFF to RGBA
    # TODO use convert instead of tiff2rgba
    os.system('tiff2rgba %r %r' % (tiff_original_path, rgba_path))

    # Save the original as JPEG
    image.save(
        image.load(rgba_path),
        jpeg_path)

    # Save the thumbnail as JPEG
    image.save(
        image.thumbnail(
            image.load(rgba_path),
            settings.THUMBNAIL_SIZE),
        thumb_path)

    # Upload the new asset files
    operations.upload_asset_file( original,  pdf_orig_path )
    operations.upload_asset_file( image,     jpeg_path     )
    operations.upload_asset_file( thumbnail, thumb_path    )

    # Put the assets into the work queue
    return [ original, image, thumbnail ]

##############################################################################
<|endoftext|>


<commit_before>import sys
import time
import os
import RPi.GPIO as GPIO
import Adafruit_MPR121.MPR121 as MPR121
import threading
import serial
from threading import Thread

flag1 = 0
flag2 = 0
#GPIO.setmode(GPIO.BCM)
#set up GPIO pins as outputs
#GPIO.setup(16,GPIO.OUT)
#GPIO.setup(26,GPIO.OUT)
#red = GPIO.PWM(26, 100)
#green = GPIO.PWM(16, 100)
ser = serial.Serial('/dev/ttyACM0', 9600)

def yoda():
	global flag1
	os.system('aplay yoda.wav')
	flag1 = 0

def luke():
	global flag1
	os.system('aplay LukeLsbr.wav')
	flag1 = 0

def vader():
	global flag1
	os.system('aplay DarthLsbr.wav')
	flag1 = 0

def vaderBreathing():
	global flag1
	os.system('aplay vader.wav')
	flag1 = 0

def greenLight():
	global flag2
	ser.write('1')
	flag2 = 0

def redLight():
	global flag2
	ser.write('3')
	flag2 = 0

#def redLight():
#	global flag2
#	red.start(0)
#	for i in range(0,101):
#               red.ChangeDutyCycle(i)
#               time.sleep(0.02)
#       for i in range(100,-1,-1):
#               red.ChangeDutyCycle(i)
#               time.sleep(0.02)
#	print('flag2 is %d', flag2)
#	flag2 = 0
#	print('flag2 is now %d', flag2)
#	red.stop()

#def greenLight():
#        global flag2
#        green.start(0)
#        for i in range(0,101):
#                green.ChangeDutyCycle(i)
#                time.sleep(0.02)
#        for i in range(100,-1,-1):
#                green.ChangeDutyCycle(i)
#                time.sleep(0.02)
#        print('flag2 is %d', flag2)
#        flag2 = 0
#        print('flag2 is now %d', flag2)
#        green.stop()

print('Adafruit MPR121 Capacitive Touch Sensor Test')

# Create MPR121 instance.
cap = MPR121.MPR121()

if not cap.begin():
    print('Error initializing MPR121.  Check your wiring!')
    sys.exit(1)

# Main loop to print a message every time a pin is touched.
print('Press Ctrl-C to quit.')
last_touched = cap.touched()
while True:
    current_touched = cap.touched()
    time.sleep(0.25)

    if cap.is_touched(0) and flag1 == 0 and flag2 == 0:
        print('Pin 0 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('1')
	Thread(target = yoda).start()
	Thread(target = greenLight).start()

    if cap.is_touched(4) and flag1 == 0 and flag2 == 0:
	print('Pin 4 is being touched!')
	flag1 = 1
        flag2 = 1
#	ser.write('2')
        Thread(target = luke).start()
        Thread(target = greenLight).start()

    if cap.is_touched(10) and flag1 == 0 and flag2 == 0:
	print('Pin 10 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('3')
	Thread(target = vader).start()
	Thread(target = redLight).start()

    if cap.is_touched(11) and flag1 == 0 and flag2 == 0:
	print('Pin 11 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('4')
        Thread(target = vaderBreathing).start()
	Thread(target = redLight).start()
<commit_msg>Added main theme for logo being touched on pin 6.<commit_after>import sys
import time
import os
import RPi.GPIO as GPIO
import Adafruit_MPR121.MPR121 as MPR121
import threading
import serial
from threading import Thread

flag1 = 0
flag2 = 0
#GPIO.setmode(GPIO.BCM)
#set up GPIO pins as outputs
#GPIO.setup(16,GPIO.OUT)
#GPIO.setup(26,GPIO.OUT)
#red = GPIO.PWM(26, 100)
#green = GPIO.PWM(16, 100)
ser = serial.Serial('/dev/ttyACM0', 9600)

def yoda():
	global flag1
	os.system('aplay yoda.wav')
	flag1 = 0

def luke():
	global flag1
	os.system('aplay LukeLsbr.wav')
	flag1 = 0

def vader():
	global flag1
	os.system('aplay DarthLsbr.wav')
	flag1 = 0

def vaderBreathing():
	global flag1
	os.system('aplay vader.wav')
	flag1 = 0

def logo():
	global flag1
	os.system('aplay mainthemeshort.wav')
	flag1 = 0

def greenLight():
	global flag2
	ser.write('1')
	flag2 = 0

def redLight():
	global flag2
	ser.write('3')
	flag2 = 0

def logoLight():
	global flag2
	ser.write('5')
	flag2 = 0

#def redLight():
#	global flag2
#	red.start(0)
#	for i in range(0,101):
#               red.ChangeDutyCycle(i)
#               time.sleep(0.02)
#       for i in range(100,-1,-1):
#               red.ChangeDutyCycle(i)
#               time.sleep(0.02)
#	print('flag2 is %d', flag2)
#	flag2 = 0
#	print('flag2 is now %d', flag2)
#	red.stop()

#def greenLight():
#        global flag2
#        green.start(0)
#        for i in range(0,101):
#                green.ChangeDutyCycle(i)
#                time.sleep(0.02)
#        for i in range(100,-1,-1):
#                green.ChangeDutyCycle(i)
#                time.sleep(0.02)
#        print('flag2 is %d', flag2)
#        flag2 = 0
#        print('flag2 is now %d', flag2)
#        green.stop()

print('Adafruit MPR121 Capacitive Touch Sensor Test')

# Create MPR121 instance.
cap = MPR121.MPR121()

if not cap.begin():
    print('Error initializing MPR121.  Check your wiring!')
    sys.exit(1)

# Main loop to print a message every time a pin is touched.
print('Press Ctrl-C to quit.')
last_touched = cap.touched()
while True:
    current_touched = cap.touched()
    time.sleep(0.25)

    if cap.is_touched(0) and flag1 == 0 and flag2 == 0:
        print('Pin 0 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('1')
	Thread(target = yoda).start()
	Thread(target = greenLight).start()

    if cap.is_touched(4) and flag1 == 0 and flag2 == 0:
	print('Pin 4 is being touched!')
	flag1 = 1
        flag2 = 1
#	ser.write('2')
        Thread(target = luke).start()
        Thread(target = greenLight).start()

    if cap.is_touched(6) and flag1 == 0 and flag2 == 0:
	print('Pin 6 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('5')
	Thread(target = logo).start()
	Thread(target = logoLight).start()

    if cap.is_touched(10) and flag1 == 0 and flag2 == 0:
	print('Pin 10 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('3')
	Thread(target = vader).start()
	Thread(target = redLight).start()

    if cap.is_touched(11) and flag1 == 0 and flag2 == 0:
	print('Pin 11 is being touched!')
	flag1 = 1
	flag2 = 1
#	ser.write('4')
        Thread(target = vaderBreathing).start()
	Thread(target = redLight).start()
<|endoftext|>


<commit_before>import time
import ipdb
from calendar import month_name

from django.conf import settings
from django.http import Http404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView

from django.core.paginator import Paginator, \
    InvalidPage, EmptyPage

from django.shortcuts import render, \
    HttpResponseRedirect, redirect

from .models import Post, Comment
from .forms import CommentsForm, CommentForm

def post(request, post_id):
    """Single post with comments and a comment form."""
    try:
        post_model = Post.objects.get(pk=post_id)
        comment_model = Comment.objects.filter(post=post_model)
        d = { 'post':post_model, 'comments':comment_model, 'form':CommentForm(), 'user':request.user }
        ipdb.set_trace()
        return render(request, "post.html", d)
    except Post.DoesNotExist:
        raise Http404

def add_comment(request, post_id):
    """Add a new comment."""
    post_data = request.POST

    if post_data.has_key("body") and post_data["body"]:
        comment_author = "Anonymous"
        if post_data["author"]:
            comment_author = post_data["author"]

        comment = Comment(post=Post.objects.get(pk=post_id))
        cf = CommentForm(post_data, instance=comment)
        cf.fields["author"].required = False

        comment = cf.save(commit=False)
        comment.author = comment_author
	comment.save()
    return redirect("main")

def mkmonth_lst():
    """Make a list of months to show archive links."""

    if not Post.objects.count():
        return []

    # set up vars
    year, month = time.localtime()[:2]
    first = Post.objects.earliest("created")
    fyear = first.created.year
    fmonth = first.created.month
    months = []

    # loop over years and months
    for y in range(year, fyear-1, -1):
        start, end = 12, 0
        if y == year:
            start = month
        if y == fyear:
            end = fmonth-1

        for m in range(start, end, -1):
            months.append((y, m, month_name[m]))
    return months

def month(request, year, month):
    """Monthly archive."""
    posts = Post.objects.filter(created__year=year, created__month=month)
    return render(request, "archive.html", { 'posts':posts, 'post_list':posts,
                                     'context_instance':RequestContext(request),
                                                'months':mkmonth_lst(), 'archive':True })

def delete_comment(request, post_pk, pk=None):
    """Delete comment(s) with primary key `pk` or with pks in POST."""
    if request.user.is_staff:
        if not pk:
            pklst = request.POST.getlist("delete")
        else:
            pklst = [pk]
	print request
        for pk in pklst:
            Comment.objects.get(pk=pk).delete()
        return HttpResponseRedirect(reverse("post", args=[post_pk]))

def blog(request):
    """Main listing."""
    posts = Post.objects.order_by("-created")
    entries_per_page = getattr(settings, 'BLOG_NUMBER_OF_ENTRIES_PER_PAGE')
    paginator = Paginator(posts, entries_per_page)

    try:
        page = int(request.GET.get("page", '1'))
    except ValueError:
        page = 1

    try:
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    return render(request, "list.html", {'posts':posts,
                                                'context_instance':RequestContext(request),
                                                'post_list':posts.object_list, 'months':mkmonth_lst()})

def posts(request):
    try:
    	post_data = request.POST
        form = CommentForm(post_data)
        posts = Post.objects.order_by("created")
        comments = Comment.objects.order_by("created")
        comment_form = CommentsForm()
        return render( request, 'recentposts.html', {'posts': posts, 'comments': comments, 'comment_form':comment_form})
    except Post.DoesNotExist:
    	raise Http404

class AboutMe(TemplateView):
    template_name = "aboutme.html"
<commit_msg>Commit of pep8 conventions to views<commit_after>import time
import ipdb
from calendar import month_name

from django.conf import settings
from django.http import Http404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView

from django.core.paginator import Paginator, \
    InvalidPage, EmptyPage

from django.shortcuts import render, \
    HttpResponseRedirect, redirect

from .models import Post, Comment
from .forms import CommentsForm, CommentForm

def post(request, post_id):
    """Single post with comments and a comment form."""
    try:
        post_model = Post.objects.get(pk=post_id)
        comment_model = Comment.objects.filter(post=post_model)
        d = {'post': post_model, 'comments': comment_model,
             'form': CommentForm(), 'user': request.user}
        ipdb.set_trace()
        return render(request, "post.html", d)
    except Post.DoesNotExist:
        raise Http404

def add_comment(request, post_id):
    """Add a new comment."""
    post_data = request.POST

    if post_data.has_key("body") and post_data["body"]:
        comment_author = "Anonymous"
        if post_data["author"]:
            comment_author = post_data["author"]

        comment = Comment(post=Post.objects.get(pk=post_id))
        cf = CommentForm(post_data, instance=comment)
        cf.fields["author"].required = False

        comment = cf.save(commit=False)
        comment.author = comment_author
        comment.save()
    return redirect("main")

def mkmonth_lst():
    """Make a list of months to show archive links."""

    if not Post.objects.count():
        return []

    # set up vars
    year, month = time.localtime()[:2]
    first = Post.objects.earliest("created")
    fyear = first.created.year
    fmonth = first.created.month
    months = []

    # loop over years and months
    for y in range(year, fyear-1, -1):
        start, end = 12, 0
        if y == year:
            start = month
        if y == fyear:
            end = fmonth-1

        for m in range(start, end, -1):
            months.append((y, m, month_name[m]))
    return months

def month(request, year, month):
    """Monthly archive."""
    posts = Post.objects.filter(created__year=year, created__month=month)
    return render(request, "archive.html", {'posts': posts, 'post_list': posts,
                  'context_instance': RequestContext(request),
                  'months': mkmonth_lst(), 'archive': True})

def delete_comment(request, post_pk, pk=None):
    """Delete comment(s) with primary key `pk` or with pks in POST."""
    if request.user.is_staff:
        if not pk:
            pklst = request.POST.getlist("delete")
        else:
            pklst = [pk]
        for pk in pklst:
            Comment.objects.get(pk=pk).delete()
        return HttpResponseRedirect(reverse("post", args=[post_pk]))

def blog(request):
    """Main listing."""
    posts = Post.objects.order_by("-created")
    entries_per_page = getattr(settings, 'BLOG_NUMBER_OF_ENTRIES_PER_PAGE')
    paginator = Paginator(posts, entries_per_page)
    try:
        page = int(request.GET.get("page", '1'))
    except ValueError:
        page = 1

    try:
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    return render(request, "list.html", {'posts': posts,
                  'context_instance': RequestContext(request),
                  'post_list': posts.object_list, 'months': mkmonth_lst()})

def posts(request):
    try:
        post_data = request.POST
        form = CommentForm(post_data)
        posts = Post.objects.order_by("created")
        comments = Comment.objects.order_by("created")
        comment_form = CommentsForm()
        return render(request, 'recentposts.html', {'posts': posts,
                      'comments': comments, 'comment_form': comment_form})
    except Post.DoesNotExist:
        raise Http404

class AboutMe(TemplateView):
    template_name = "aboutme.html"
<|endoftext|>


<commit_before># coding: utf-8

from .functions import str_list, str_list_w_last, href, hlp
from django.db.models import CharField, ForeignKey, ManyToManyField, \
                             FloatField, OneToOneField, BooleanField, \
                             permalink, get_model
from tinymce.models import HTMLField
from django.utils.html import strip_tags
from django.utils.translation import ungettext_lazy, ugettext, \
                                     ugettext_lazy as _
from django.template.defaultfilters import capfirst
from .common import CustomModel, LOWER_MSG, PLURAL_MSG, calc_pluriel
import hashlib
from django.utils.http import urlquote
from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import receiver

class AttributionDePupitre(CustomModel):
    pupitre = ForeignKey('Pupitre', related_name='attributions_de_pupitre')
    individus = ManyToManyField('Individu',
                                related_name='attributions_de_pupitre')

    class Meta:
        verbose_name = ungettext_lazy('attribution de pupitre',
                                      'attributions de pupitre', 1)
        verbose_name_plural = ungettext_lazy('attribution de pupitre',
                                             'attributions de pupitre', 2)
        ordering = ['pupitre']
        app_label = 'catalogue'

    def __unicode__(self):
        out = unicode(self.pupitre.partie) + ' : '
        ins = self.individus.iterator()
        out += str_list_w_last(unicode(i) for i in ins)
        return out

class CaracteristiqueDElementDeProgramme(CustomModel):
    nom = CharField(max_length=100, help_text=LOWER_MSG, unique=True)
    nom_pluriel = CharField(max_length=110, blank=True,
        verbose_name=_('nom (au pluriel)'), help_text=PLURAL_MSG)
    classement = FloatField(default=1.0)

    def pluriel(self):
        return calc_pluriel(self)

    class Meta:
        verbose_name = ungettext_lazy(
                u'caractéristique d’élément de programme',
                u'caractéristiques d’élément de programme',
                1)
        verbose_name_plural = ungettext_lazy(
                u'caractéristique d’élément de programme',
                u'caractéristiques d’élément de programme',
                2)
        ordering = ['nom']
        app_label = 'catalogue'

    def __unicode__(self):
        return self.nom

class ElementDeProgramme(CustomModel):
    oeuvre = ForeignKey('Oeuvre', related_name='elements_de_programme',
        verbose_name=_(u'œuvre'), blank=True, null=True)
    autre = CharField(max_length=500, blank=True)
    caracteristiques = ManyToManyField(CaracteristiqueDElementDeProgramme,
        related_name='elements_de_programme', blank=True, null=True,
        verbose_name=_(u'caractéristiques'))
    classement = FloatField(default=1.0)
    distribution = ManyToManyField(AttributionDePupitre,
        related_name='elements_de_programme', blank=True, null=True)
    personnels = ManyToManyField('Personnel',
        related_name='elements_de_programme', blank=True, null=True)
    illustrations = ManyToManyField('Illustration',
        related_name='representations', blank=True, null=True)
    documents = ManyToManyField('Document', related_name='representations',
        blank=True, null=True)
    etat = ForeignKey('Etat', related_name='elements_de_programme', null=True,
        blank=True)

    def calc_caracteristiques(self):
        cs = self.caracteristiques.iterator()
        return str_list(unicode(c) for c in cs)
    calc_caracteristiques.allow_tags = True
    calc_caracteristiques.short_description = _(u'caractéristiques')

    def html(self, tags=True):
        out = []
        out__append = out.append
        oeuvre = self.oeuvre
        if oeuvre:
            out__append(oeuvre.html(tags))
        else:
            out__append(self.autre)
        cs = self.calc_caracteristiques()
        if cs:
            out__append(' [' + cs + ']')
        distribution = self.distribution
        if distribution.exists():
            out__append(u'. — ')
            maxi = distribution.count() - 1
        for i, attribution in enumerate(distribution.iterator()):
            individus = attribution.individus.iterator()
            out__append(str_list(individu.html(tags)
                                                    for individu in individus))
            out__append(' [' + attribution.pupitre.partie.link() + ']')
            if i < maxi:
                out__append(', ')
        return ''.join(out)
    html.short_description = _('rendu HTML')
    html.allow_tags = True

    class Meta:
        verbose_name = ungettext_lazy(u'élément de programme',
                u'éléments de programme', 1)
        verbose_name_plural = ungettext_lazy(u'élément de programme',
                u'éléments de programme', 2)
        ordering = ['classement', 'oeuvre']
        app_label = 'catalogue'

    def __unicode__(self):
        return strip_tags(self.html(False))

    @staticmethod
    def autocomplete_search_fields():
        return (
            'oeuvre__prefixe_titre__icontains', 'oeuvre__titre__icontains',
            'oeuvre__prefixe_titre_secondaire__icontains',
            'oeuvre__titre_secondaire__icontains',
            'oeuvre__genre__nom__icontains',
        )

class Evenement(CustomModel):
    ancrage_debut = OneToOneField('AncrageSpatioTemporel',
        related_name='evenements_debuts')
    ancrage_fin = OneToOneField('AncrageSpatioTemporel',
        related_name='evenements_fins', blank=True, null=True)
    relache = BooleanField(verbose_name=u'relâche')
    circonstance = CharField(max_length=500, blank=True)
    programme = ManyToManyField('ElementDeProgramme',
        related_name='evenements', blank=True, null=True)
    documents = ManyToManyField('Document', related_name='evenements',
        blank=True, null=True)
    illustrations = ManyToManyField('Illustration', related_name='evenements',
        blank=True, null=True)
    etat = ForeignKey('Etat', related_name='evenements', null=True, blank=True)
    notes = HTMLField(blank=True)

    @permalink
    def get_absolute_url(self):
        return ('evenement_pk', [self.pk])

    @permalink
    def permalien(self):
        return self.get_absolute_url()

    def link(self):
        return href(self.get_absolute_url(), unicode(self))
    link.short_description = _('lien')
    link.allow_tags = True

    def sources_dict(self):
        types = get_model('catalogue',
                          'TypeDeSource').objects \
                                         .filter(sources__evenements=self)
        types = types.distinct()
        d = {}
        for type in types:
            sources = self.sources.filter(type=type)
            if sources:
                d[type] = sources
        return d

    def html(self, tags=True):
        relache, circonstance = '', ''
        if self.circonstance:
            circonstance = hlp(self.circonstance, ugettext(u'circonstance'),
                               tags)
        if self.relache:
            relache = ugettext(u'Relâche')
        l = (self.ancrage_debut.calc_lieu(tags), circonstance,
             self.ancrage_debut.calc_heure(), relache)
        out = str_list(l)
        return out
    html.short_description = _('rendu HTML')
    html.allow_tags = True

    def clear_cache(self):
        args = hashlib.md5(str(self.pk))
        cache_key = 'template.cache.%s.%s' % ('evenement', args.hexdigest())
        cache.delete(cache_key)

    @staticmethod
    @receiver(post_save)
    def clear_all_cache(sender, **kwargs):
        print 'test'
        for e in Evenement.objects.all():
            e.clear_cache()

    class Meta:
        verbose_name = ungettext_lazy(u'événement', u'événements', 1)
        verbose_name_plural = ungettext_lazy(u'événement', u'événements', 2)
        ordering = ['ancrage_debut']
        app_label = 'catalogue'

    def __unicode__(self):
        out = self.ancrage_debut.calc_date(False)
        out = capfirst(out)
        out += u'\u00A0; ' + self.html(False)
        return strip_tags(out)

    @staticmethod
    def autocomplete_search_fields():
        return (
            'circonstace__icontains',
            'ancrage_debut__lieu__nom__icontains',
            'ancrage_debut__lieu__parent__nom__icontains',
            'ancrage_debut__date__icontains',
            'ancrage_debut__heure__icontains',
            'ancrage_debut__lieu_approx__icontains',
            'ancrage_debut__date_approx__icontains',
            'ancrage_debut__heure_approx__icontains',
        )
<commit_msg>Retire un message de debug.<commit_after># coding: utf-8

from .functions import str_list, str_list_w_last, href, hlp
from django.db.models import CharField, ForeignKey, ManyToManyField, \
                             FloatField, OneToOneField, BooleanField, \
                             permalink, get_model
from tinymce.models import HTMLField
from django.utils.html import strip_tags
from django.utils.translation import ungettext_lazy, ugettext, \
                                     ugettext_lazy as _
from django.template.defaultfilters import capfirst
from .common import CustomModel, LOWER_MSG, PLURAL_MSG, calc_pluriel
import hashlib
from django.utils.http import urlquote
from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import receiver

class AttributionDePupitre(CustomModel):
    pupitre = ForeignKey('Pupitre', related_name='attributions_de_pupitre')
    individus = ManyToManyField('Individu',
                                related_name='attributions_de_pupitre')

    class Meta:
        verbose_name = ungettext_lazy('attribution de pupitre',
                                      'attributions de pupitre', 1)
        verbose_name_plural = ungettext_lazy('attribution de pupitre',
                                             'attributions de pupitre', 2)
        ordering = ['pupitre']
        app_label = 'catalogue'

    def __unicode__(self):
        out = unicode(self.pupitre.partie) + ' : '
        ins = self.individus.iterator()
        out += str_list_w_last(unicode(i) for i in ins)
        return out

class CaracteristiqueDElementDeProgramme(CustomModel):
    nom = CharField(max_length=100, help_text=LOWER_MSG, unique=True)
    nom_pluriel = CharField(max_length=110, blank=True,
        verbose_name=_('nom (au pluriel)'), help_text=PLURAL_MSG)
    classement = FloatField(default=1.0)

    def pluriel(self):
        return calc_pluriel(self)

    class Meta:
        verbose_name = ungettext_lazy(
                u'caractéristique d’élément de programme',
                u'caractéristiques d’élément de programme',
                1)
        verbose_name_plural = ungettext_lazy(
                u'caractéristique d’élément de programme',
                u'caractéristiques d’élément de programme',
                2)
        ordering = ['nom']
        app_label = 'catalogue'

    def __unicode__(self):
        return self.nom

class ElementDeProgramme(CustomModel):
    oeuvre = ForeignKey('Oeuvre', related_name='elements_de_programme',
        verbose_name=_(u'œuvre'), blank=True, null=True)
    autre = CharField(max_length=500, blank=True)
    caracteristiques = ManyToManyField(CaracteristiqueDElementDeProgramme,
        related_name='elements_de_programme', blank=True, null=True,
        verbose_name=_(u'caractéristiques'))
    classement = FloatField(default=1.0)
    distribution = ManyToManyField(AttributionDePupitre,
        related_name='elements_de_programme', blank=True, null=True)
    personnels = ManyToManyField('Personnel',
        related_name='elements_de_programme', blank=True, null=True)
    illustrations = ManyToManyField('Illustration',
        related_name='representations', blank=True, null=True)
    documents = ManyToManyField('Document', related_name='representations',
        blank=True, null=True)
    etat = ForeignKey('Etat', related_name='elements_de_programme', null=True,
        blank=True)

    def calc_caracteristiques(self):
        cs = self.caracteristiques.iterator()
        return str_list(unicode(c) for c in cs)
    calc_caracteristiques.allow_tags = True
    calc_caracteristiques.short_description = _(u'caractéristiques')

    def html(self, tags=True):
        out = []
        out__append = out.append
        oeuvre = self.oeuvre
        if oeuvre:
            out__append(oeuvre.html(tags))
        else:
            out__append(self.autre)
        cs = self.calc_caracteristiques()
        if cs:
            out__append(' [' + cs + ']')
        distribution = self.distribution
        if distribution.exists():
            out__append(u'. — ')
            maxi = distribution.count() - 1
        for i, attribution in enumerate(distribution.iterator()):
            individus = attribution.individus.iterator()
            out__append(str_list(individu.html(tags)
                                                    for individu in individus))
            out__append(' [' + attribution.pupitre.partie.link() + ']')
            if i < maxi:
                out__append(', ')
        return ''.join(out)
    html.short_description = _('rendu HTML')
    html.allow_tags = True

    class Meta:
        verbose_name = ungettext_lazy(u'élément de programme',
                u'éléments de programme', 1)
        verbose_name_plural = ungettext_lazy(u'élément de programme',
                u'éléments de programme', 2)
        ordering = ['classement', 'oeuvre']
        app_label = 'catalogue'

    def __unicode__(self):
        return strip_tags(self.html(False))

    @staticmethod
    def autocomplete_search_fields():
        return (
            'oeuvre__prefixe_titre__icontains', 'oeuvre__titre__icontains',
            'oeuvre__prefixe_titre_secondaire__icontains',
            'oeuvre__titre_secondaire__icontains',
            'oeuvre__genre__nom__icontains',
        )

class Evenement(CustomModel):
    ancrage_debut = OneToOneField('AncrageSpatioTemporel',
        related_name='evenements_debuts')
    ancrage_fin = OneToOneField('AncrageSpatioTemporel',
        related_name='evenements_fins', blank=True, null=True)
    relache = BooleanField(verbose_name=u'relâche')
    circonstance = CharField(max_length=500, blank=True)
    programme = ManyToManyField('ElementDeProgramme',
        related_name='evenements', blank=True, null=True)
    documents = ManyToManyField('Document', related_name='evenements',
        blank=True, null=True)
    illustrations = ManyToManyField('Illustration', related_name='evenements',
        blank=True, null=True)
    etat = ForeignKey('Etat', related_name='evenements', null=True, blank=True)
    notes = HTMLField(blank=True)

    @permalink
    def get_absolute_url(self):
        return ('evenement_pk', [self.pk])

    @permalink
    def permalien(self):
        return self.get_absolute_url()

    def link(self):
        return href(self.get_absolute_url(), unicode(self))
    link.short_description = _('lien')
    link.allow_tags = True

    def sources_dict(self):
        types = get_model('catalogue',
                          'TypeDeSource').objects \
                                         .filter(sources__evenements=self)
        types = types.distinct()
        d = {}
        for type in types:
            sources = self.sources.filter(type=type)
            if sources:
                d[type] = sources
        return d

    def html(self, tags=True):
        relache, circonstance = '', ''
        if self.circonstance:
            circonstance = hlp(self.circonstance, ugettext(u'circonstance'),
                               tags)
        if self.relache:
            relache = ugettext(u'Relâche')
        l = (self.ancrage_debut.calc_lieu(tags), circonstance,
             self.ancrage_debut.calc_heure(), relache)
        out = str_list(l)
        return out
    html.short_description = _('rendu HTML')
    html.allow_tags = True

    def clear_cache(self):
        args = hashlib.md5(str(self.pk))
        cache_key = 'template.cache.%s.%s' % ('evenement', args.hexdigest())
        cache.delete(cache_key)

    @staticmethod
    @receiver(post_save)
    def clear_all_cache(sender, **kwargs):
        for e in Evenement.objects.all():
            e.clear_cache()

    class Meta:
        verbose_name = ungettext_lazy(u'événement', u'événements', 1)
        verbose_name_plural = ungettext_lazy(u'événement', u'événements', 2)
        ordering = ['ancrage_debut']
        app_label = 'catalogue'

    def __unicode__(self):
        out = self.ancrage_debut.calc_date(False)
        out = capfirst(out)
        out += u'\u00A0; ' + self.html(False)
        return strip_tags(out)

    @staticmethod
    def autocomplete_search_fields():
        return (
            'circonstace__icontains',
            'ancrage_debut__lieu__nom__icontains',
            'ancrage_debut__lieu__parent__nom__icontains',
            'ancrage_debut__date__icontains',
            'ancrage_debut__heure__icontains',
            'ancrage_debut__lieu_approx__icontains',
            'ancrage_debut__date_approx__icontains',
            'ancrage_debut__heure_approx__icontains',
        )
<|endoftext|>


<commit_before>__author__ = 'Krylik'
import argparse
import re
import xml.etree.ElementTree as ET
from xml.dom import minidom
from shutil import copytree, ignore_patterns

argparser = argparse.ArgumentParser()
argparser.add_argument('indir',
                       metavar='input',
                       type=str,
                       description="The directory containing the pidgin emotes")
argparser.add_argument('outdir',
                       metavar='output',
                       type=str,
                       description="The output directory name, this will have .AdiumEmoticonSet appended to the name")
args = argparser.parse_args()

copytree(args.indir, args.outdir, ignore=ignore_patterns('theme', '.git*', '*.gz'))

emoticons = []
with open('%s/theme' % args.indir) as themefile:
    for themeline in themefile:
        if themeline.startswith('! '):
            parts = re.split('\s*', themeline.strip('! ').strip('\n'))
            img = parts[0]
            triggers = parts[1:]
            emoticons.append((img, triggers))

# Build plist file from template
tree = ET.parse('emoticonpack_builder/template.plist')
plist = tree.getroot()
plist_root_dict = plist.find('dict')
emote_dict = ET.SubElement(plist_root_dict, 'dict')
for emote in emoticons:
    img, triggers = emote
    # key for image name
    img_key = ET.SubElement(emote_dict, 'key')
    img_key.text = img
    # dict to hold triggers for this emote
    triggers_dict = ET.SubElement(emote_dict, 'dict')
    equiv_key = ET.SubElement(triggers_dict, 'key')
    equiv_key.text = 'Equivalents'
    triggers_array = ET.SubElement(triggers_dict, 'array')
    for trigger in triggers:
        trigger_item = ET.SubElement(triggers_array, 'string')
        trigger_item.text = trigger
    name_key = ET.SubElement(triggers_dict, 'key')
    name_key.text = 'Name'
    name_value = ET.SubElement(triggers_dict, 'string')
    name_value.text = img

# Write xml output to the outfile specified
reparsed_xml = minidom.parseString(ET.tostring(plist))
with open('%s/Emoticons.plist' % args.outdir, 'w+') as outplist:
    outplist.write(reparsed_xml.toprettyxml(indent="\t"))<commit_msg>Help update<commit_after>__author__ = 'Krylik'
import argparse
import re
import xml.etree.ElementTree as ET
from xml.dom import minidom
from shutil import copytree, ignore_patterns

argparser = argparse.ArgumentParser()
argparser.add_argument('indir',
                       metavar='input',
                       type=str,
                       help="The directory containing the pidgin emotes")
argparser.add_argument('outdir',
                       metavar='output',
                       type=str,
                       help="The output directory name, this will have .AdiumEmoticonSet appended to the name")
args = argparser.parse_args()

copytree(args.indir, args.outdir, ignore=ignore_patterns('theme', '.git*', '*.gz'))

emoticons = []
with open('%s/theme' % args.indir) as themefile:
    for themeline in themefile:
        if themeline.startswith('! '):
            parts = re.split('\s*', themeline.strip('! ').strip('\n'))
            img = parts[0]
            triggers = parts[1:]
            emoticons.append((img, triggers))

# Build plist file from template
tree = ET.parse('emoticonpack_builder/template.plist')
plist = tree.getroot()
plist_root_dict = plist.find('dict')
emote_dict = ET.SubElement(plist_root_dict, 'dict')
for emote in emoticons:
    img, triggers = emote
    # key for image name
    img_key = ET.SubElement(emote_dict, 'key')
    img_key.text = img
    # dict to hold triggers for this emote
    triggers_dict = ET.SubElement(emote_dict, 'dict')
    equiv_key = ET.SubElement(triggers_dict, 'key')
    equiv_key.text = 'Equivalents'
    triggers_array = ET.SubElement(triggers_dict, 'array')
    for trigger in triggers:
        trigger_item = ET.SubElement(triggers_array, 'string')
        trigger_item.text = trigger
    name_key = ET.SubElement(triggers_dict, 'key')
    name_key.text = 'Name'
    name_value = ET.SubElement(triggers_dict, 'string')
    name_value.text = img

# Write xml output to the outfile specified
reparsed_xml = minidom.parseString(ET.tostring(plist))
with open('%s/Emoticons.plist' % args.outdir, 'w+') as outplist:
    outplist.write(reparsed_xml.toprettyxml(indent="\t"))<|endoftext|>


<commit_before>group = {
    "groupConfiguration": {
        "name": "manitest",
        "cooldown": 5,
        "minEntities": 0,
        "maxEntities": 25,
        "metadata": {
            "firstkey": "this is a string",
            "secondkey": "1"
        }
    },
    "launchConfiguration": {
        "type": "launch_server",
        "args": {
            "server": {
                "flavorRef": "3",
                "name": "webhead",
                "imageRef": "0d589460-f177-4b0f-81c1-8ab8903ac7d8",
                "metadata": {
                    "mani": "manitest"
                },
                "personality" : [
                    {
                        "path" : "/etc/banner.txt",
                        "contents": "VGhpcyBpcyBhIHRlc3Qgb2YgYmFzZTY0IGVuY29kaW5n"
                    },
                ]
            }
        }
    },
    "scalingPolicies": [
        {
            "name": "Delete all servers",
            "desiredCapacity": 0,
            "cooldown": 3,
            "type": "webhook"
        }
    ]
}

policies = [
    {
        "name": "scale up by one server",
        "change": 1,
        "cooldown": 150,
        "type": "webhook"
    },
    {
        "name": "scale down by 5.5 percent",
        "changePercent": -5.5,
        "cooldown": 6,
        "type": "webhook"
    }
]

webhooks = [
    {
        "name": "mani-webhook",
        "metadata": {
            "notes": "this is for mani"
        }
    }
]

config = {
    "name": "Rackspace Auto Scale",
    "description": "CLI to work on Racksapce Autoscale",
    "uriprefix": {
        "regex": "/v1.0/\d+/",
        "env": "AS_URI_PREFIX"
    },
    "headers": {
        "X-Auth-Token": "AS_AUTH_TOKEN"
    },
    "tempfile": "/tmp/ascli_req.json",
    "resources": {
        "groups/?$": {
            "post": group,
            "aliases": {
                "name": "groupConfiguration.name"
            },
            "help": "Scaling groups. Ex: groups"
        },
        "groups/[\w\-]+/?$": {
            "aliases": {
                "name": "groupConfiguration.name"
            },
            "help": "Single scaling group. Format: groups/<groupID> Ex: groups/2339-23-543"
        },
        "groups/[\w\-]+/policies/?$": {
            "post": policies,
            "help": "Scaling group's policies. Format: groups/<groupID>/policies"
        },
        "groups/[\w\-]+/policies/[\w\-]+/?$": {
            "help": "Scaling group's single policy. Format: groups/<groupID>/policies/<policyID>"
        },
        "groups/[\w\-]+/policies/[\w\-]+/webhooks/?$": {
            "post": webhooks,
            "help": "A single policy's webhooks. Format: groups/<groupID>/policies/<policyID>/webhooks"
        }
    }
}

<commit_msg>updated asconfig<commit_after>policies = [
    {
        "name": "scale up by one server",
        "change": 1,
        "cooldown": 150,
        "type": "webhook"
    },
    {
        "name": "scale down by 5.5 percent",
        "changePercent": -5.5,
        "cooldown": 6,
        "type": "webhook"
    },
    {
        "name": "cron monthly example",
        "change": 1,
        "cooldown": 100,
        "type": "schedule",
        "args": {
            "cron": "* * 3 * *",
        }
    }
]

group = {
    "groupConfiguration": {
        "name": "manitest",
        "cooldown": 5,
        "minEntities": 0,
        "maxEntities": 25,
        "metadata": {
            "firstkey": "this is a string",
            "secondkey": "1"
        }
    },
    "launchConfiguration": {
        "type": "launch_server",
        "args": {
            "server": {
                "flavorRef": "performance1-1",
                "name": "webhead",
                "imageRef": "0d589460-f177-4b0f-81c1-8ab8903ac7d8",
                "metadata": {
                    "mani": "manitest"
                },
                "networks": [
                 {
                     "uuid": "11111111-1111-1111-1111-111111111111"
                 }
                ]
            }
        }
    },
    "scalingPolicies": policies
}

webhooks = [
    {
        "name": "mani-webhook",
        "metadata": {
            "notes": "this is for mani"
        }
    }
]

config = {
    "name": "Rackspace Auto Scale",
    "description": "CLI to work on Racksapce Autoscale",
    "uriprefix": {
        "regex": "/v1.0/\d+/",
        "env": "AS_URI_PREFIX"
    },
    "headers": {
        "X-Auth-Token": "AS_AUTH_TOKEN"
    },
    "tempfile": "/tmp/ascli_req.json",
    "resources": {
        "groups/?$": {
            "post": group,
            "aliases": {
                "name": "groupConfiguration.name"
            },
            "help": "Scaling groups. Ex: groups"
        },
        "groups/[\w\-]+/?$": {
            "aliases": {
                "name": "groupConfiguration.name"
            },
            "help": "Single scaling group. Format: groups/<groupID> Ex: groups/2339-23-543"
        },
        "groups/[\w\-]+/policies/?$": {
            "post": policies,
            "help": "Scaling group's policies. Format: groups/<groupID>/policies"
        },
        "groups/[\w\-]+/policies/[\w\-]+/?$": {
            "help": "Scaling group's single policy. Format: groups/<groupID>/policies/<policyID>"
        },
        "groups/[\w\-]+/policies/[\w\-]+/webhooks/?$": {
            "post": webhooks,
            "help": "A single policy's webhooks. Format: groups/<groupID>/policies/<policyID>/webhooks"
        }
    }
}

<|endoftext|>


<commit_before># Tai Sakuma <tai.sakuma@gmail.com>
import pytest
import time

try:
    import unittest.mock as mock
except ImportError:
    import mock

from alphatwirl.progressbar import ProgressReporter

##__________________________________________________________________||
@pytest.fixture()
def queue():
    return mock.MagicMock()

@pytest.fixture()
def mocktime():
    return mock.MagicMock(return_value = 1000.0)

@pytest.fixture()
def reporter(queue, mocktime, monkeypatch):
    monkeypatch.setattr(time, 'time', mocktime)
    ret = ProgressReporter(queue)
    return ret

@pytest.fixture()
def report():
    return mock.MagicMock(**{'last.return_value': False, 'first.return_value': False})

@pytest.fixture()
def report_last():
    return mock.MagicMock(**{'last.return_value': True, 'first.return_value': False})

@pytest.fixture()
def report_first():
    return mock.MagicMock(**{'last.return_value': False, 'first.return_value': True})

##__________________________________________________________________||
def test_repr(reporter):
    repr(reporter)

def test_report(reporter, queue, mocktime, report):

    assert 1000.0 == reporter.last_time

    mocktime.return_value = 1000.2
    reporter._report(report)

    assert [mock.call(report)] == queue.put.call_args_list

    assert 1000.2 == reporter.last_time

def test_need_to_report(reporter, queue, mocktime, report, report_last,
                      report_first):

    interval = reporter.interval
    assert 0.1 == interval

    assert 1000.0 == reporter.last_time

    # before the interval passes
    mocktime.return_value += 0.1*interval
    assert not reporter._need_to_report(report)

    # the first report before the interval passes
    assert reporter._need_to_report(report_first)

    # the last report before the interval passes
    assert reporter._need_to_report(report_last)

    # after the interval passes
    mocktime.return_value += 1.2*interval
    assert reporter._need_to_report(report)

    assert 1000.0 == reporter.last_time

##__________________________________________________________________||
<commit_msg>update test_ProgressReporter.py<commit_after># Tai Sakuma <tai.sakuma@gmail.com>
import pytest
import time

try:
    import unittest.mock as mock
except ImportError:
    import mock

from alphatwirl.progressbar import ProgressReporter

##__________________________________________________________________||
@pytest.fixture()
def queue():
    return mock.MagicMock()

@pytest.fixture()
def mocktime():
    return mock.MagicMock(return_value = 1000.0)

@pytest.fixture()
def reporter(queue, mocktime, monkeypatch):
    monkeypatch.setattr(time, 'time', mocktime)
    ret = ProgressReporter(queue)
    return ret

@pytest.fixture()
def report():
    return mock.MagicMock(**{'last.return_value': False, 'first.return_value': False})

@pytest.fixture()
def report_last():
    return mock.MagicMock(**{'last.return_value': True, 'first.return_value': False})

@pytest.fixture()
def report_first():
    return mock.MagicMock(**{'last.return_value': False, 'first.return_value': True})

##__________________________________________________________________||
def test_repr(reporter):
    repr(reporter)

##__________________________________________________________________||
def test_report_no_need_to_report(reporter, monkeypatch, report):

    mock_report = mock.MagicMock()
    monkeypatch.setattr(reporter, '_report', mock_report)

    mock_need_to_report = mock.MagicMock()
    mock_need_to_report.return_value = False
    monkeypatch.setattr(reporter, '_need_to_report', mock_need_to_report)

    reporter.report(report)

    mock_report.assert_not_called()

def test_report_need_to_report(reporter, monkeypatch, report):

    mock_report = mock.MagicMock()
    monkeypatch.setattr(reporter, '_report', mock_report)

    mock_need_to_report = mock.MagicMock()
    mock_need_to_report.return_value = True
    monkeypatch.setattr(reporter, '_need_to_report', mock_need_to_report)

    reporter.report(report)

    mock_report.assert_called_once_with(report)

##__________________________________________________________________||
def test__report(reporter, queue, mocktime, report):

    assert 1000.0 == reporter.last_time

    mocktime.return_value = 1000.2
    reporter._report(report)

    assert [mock.call(report)] == queue.put.call_args_list

    assert 1000.2 == reporter.last_time

def test_need_to_report(reporter, queue, mocktime, report, report_last,
                      report_first):

    interval = reporter.interval
    assert 0.1 == interval

    assert 1000.0 == reporter.last_time

    # before the interval passes
    mocktime.return_value += 0.1*interval
    assert not reporter._need_to_report(report)

    # the first report before the interval passes
    assert reporter._need_to_report(report_first)

    # the last report before the interval passes
    assert reporter._need_to_report(report_last)

    # after the interval passes
    mocktime.return_value += 1.2*interval
    assert reporter._need_to_report(report)

    assert 1000.0 == reporter.last_time

##__________________________________________________________________||
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals

import collections
import inspect
import logging
import os.path
import pkgutil
import re
import sys
import traceback as tb
from functools import partial

import wrapt

__sacred__ = True  # marks files that should be filtered from stack traces

__all__ = ["NO_LOGGER", "PYTHON_IDENTIFIER", "CircularDependencyError",
           "ObserverError", "SacredInterrupt", "TimeoutInterrupt",
           "create_basic_stream_logger", "recursive_update",
           "iterate_flattened", "iterate_flattened_separately",
           "set_by_dotted_path", "get_by_dotted_path", "iter_path_splits",
           "iter_prefixes", "join_paths", "is_prefix",
           "convert_to_nested_dict", "convert_camel_case_to_snake_case",
           "print_filtered_stacktrace", "is_subdir",
           "optional_kwargs_decorator", "get_inheritors",
           "apply_backspaces_and_linefeeds", "StringIO", "FileNotFoundError"]

# A PY2 compatible FileNotFoundError
if sys.version_info[0] == 2:
    import errno

    class FileNotFoundError(IOError):
        def __init__(self, msg):
            super(FileNotFoundError, self).__init__(errno.ENOENT, msg)
    from StringIO import StringIO
else:
    # Reassign so that we can import it from here
    FileNotFoundError = FileNotFoundError
    from io import StringIO

NO_LOGGER = logging.getLogger('ignore')
NO_LOGGER.disabled = 1

PATHCHANGE = object()

PYTHON_IDENTIFIER = re.compile("^[a-zA-Z_][_a-zA-Z0-9]*$")

class CircularDependencyError(Exception):
    """The ingredients of the current experiment form a circular dependency."""

class ObserverError(Exception):
    """Error that an observer raises but that should not make the run fail."""

class SacredInterrupt(Exception):
    """Base-Class for all custom interrupts.

    For more information see :ref:`custom_interrupts`.
    """

    STATUS = "INTERRUPTED"

class TimeoutInterrupt(SacredInterrupt):
    """Signal a that the experiment timed out.

    This exception can be used in client code to indicate that the run
    exceeded its time limit and has been interrupted because of that.
    The status of the interrupted run will then be set to ``TIMEOUT``.

    For more information see :ref:`custom_interrupts`.
    """

    STATUS = "TIMEOUT"

def create_basic_stream_logger():
    logger = logging.getLogger('')
    logger.setLevel(logging.INFO)
    logger.handlers = []
    ch = logging.StreamHandler()
    formatter = logging.Formatter('%(levelname)s - %(name)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

def recursive_update(d, u):
    """
    Given two dictionaries d and u, update dict d recursively.

    E.g.:
    d = {'a': {'b' : 1}}
    u = {'c': 2, 'a': {'d': 3}}
    => {'a': {'b': 1, 'd': 3}, 'c': 2}
    """
    for k, v in u.items():
        if isinstance(v, collections.Mapping):
            r = recursive_update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d

def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
    """
    Recursively iterate over the items of a dictionary in a special order.

    First iterate over manually sorted keys and then over all items that are
    non-dictionary values (sorted by keys), then over the rest
    (sorted by keys), providing full dotted paths for every leaf.
    """
    if manually_sorted_keys is None:
        manually_sorted_keys = []
    for key in manually_sorted_keys:
        if key in dictionary:
            yield key, dictionary[key]

    single_line_keys = [key for key in dictionary.keys() if
                        key not in manually_sorted_keys and
                        (not dictionary[key] or
                         not isinstance(dictionary[key], dict))]
    for key in sorted(single_line_keys):
        yield key, dictionary[key]

    multi_line_keys = [key for key in dictionary.keys() if
                       key not in manually_sorted_keys and
                       (dictionary[key] and
                        isinstance(dictionary[key], dict))]
    for key in sorted(multi_line_keys):
        yield key, PATHCHANGE
        for k, val in iterate_flattened_separately(dictionary[key],
                                                   manually_sorted_keys):
            yield join_paths(key, k), val

def iterate_flattened(d):
    """
    Recursively iterate over the items of a dictionary.

    Provides a full dotted paths for every leaf.
    """
    for key in sorted(d.keys()):
        value = d[key]
        if isinstance(value, dict):
            for k, v in iterate_flattened(d[key]):
                yield join_paths(key, k), v
        else:
            yield key, value

def set_by_dotted_path(d, path, value):
    """
    Set an entry in a nested dict using a dotted path.

    Will create dictionaries as needed.

    Examples
    --------
    >>> d = {'foo': {'bar': 7}}
    >>> set_by_dotted_path(d, 'foo.bar', 10)
    >>> d
    {'foo': {'bar': 10}}
    >>> set_by_dotted_path(d, 'foo.d.baz', 3)
    >>> d
    {'foo': {'bar': 10, 'd': {'baz': 3}}}

    """
    split_path = path.split('.')
    current_option = d
    for p in split_path[:-1]:
        if p not in current_option:
            current_option[p] = dict()
        current_option = current_option[p]
    current_option[split_path[-1]] = value

def get_by_dotted_path(d, path, default=None):
    """
    Get an entry from nested dictionaries using a dotted path.

    Example:
    >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
    12
    """
    if not path:
        return d
    split_path = path.split('.')
    current_option = d
    for p in split_path:
        if p not in current_option:
            return default
        current_option = current_option[p]
    return current_option

def iter_path_splits(path):
    """
    Iterate over possible splits of a dotted path.

    The first part can be empty the second should not be.

    Example:
    >>> list(iter_path_splits('foo.bar.baz'))
    [('',        'foo.bar.baz'),
     ('foo',     'bar.baz'),
     ('foo.bar', 'baz')]
    """
    split_path = path.split('.')
    for i in range(len(split_path)):
        p1 = join_paths(*split_path[:i])
        p2 = join_paths(*split_path[i:])
        yield p1, p2

def iter_prefixes(path):
    """
    Iterate through all (non-empty) prefixes of a dotted path.

    Example:
    >>> list(iter_prefixes('foo.bar.baz'))
    ['foo', 'foo.bar', 'foo.bar.baz']
    """
    split_path = path.split('.')
    for i in range(1, len(split_path) + 1):
        yield join_paths(*split_path[:i])

def join_paths(*parts):
    """Join different parts together to a valid dotted path."""
    return '.'.join(str(p).strip('.') for p in parts if p)

def is_prefix(pre_path, path):
    """Return True if pre_path is a path-prefix of path."""
    pre_path = pre_path.strip('.')
    path = path.strip('.')
    return not pre_path or path.startswith(pre_path + '.')

def convert_to_nested_dict(dotted_dict):
    """Convert a dict with dotted path keys to corresponding nested dict."""
    nested_dict = {}
    for k, v in iterate_flattened(dotted_dict):
        set_by_dotted_path(nested_dict, k, v)
    return nested_dict

def print_filtered_stacktrace():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # determine if last exception is from sacred
    current_tb = exc_traceback
    while current_tb.tb_next is not None:
        current_tb = current_tb.tb_next
    if '__sacred__' in current_tb.tb_frame.f_globals:
        header = ["Exception originated from within Sacred.\n",
                  "Traceback (most recent calls):\n"]
        texts = tb.format_exception(exc_type, exc_value, exc_traceback)
    else:
        header = ["Traceback (most recent calls WITHOUT Sacred internals):\n"]
        texts = tb.format_exception(exc_type, exc_value, exc_traceback)
    print("".join(header + texts[1:]).strip(), file=sys.stderr)

def is_subdir(path, directory):
    path = os.path.abspath(os.path.realpath(path)) + os.sep
    directory = os.path.abspath(os.path.realpath(directory)) + os.sep

    return path.startswith(directory)

# noinspection PyUnusedLocal
@wrapt.decorator
def optional_kwargs_decorator(wrapped, instance=None, args=None, kwargs=None):
    # here wrapped is itself a decorator
    if args:  # means it was used as a normal decorator (so just call it)
        return wrapped(*args, **kwargs)
    else:  # used with kwargs, so we need to return a decorator
        return partial(wrapped, **kwargs)

def get_inheritors(cls):
    """Get a set of all classes that inherit from the given class."""
    subclasses = set()
    work = [cls]
    while work:
        parent = work.pop()
        for child in parent.__subclasses__():
            if child not in subclasses:
                subclasses.add(child)
                work.append(child)
    return subclasses

# Credit to Zarathustra and epost from stackoverflow
# Taken from http://stackoverflow.com/a/1176023/1388435
def convert_camel_case_to_snake_case(name):
    """Convert CamelCase to snake_case."""
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def apply_backspaces_and_linefeeds(text):
    """
    Interpret backspaces and linefeeds in text like a terminal would.

    Interpret text like a terminal by removing backspace and linefeed
    characters and applying them line by line.

    If final line ends with a carriage it keeps it to be concatenable with next
    output chunk.
    """
    orig_lines = text.split('\n')
    orig_lines_len = len(orig_lines)
    new_lines = []
    for orig_line_idx, orig_line in enumerate(orig_lines):
        chars, cursor = [], 0
        orig_line_len = len(orig_line)
        for orig_char_idx, orig_char in enumerate(orig_line):
            if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
                                      orig_line_idx != orig_lines_len - 1):
                cursor = 0
            elif orig_char == '\b':
                cursor = max(0, cursor - 1)
            else:
                if (orig_char == '\r' and
                        orig_char_idx == orig_line_len - 1 and
                        orig_line_idx == orig_lines_len - 1):
                    cursor = len(chars)
                if cursor == len(chars):
                    chars.append(orig_char)
                else:
                    chars[cursor] = orig_char
                cursor += 1
        new_lines.append(''.join(chars))
    return '\n'.join(new_lines)

def module_exists(modname):
    """Checks if a module exists without actually importing it."""
    return pkgutil.find_loader(modname) is not None

def modules_exist(*modnames):
    return all(module_exists(m) for m in modnames)

def module_is_in_cache(modname):
    """Checks if a module was imported before (is in the import cache)."""
    return modname in sys.modules

def module_is_imported(modname, scope=None):
    """Checks if a module is imported within the current namespace."""
    # return early if modname is not even cached
    if not module_is_in_cache(modname):
        return False

    if scope is None:  # use globals() of the caller by default
        scope = inspect.stack()[1][0].f_globals

    for m in scope.values():
        if isinstance(m, type(sys)) and m.__name__ == modname:
            return True

    return False
<commit_msg>Fix #225<commit_after>#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals

import collections
import inspect
import logging
import os.path
import pkgutil
import re
import sys
import traceback as tb
from functools import partial

import wrapt

__sacred__ = True  # marks files that should be filtered from stack traces

__all__ = ["NO_LOGGER", "PYTHON_IDENTIFIER", "CircularDependencyError",
           "ObserverError", "SacredInterrupt", "TimeoutInterrupt",
           "create_basic_stream_logger", "recursive_update",
           "iterate_flattened", "iterate_flattened_separately",
           "set_by_dotted_path", "get_by_dotted_path", "iter_path_splits",
           "iter_prefixes", "join_paths", "is_prefix",
           "convert_to_nested_dict", "convert_camel_case_to_snake_case",
           "print_filtered_stacktrace", "is_subdir",
           "optional_kwargs_decorator", "get_inheritors",
           "apply_backspaces_and_linefeeds", "StringIO", "FileNotFoundError"]

# A PY2 compatible FileNotFoundError
if sys.version_info[0] == 2:
    import errno

    class FileNotFoundError(IOError):
        def __init__(self, msg):
            super(FileNotFoundError, self).__init__(errno.ENOENT, msg)
    from StringIO import StringIO
else:
    # Reassign so that we can import it from here
    FileNotFoundError = FileNotFoundError
    from io import StringIO

NO_LOGGER = logging.getLogger('ignore')
NO_LOGGER.disabled = 1

PATHCHANGE = object()

PYTHON_IDENTIFIER = re.compile("^[a-zA-Z_][_a-zA-Z0-9]*$")

class CircularDependencyError(Exception):
    """The ingredients of the current experiment form a circular dependency."""

class ObserverError(Exception):
    """Error that an observer raises but that should not make the run fail."""

class SacredInterrupt(Exception):
    """Base-Class for all custom interrupts.

    For more information see :ref:`custom_interrupts`.
    """

    STATUS = "INTERRUPTED"

class TimeoutInterrupt(SacredInterrupt):
    """Signal a that the experiment timed out.

    This exception can be used in client code to indicate that the run
    exceeded its time limit and has been interrupted because of that.
    The status of the interrupted run will then be set to ``TIMEOUT``.

    For more information see :ref:`custom_interrupts`.
    """

    STATUS = "TIMEOUT"

def create_basic_stream_logger():
    logger = logging.getLogger('')
    logger.setLevel(logging.INFO)
    logger.handlers = []
    ch = logging.StreamHandler()
    formatter = logging.Formatter('%(levelname)s - %(name)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

def recursive_update(d, u):
    """
    Given two dictionaries d and u, update dict d recursively.

    E.g.:
    d = {'a': {'b' : 1}}
    u = {'c': 2, 'a': {'d': 3}}
    => {'a': {'b': 1, 'd': 3}, 'c': 2}
    """
    for k, v in u.items():
        if isinstance(v, collections.Mapping):
            r = recursive_update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d

def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
    """
    Recursively iterate over the items of a dictionary in a special order.

    First iterate over manually sorted keys and then over all items that are
    non-dictionary values (sorted by keys), then over the rest
    (sorted by keys), providing full dotted paths for every leaf.
    """
    if manually_sorted_keys is None:
        manually_sorted_keys = []
    for key in manually_sorted_keys:
        if key in dictionary:
            yield key, dictionary[key]

    single_line_keys = [key for key in dictionary.keys() if
                        key not in manually_sorted_keys and
                        (not dictionary[key] or
                         not isinstance(dictionary[key], dict))]
    for key in sorted(single_line_keys):
        yield key, dictionary[key]

    multi_line_keys = [key for key in dictionary.keys() if
                       key not in manually_sorted_keys and
                       (dictionary[key] and
                        isinstance(dictionary[key], dict))]
    for key in sorted(multi_line_keys):
        yield key, PATHCHANGE
        for k, val in iterate_flattened_separately(dictionary[key],
                                                   manually_sorted_keys):
            yield join_paths(key, k), val

def iterate_flattened(d):
    """
    Recursively iterate over the items of a dictionary.

    Provides a full dotted paths for every leaf.
    """
    for key in sorted(d.keys()):
        value = d[key]
        if isinstance(value, dict):
            for k, v in iterate_flattened(d[key]):
                yield join_paths(key, k), v
        else:
            yield key, value

def set_by_dotted_path(d, path, value):
    """
    Set an entry in a nested dict using a dotted path.

    Will create dictionaries as needed.

    Examples
    --------
    >>> d = {'foo': {'bar': 7}}
    >>> set_by_dotted_path(d, 'foo.bar', 10)
    >>> d
    {'foo': {'bar': 10}}
    >>> set_by_dotted_path(d, 'foo.d.baz', 3)
    >>> d
    {'foo': {'bar': 10, 'd': {'baz': 3}}}

    """
    split_path = path.split('.')
    current_option = d
    for p in split_path[:-1]:
        if p not in current_option:
            current_option[p] = dict()
        current_option = current_option[p]
    current_option[split_path[-1]] = value

def get_by_dotted_path(d, path, default=None):
    """
    Get an entry from nested dictionaries using a dotted path.

    Example:
    >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
    12
    """
    if not path:
        return d
    split_path = path.split('.')
    current_option = d
    for p in split_path:
        if p not in current_option:
            return default
        current_option = current_option[p]
    return current_option

def iter_path_splits(path):
    """
    Iterate over possible splits of a dotted path.

    The first part can be empty the second should not be.

    Example:
    >>> list(iter_path_splits('foo.bar.baz'))
    [('',        'foo.bar.baz'),
     ('foo',     'bar.baz'),
     ('foo.bar', 'baz')]
    """
    split_path = path.split('.')
    for i in range(len(split_path)):
        p1 = join_paths(*split_path[:i])
        p2 = join_paths(*split_path[i:])
        yield p1, p2

def iter_prefixes(path):
    """
    Iterate through all (non-empty) prefixes of a dotted path.

    Example:
    >>> list(iter_prefixes('foo.bar.baz'))
    ['foo', 'foo.bar', 'foo.bar.baz']
    """
    split_path = path.split('.')
    for i in range(1, len(split_path) + 1):
        yield join_paths(*split_path[:i])

def join_paths(*parts):
    """Join different parts together to a valid dotted path."""
    return '.'.join(str(p).strip('.') for p in parts if p)

def is_prefix(pre_path, path):
    """Return True if pre_path is a path-prefix of path."""
    pre_path = pre_path.strip('.')
    path = path.strip('.')
    return not pre_path or path.startswith(pre_path + '.')

def convert_to_nested_dict(dotted_dict):
    """Convert a dict with dotted path keys to corresponding nested dict."""
    nested_dict = {}
    for k, v in iterate_flattened(dotted_dict):
        set_by_dotted_path(nested_dict, k, v)
    return nested_dict

def print_filtered_stacktrace():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # determine if last exception is from sacred
    current_tb = exc_traceback
    while current_tb.tb_next is not None:
        current_tb = current_tb.tb_next
    if '__sacred__' in current_tb.tb_frame.f_globals:
        print("Exception originated from within Sacred.\n"
              "Traceback (most recent calls):", file=sys.stderr)
        tb.print_exception(exc_type, exc_value, current_tb)
    else:
        tb_exception =\
            tb.TracebackException(exc_type, exc_value, exc_traceback,
                                  limit=None)
        for line in filtered_traceback_format(tb_exception):
            print(line, file=sys.stderr, end="")

def filtered_traceback_format(tb_exception, chain=True):
    if chain:
        if tb_exception.__cause__ is not None:
            yield from filtered_traceback_format(tb_exception.__cause__,
                                                 chain=chain)
            yield tb._cause_message
        elif (tb_exception.__context__ is not None and
            not tb_exception.__suppress_context__):
            yield from filtered_traceback_format(tb_exception.__context__,
                                                 chain=chain)
            yield tb._context_message
    yield 'Traceback (most recent calls WITHOUT Sacred internals):\n'
    current_tb = tb_exception.exc_traceback
    while current_tb is not None:
        if '__sacred__' not in current_tb.tb_frame.f_globals:
            stack = tb.StackSummary.extract(tb.walk_tb(current_tb),
                                            limit=1,
                                            lookup_lines=True,
                                            capture_locals=False)
            yield from stack.format()
        current_tb = current_tb.tb_next
    yield from tb_exception.format_exception_only()

def is_subdir(path, directory):
    path = os.path.abspath(os.path.realpath(path)) + os.sep
    directory = os.path.abspath(os.path.realpath(directory)) + os.sep

    return path.startswith(directory)

# noinspection PyUnusedLocal
@wrapt.decorator
def optional_kwargs_decorator(wrapped, instance=None, args=None, kwargs=None):
    # here wrapped is itself a decorator
    if args:  # means it was used as a normal decorator (so just call it)
        return wrapped(*args, **kwargs)
    else:  # used with kwargs, so we need to return a decorator
        return partial(wrapped, **kwargs)

def get_inheritors(cls):
    """Get a set of all classes that inherit from the given class."""
    subclasses = set()
    work = [cls]
    while work:
        parent = work.pop()
        for child in parent.__subclasses__():
            if child not in subclasses:
                subclasses.add(child)
                work.append(child)
    return subclasses

# Credit to Zarathustra and epost from stackoverflow
# Taken from http://stackoverflow.com/a/1176023/1388435
def convert_camel_case_to_snake_case(name):
    """Convert CamelCase to snake_case."""
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def apply_backspaces_and_linefeeds(text):
    """
    Interpret backspaces and linefeeds in text like a terminal would.

    Interpret text like a terminal by removing backspace and linefeed
    characters and applying them line by line.

    If final line ends with a carriage it keeps it to be concatenable with next
    output chunk.
    """
    orig_lines = text.split('\n')
    orig_lines_len = len(orig_lines)
    new_lines = []
    for orig_line_idx, orig_line in enumerate(orig_lines):
        chars, cursor = [], 0
        orig_line_len = len(orig_line)
        for orig_char_idx, orig_char in enumerate(orig_line):
            if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
                                      orig_line_idx != orig_lines_len - 1):
                cursor = 0
            elif orig_char == '\b':
                cursor = max(0, cursor - 1)
            else:
                if (orig_char == '\r' and
                        orig_char_idx == orig_line_len - 1 and
                        orig_line_idx == orig_lines_len - 1):
                    cursor = len(chars)
                if cursor == len(chars):
                    chars.append(orig_char)
                else:
                    chars[cursor] = orig_char
                cursor += 1
        new_lines.append(''.join(chars))
    return '\n'.join(new_lines)

def module_exists(modname):
    """Checks if a module exists without actually importing it."""
    return pkgutil.find_loader(modname) is not None

def modules_exist(*modnames):
    return all(module_exists(m) for m in modnames)

def module_is_in_cache(modname):
    """Checks if a module was imported before (is in the import cache)."""
    return modname in sys.modules

def module_is_imported(modname, scope=None):
    """Checks if a module is imported within the current namespace."""
    # return early if modname is not even cached
    if not module_is_in_cache(modname):
        return False

    if scope is None:  # use globals() of the caller by default
        scope = inspect.stack()[1][0].f_globals

    for m in scope.values():
        if isinstance(m, type(sys)) and m.__name__ == modname:
            return True

    return False
<|endoftext|>