text:
import gtk
import gobject
import os
import shutil
import telepathy
import telepathy.client
import logging
import xml.dom.minidom
import time
from xml.dom.minidom import parse
import pygst
pygst.require('0.10')
import gst

import logging
logger = logging.getLogger('record:record.py')

from sugar.activity import activity
from sugar.presence import presenceservice
from sugar.presence.tubeconn import TubeConnection
from sugar import util
import port.json

from model import Model
from ui import UI
from recordtube import RecordTube
from glive import Glive
from glivex import GliveX
from gplay import Gplay
from greplay import Greplay
from recorded import Recorded
from constants import Constants
import instance
from instance import Instance
import serialize
import utils

gst.debug_set_active(True)
gst.debug_set_colored(False)
if logging.getLogger().level <= logging.DEBUG:
    gst.debug_set_default_threshold(gst.LEVEL_WARNING)
else:
    gst.debug_set_default_threshold(gst.LEVEL_ERROR)

class Record(activity.Activity):

    log = logging.getLogger('record-activity')

    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        #flags for controlling the writing to the datastore
        self.I_AM_CLOSING = False
        self.I_AM_SAVED = False

        self.props.enable_fullscreen_mode = False
        Instance(self)
        Constants(self)
        self.modify_bg( gtk.STATE_NORMAL, Constants.colorBlack.gColor )

        #wait a moment so that our debug console capture mistakes
        gobject.idle_add( self._initme, None )

    def _initme( self, userdata=None ):
        #totally tubular
        self.meshTimeoutTime = 10000
        self.recTube = None
        self.connect( "shared", self._sharedCb )

        #the main classes
        self.m = Model(self)
        self.glive = Glive(self)
        self.glivex = GliveX(self)
        self.gplay = Gplay(self)
        self.ui = UI(self)

        #CSCL
        if self._shared_activity:
            #have you joined or shared this activity yourself?
            if self.get_shared():
                self._meshJoinedCb( self )
            else:
                self.connect("joined", self._meshJoinedCb)

        return False

    def read_file(self, file):
        try:
            dom = parse(file)
        except Exception, e:
            logger.error('read_file: %s' % e)
            return

        serialize.fillMediaHash(dom, self.m.mediaHashs)

        for i in dom.documentElement.getElementsByTagName('ui'):
            for ui_el in i.childNodes:
                self.ui.deserialize(port.json.loads(ui_el.data))

    def write_file(self, file):
        self.I_AM_SAVED = False

        self.m.mediaHashs['ui'] = self.ui.serialize()

        dom = serialize.saveMediaHash(self.m.mediaHashs)

        ui_data = port.json.dumps(self.ui.serialize())
        ui_el = dom.createElement('ui')
        ui_el.appendChild(dom.createTextNode(ui_data))
        dom.documentElement.appendChild(ui_el)

        xmlFile = open( file, "w" )
        dom.writexml(xmlFile)
        xmlFile.close()

        allDone = True
        for h in range (0, len(self.m.mediaHashs)-1):
            mhash = self.m.mediaHashs[h]
            for i in range (0, len(mhash)):
                recd = mhash[i]

                if ( (not recd.savedMedia) or (not recd.savedXml) ):
                    allDone = False

                if (self.I_AM_CLOSING):
                    mediaObject = recd.datastoreOb
                    if (mediaObject != None):
                        recd.datastoreOb = None
                        mediaObject.destroy()
                        del mediaObject

        self.I_AM_SAVED = True
        if (self.I_AM_SAVED and self.I_AM_CLOSING):
            self.destroy()

    def stopPipes(self):
        self.ui.doMouseListener( False )
        self.m.setUpdating( False )

        if (self.ui.COUNTINGDOWN):
            self.m.abandonRecording()
        elif (self.m.RECORDING):
            self.m.doShutter()
        else:
            self.glive.stop()
            self.glivex.stop()

    def restartPipes(self):
        if (not self.ui.TRANSCODING):
            self.ui.updateModeChange( )
            self.ui.doMouseListener( True )

    def close( self ):
        self.I_AM_CLOSING = True

        self.m.UPDATING = False
        if (self.ui != None):
            self.ui.updateButtonSensitivities( )
            self.ui.doMouseListener( False )
            self.ui.hideAllWindows()
        if (self.gplay != None):
            self.gplay.stop( )
        if (self.glive != None):
            self.glive.stop( )
        if self.glivex != None:
            self.glivex.stop()

        #this calls write_file
        activity.Activity.close( self )

    def destroy( self ):
        if self.I_AM_SAVED:
            activity.Activity.destroy( self )

    def _sharedCb( self, activity ):
        self._setup()

        id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube( Constants.SERVICE, {})

    def _meshJoinedCb( self, activity ):
        if not self._shared_activity:
            return

        self._setup()

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._list_tubes_reply_cb, error_handler=self._list_tubes_error_cb)

    def _list_tubes_reply_cb(self, tubes):
        for tube_info in tubes:
            self._newTubeCb(*tube_info)

    def _list_tubes_error_cb(self, e):
        self.__class__.log.error('ListTubes() failed: %s', e)

    def _setup(self):
        #sets up the tubes...
        if self._shared_activity is None:
            self.__class__.log.error('_setup: Failed to share or join activity')
            return

        pservice = presenceservice.get_instance()
        try:
            name, path = pservice.get_preferred_connection()
            self.conn = telepathy.client.Connection(name, path)
        except:
            self.__class__.log.error('_setup: Failed to get_preferred_connection')

        # Work out what our room is called and whether we have Tubes already
        bus_name, conn_path, channel_paths = self._shared_activity.get_channels()
        room = None
        tubes_chan = None
        text_chan = None
        for channel_path in channel_paths:
            channel = telepathy.client.Channel(bus_name, channel_path)
            htype, handle = channel.GetHandle()
            if htype == telepathy.HANDLE_TYPE_ROOM:
                self.__class__.log.debug('Found our room: it has handle#%d "%s"', handle, self.conn.InspectHandles(htype, [handle])[0])
                room = handle
                ctype = channel.GetChannelType()
                if ctype == telepathy.CHANNEL_TYPE_TUBES:
                    self.__class__.log.debug('Found our Tubes channel at %s', channel_path)
                    tubes_chan = channel
                elif ctype == telepathy.CHANNEL_TYPE_TEXT:
                    self.__class__.log.debug('Found our Text channel at %s', channel_path)
                    text_chan = channel

        if room is None:
            self.__class__.log.error("Presence service didn't create a room")
            return
        if text_chan is None:
                self.__class__.log.error("Presence service didn't create a text channel")
                return

        # Make sure we have a Tubes channel - PS doesn't yet provide one
        if tubes_chan is None:
            self.__class__.log.debug("Didn't find our Tubes channel, requesting one...")
            tubes_chan = self.conn.request_channel(telepathy.CHANNEL_TYPE_TUBES, telepathy.HANDLE_TYPE_ROOM, room, True)

        self.tubes_chan = tubes_chan
        self.text_chan = text_chan

        tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal('NewTube', self._newTubeCb)

    def _newTubeCb(self, id, initiator, type, service, params, state):
        self.__class__.log.debug('New tube: ID=%d initator=%d type=%d service=%s params=%r state=%d', id, initiator, type, service, params, state)
        if (type == telepathy.TUBE_TYPE_DBUS and service == Constants.SERVICE):
            if state == telepathy.TUBE_STATE_LOCAL_PENDING:
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(id)
            tube_conn = TubeConnection(self.conn, self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])
            self.recTube = RecordTube(tube_conn)
            self.recTube.connect("new-recd", self._newRecdCb)
            self.recTube.connect("recd-request", self._recdRequestCb)
            self.recTube.connect("recd-bits-arrived", self._recdBitsArrivedCb)
            self.recTube.connect("recd-unavailable", self._recdUnavailableCb)

    def _newRecdCb( self, objectThatSentTheSignal, recorder, xmlString ):
        self.__class__.log.debug('_newRecdCb')
        dom = None
        try:
            dom = xml.dom.minidom.parseString(xmlString)
        except:
            self.__class__.log.error('Unable to parse mesh xml')
        if (dom == None):
            return

        recd = Recorded()
        recd = serialize.fillRecdFromNode(recd, dom.documentElement)
        if (recd != None):
            self.__class__.log.debug('_newRecdCb: adding new recd thumb')
            recd.buddy = True
            recd.downloadedFromBuddy = False
            self.m.addMeshRecd( recd )
        else:
            self.__class__.log.debug('_newRecdCb: recd is None. Unable to parse XML')

    def requestMeshDownload( self, recd ):
        if (recd.meshDownloading):
            return True

        self.m.updateXoFullStatus()
        if (self.m.FULL):
            return True

        #this call will get the bits or request the bits if they're not available
        if (recd.buddy and (not recd.downloadedFromBuddy)):
            self.meshInitRoundRobin(recd)
            return True

        else:
            return False

    def meshInitRoundRobin( self, recd ):
        if (recd.meshDownloading):
            self.__class__.log.debug("meshInitRoundRobin: we are in midst of downloading this file...")
            return

        if (self.recTube == None):
            gobject.idle_add(self.ui.updateMeshProgress, False, recd)
            return

        #start with who took the photo
        recd.triedMeshBuddies = []
        recd.triedMeshBuddies.append(Instance.keyHashPrintable)
        self.meshReqRecFromBuddy( recd, recd.recorderHash, recd.recorderName )

    def meshNextRoundRobinBuddy( self, recd ):
        self.__class__.log.debug('meshNextRoundRobinBuddy')
        if (recd.meshReqCallbackId != 0):
            gobject.source_remove(recd.meshReqCallbackId)
            recd.meshReqCallbackId = 0

        #delete any stub of a partially downloaded file
        filepath = recd.getMediaFilepath()
        if (filepath != None):
            if (os.path.exists(filepath)):
                os.remove( filepath )

        goodBudObj = None
        buds = self._shared_activity.get_joined_buddies()
        for i in range (0, len(buds)):
            nextBudObj = buds[i]
            nextBud = util._sha_data(nextBudObj.props.key)
            nextBud = util.printable_hash(nextBud)
            if (recd.triedMeshBuddies.count(nextBud) > 0):
                self.__class__.log.debug('mnrrb: weve already tried bud ' + str(nextBudObj.props.nick))
            else:
                self.__class__.log.debug('mnrrb: ask next buddy: ' + str(nextBudObj.props.nick))
                goodBudObj = nextBudObj
                break

        if (goodBudObj != None):
            goodNick = goodBudObj.props.nick
            goodBud = util._sha_data(goodBudObj.props.key)
            goodBud = util.printable_hash(goodBud)
            self.meshReqRecFromBuddy(recd, goodBud, goodNick)
        else:
            self.__class__.log.debug('weve tried all buddies here, and no one has this recd')
            recd.meshDownloading = False
            recd.triedMeshBuddies = []
            recd.triedMeshBuddies.append(Instance.keyHashPrintable)
            self.ui.updateMeshProgress(False, recd)

    def meshReqRecFromBuddy( self, recd, fromWho, fromWhosNick ):
        recd.triedMeshBuddies.append( fromWho )
        recd.meshDownloadingFrom = fromWho
        recd.meshDownloadingFromNick = fromWhosNick
        recd.meshDownloadingProgress = False
        recd.meshDownloading = True
        recd.meshDownlodingPercent = 0.0
        self.ui.updateMeshProgress(True, recd)
        recd.meshReqCallbackId = gobject.timeout_add(self.meshTimeoutTime, self._meshCheckOnRecdRequest, recd)
        self.recTube.requestRecdBits( Instance.keyHashPrintable, fromWho, recd.mediaMd5 )

    def _meshCheckOnRecdRequest( self, recdRequesting ):
        #todo: add category for "not active activity, so go ahead and delete"

        if (recdRequesting.downloadedFromBuddy):
            self.__class__.log.debug('_meshCheckOnRecdRequest: recdRequesting.downloadedFromBuddy')
            if (recdRequesting.meshReqCallbackId != 0):
                gobject.source_remove(recdRequesting.meshReqCallbackId)
                recdRequesting.meshReqCallbackId = 0
            return False
        if (recdRequesting.deleted):
            self.__class__.log.debug('_meshCheckOnRecdRequest: recdRequesting.deleted')
            if (recdRequesting.meshReqCallbackId != 0):
                gobject.source_remove(recdRequesting.meshReqCallbackId)
                recdRequesting.meshReqCallbackId = 0
            return False
        if (recdRequesting.meshDownloadingProgress):
            self.__class__.log.debug('_meshCheckOnRecdRequest: recdRequesting.meshDownloadingProgress')
            #we've received some bits since last we checked, so keep waiting...  they'll all get here eventually!
            recdRequesting.meshDownloadingProgress = False
            return True
        else:
            self.__class__.log.debug('_meshCheckOnRecdRequest: ! recdRequesting.meshDownloadingProgress')
            #that buddy we asked info from isn't responding; next buddy!
            #self.meshNextRoundRobinBuddy( recdRequesting )
            gobject.idle_add(self.meshNextRoundRobinBuddy, recdRequesting)
            return False

    def _recdRequestCb( self, objectThatSentTheSignal, whoWantsIt, md5sumOfIt ):
        #if we are here, it is because someone has been told we have what they want.
        #we need to send them that thing, whatever that thing is
        recd = self.m.getRecdByMd5( md5sumOfIt )
        if (recd == None):
            self.__class__.log.debug('_recdRequestCb: we dont have the recd they asked for')
            self.recTube.unavailableRecd(md5sumOfIt, Instance.keyHashPrintable, whoWantsIt)
            return
        if (recd.deleted):
            self.__class__.log.debug('_recdRequestCb: we have the recd, but it has been deleted, so we wont share')
            self.recTube.unavailableRecd(md5sumOfIt, Instance.keyHashPrintable, whoWantsIt)
            return
        if (recd.buddy and not recd.downloadedFromBuddy):
            self.__class__.log.debug('_recdRequestCb: we have an incomplete recd, so we wont share')
            self.recTube.unavailableRecd(md5sumOfIt, Instance.keyHashPrintable, whoWantsIt)
            return

        recd.meshUploading = True
        filepath = recd.getMediaFilepath()

        if (recd.type == Constants.TYPE_AUDIO):
            audioImgFilepath = recd.getAudioImageFilepath()

            destPath = os.path.join(Instance.instancePath, "audioBundle")
            destPath = utils.getUniqueFilepath(destPath, 0)
            cmd = "cat " + str(filepath) + " " + str(audioImgFilepath) + " > " + str(destPath)
            self.__class__.log.debug(cmd)
            os.system(cmd)
            filepath = destPath

        sent = self.recTube.broadcastRecd(recd.mediaMd5, filepath, whoWantsIt)
        recd.meshUploading = False
        #if you were deleted while uploading, now throw away those bits now
        if (recd.deleted):
            recd.doDeleteRecorded(recd)

    def _recdBitsArrivedCb( self, objectThatSentTheSignal, md5sumOfIt, part, numparts, bytes, fromWho ):
        #self.__class__.log.debug('_recdBitsArrivedCb: ' + str(part) + "/" + str(numparts))
        recd = self.m.getRecdByMd5( md5sumOfIt )
        if (recd == None):
            self.__class__.log.debug('_recdBitsArrivedCb: thx 4 yr bits, but we dont even have that photo')
            return
        if (recd.deleted):
            self.__class__.log.debug('_recdBitsArrivedCb: thx 4 yr bits, but we deleted that photo')
            return
        if (recd.downloadedFromBuddy):
            self.__class__.log.debug('_recdBitsArrivedCb: weve already downloadedFromBuddy')
            return
        if (not recd.buddy):
            self.__class__.log.debug('_recdBitsArrivedCb: uh, we took this photo, so dont need your bits')
            return
        if (recd.meshDownloadingFrom != fromWho):
            self.__class__.log.debug('_recdBitsArrivedCb: wrong bits ' + str(fromWho) + ", exp:" + str(recd.meshDownloadingFrom))
            return

        #update that we've heard back about this, reset the timeout
        gobject.source_remove(recd.meshReqCallbackId)
        recd.meshReqCallbackId = gobject.timeout_add(self.meshTimeoutTime, self._meshCheckOnRecdRequest, recd)

        #update the progress bar
        recd.meshDownlodingPercent = (part+0.0)/(numparts+0.0)
        recd.meshDownloadingProgress = True
        self.ui.updateMeshProgress(True, recd)
        f = open(recd.getMediaFilepath(), 'a+')
        f.write(bytes)
        f.close()

        if part == numparts:
            self.__class__.log.debug('Finished receiving %s' % recd.title)
            gobject.source_remove( recd.meshReqCallbackId )
            recd.meshReqCallbackId = 0
            recd.meshDownloading = False
            recd.meshDownlodingPercent = 1.0
            recd.downloadedFromBuddy = True
            if (recd.type == Constants.TYPE_AUDIO):
                filepath = recd.getMediaFilepath()
                bundlePath = os.path.join(Instance.instancePath, "audioBundle")
                bundlePath = utils.getUniqueFilepath(bundlePath, 0)

                cmd = "split -a 1 -b " + str(recd.mediaBytes) + " " + str(filepath) + " " + str(bundlePath)
                self.__class__.log.debug( cmd )
                os.system( cmd )

                bundleName = os.path.basename(bundlePath)
                mediaFilename = str(bundleName) + "a"
                mediaFilepath = os.path.join(Instance.instancePath, mediaFilename)
                mediaFilepathExt = os.path.join(Instance.instancePath, mediaFilename+".ogg")
                os.rename(mediaFilepath, mediaFilepathExt)
                audioImageFilename = str(bundleName) + "b"
                audioImageFilepath = os.path.join(Instance.instancePath, audioImageFilename)
                audioImageFilepathExt = os.path.join(Instance.instancePath, audioImageFilename+".png")
                os.rename(audioImageFilepath, audioImageFilepathExt)

                recd.mediaFilename = os.path.basename(mediaFilepathExt)
                recd.audioImageFilename = os.path.basename(audioImageFilepathExt)

            self.ui.showMeshRecd( recd )
        elif part > numparts:
            self.__class__.log.error('More parts than required have arrived')

    def _getAlbumArtCb( self, objectThatSentTheSignal, pixbuf, recd ):

        if (pixbuf != None):
            imagePath = os.path.join(Instance.instancePath, "audioPicture.png")
            imagePath = utils.getUniqueFilepath( imagePath, 0 )
            pixbuf.save( imagePath, "png", {} )
            recd.audioImageFilename = os.path.basename(imagePath)

        self.ui.showMeshRecd( recd )
        return False

    def _recdUnavailableCb( self, objectThatSentTheSignal, md5sumOfIt, whoDoesntHaveIt ):
        self.__class__.log.debug('_recdUnavailableCb: sux, we want to see that photo')
        recd = self.m.getRecdByMd5( md5sumOfIt )
        if (recd == None):
            self.__class__.log.debug('_recdUnavailableCb: actually, we dont even know about that one..')
            return
        if (recd.deleted):
            self.__class__.log.debug('_recdUnavailableCb: actually, since we asked, we deleted.')
            return
        if (not recd.buddy):
            self.__class__.log.debug('_recdUnavailableCb: uh, odd, we took that photo and have it already.')
            return
        if (recd.downloadedFromBuddy):
            self.__class__.log.debug('_recdUnavailableCb: we already downloaded it...  you might have been slow responding.')
            return
        if (recd.meshDownloadingFrom != whoDoesntHaveIt):
            self.__class__.log.debug('_recdUnavailableCb: we arent asking you for a copy now.  slow response, pbly.')
            return

        #self.meshNextRoundRobinBuddy( recd )


text:
package com.tianma.propertyanimationsample;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Object Animator Sample
 */
public class ObjectAnimatorSampleActivity extends AppCompatActivity {

    private Button alphaAnimBtn;
    private Button rotationAnimBtn;
    private Button translationAnimBtn;
    private Button scaleAnimBtn;

    private TextView sampleText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_animator_sample);

        initViews();

    }

    private void initViews() {
        alphaAnimBtn = (Button) findViewById(R.id.alpha_animator);
        rotationAnimBtn = (Button) findViewById(R.id.rotation_animator);
        translationAnimBtn = (Button) findViewById(R.id.translation_x_animator);
        scaleAnimBtn = (Button) findViewById(R.id.scale_y_animator);

        sampleText = (TextView) findViewById(R.id.sample_text);

        alphaAnimBtn.setOnClickListener(listener);
        rotationAnimBtn.setOnClickListener(listener);
        translationAnimBtn.setOnClickListener(listener);
        scaleAnimBtn.setOnClickListener(listener);

        findViewById(R.id.combine_animator).setOnClickListener(listener);

    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.alpha_animator:
                    alphaAnimatorSample();
                    break;
                case R.id.rotation_animator:
                    rotationAnimatorSample();
                    break;
                case R.id.translation_x_animator:
                    translationAnimatorSample();
                    break;
                case R.id.scale_y_animator:
                    scaleAnimatorSample();
                    break;
                case R.id.combine_animator:
                    combineAnimatorSample();
                    break;
            }
        }
    };

    private void animate(String property, float... values) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(sampleText, property, values);
        animator.setDuration(5000);
        animator.start();
    }

    private void alphaAnimatorSample() {
        animate("alpha", 1f, 0f, 1f);
    }

    private void rotationAnimatorSample() {
        animate("rotation", 0f, 360f);
    }

    private void translationAnimatorSample() {
        float x = sampleText.getTranslationX();
        animate("translationX", x, -500f, x);
    }

    private void scaleAnimatorSample() {
        animate("scaleY", 1f, 3f, 0.5f, 1f);
    }

    private void combineAnimatorSample() {
        float currentX = sampleText.getTranslationX();
        ObjectAnimator moveIn = ObjectAnimator.ofFloat(sampleText, "translationX", -500, currentX);
        ObjectAnimator rotate = ObjectAnimator.ofFloat(sampleText, "rotation", 0f, 360f);
        ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(sampleText, "alpha", 1f, 0f, 1f);
        ObjectAnimator zoomOutIn = ObjectAnimator.ofFloat(sampleText, "scaleY", 1f, 3f, 0.1f, 1f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(rotate).with(fadeInOut).before(zoomOutIn).after(moveIn);
        animatorSet.setDuration(3000);
        animatorSet.start();

    }

}

redpajama_set_name: RedPajamaGithub


text:
Front End for Course Management System

Dependencies:

Angular 1.5.3

jQuery 2.2.0

Bootstrap 3.3.5

ui-Bootstrap 0.9.

Don't need to install. Included in the repo.


text:
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import jsdomReact from './jsdomReact';

import CategorizedTagInput from '../src/CategorizedTagInput.jsx';

describe('CategorizedTagInput', () => {
  jsdomReact();
});


text:
import math
from pyglet.gl import *
from pyglet import font
import sys, os
from pyglet.window import key
sys.path.append('../..')
sys.path.append('../../..')
from sprite_struct import Sprite, Vec3, Color
from controls import Controls, message
#imports for particle effects
from pyglet import image
from lepton import Particle, ParticleGroup, default_system
from lepton.renderer import BillboardRenderer
from lepton.emitter import StaticEmitter
from lepton.controller import Gravity, Lifetime, Movement, Fader, ColorBlender

class game_system(object):
	"""game system controls when objects in the system get updated"""
	objects = ()
	controllers = ()
	def __init__(self, window=None, objects=(), controllers=()):
		#Create a font for score
		self.font = font.load('Arial', 18)
		#pyglet.font.Text object to display the score
		self.score = font.Text(self.font, x = 10, y=10, color=(1, 1, 1, 1))
		self.control = Controls(window)
		self.bind_objects(*objects)
		self.bind_controllers(*controllers)
		self.score_right = 0
		self.score_left = 0
		self.draw_score()
		self.height = window.width
		self.width  = window.height
		#should this not be handled within the object?
		#map effects to different objects in the game
		effects_map = { "fire": None}
	def draw_score(self):
		self.score.text = ("left: %d right: %d") % (self.score_left, self.score_right)
		self.score.draw()
	def bind_controllers(self, *controllers):
		"""Bind one or more controllers"""
		self.controllers += controllers
	def bind_objects(self, *objects):
		"""Bind one or more objects"""
		self.control.bind_keys(objects)
		self.objects += objects
	def add(self, object):
		"""Add an object to the list of objects that get traveresed when update is called"""
		self.objects += object
	def __iter__(self):
		"""Iterate the particles in the group"""
		# Make a copy of the particle set in case the group is
		# modified during iteration
		return iter(set(self.objects))#used to be particles

	def __len__(self):
		"""Return the number of particles in the group"""
		return len(self.objects)
	def send(self, message):
		#send the message to correct object
		for object in self.objects:
			if object.name == message.to:
				object.move(message.content)
		#Check to see if score has occured
		if message.to == "score":
			print "score message"
			self.update_score(message.content)
	def update_score(self, message):
		if message == "right:score":
			self.score_right += 1
		if message == "left:score":
			self.score_left += 1
		#draw the score
		self.draw_score()
		#reset ball because its gone outside of the screen
		for object in self.objects:
			if object.name =="ball":
				object.reset_ball(self.height/2, self.width/2)
	def update(self, time_delta):
		"""Update all sprites in the system. time_delta is the
		time since the last update (in arbitrary time units).

		This method can be conveniently scheduled using the Pyglet
		scheduler method: pyglet.clock.schedule_interval
		"""
		self.control.update(self, time_delta)
		for object in self.objects:
			object.update(time_delta)
			#object.sprite.last_position = object.sprite.position
			#object.sprite.last_velocity = object.sprite.velocity

		#for group in self:
		for controller in self.controllers:
			controller(time_delta, self)
	def draw(self):
		"""Draw all the sprites in the system using their renderers.

		This method is convenient to call from you Pyglet window's
		on_draw handler to redraw particles when needed.
		"""
		glPushAttrib(GL_ALL_ATTRIB_BITS)
		self.draw_score()
		for sprite in self:
			sprite.draw()
		glPopAttrib()

class Paddle(object):
	"""Draw a rectangle paddle"""
	keys = ()
	def __init__(self, position, color, size, name, screen_height, keys=None):
		if keys != None:
			self.bind_keys(*keys)
		self.name =name
		self.velocity=(0,0,0)
		self.sprite = Sprite(position=position, color=color, size=size)
		self.screen_height = screen_height - self.sprite.size.y
		self.domain = Box((self.sprite.position.x, self.sprite.position.y, self.sprite.position.z),
		(self.sprite.position.x+self.sprite.size.x,self.sprite.position.y+self.sprite.size.y,
		self.sprite.position.z + self.sprite.size.z))
	def install_domain(self, domain):
		"""Manually change the domain that handles collision
		detection to something else. remove for debugging purposes only"""
		self.domain = domain
	def bind_keys(self, *keys):
		"""Bind one or more controllers"""
		if keys != None:
			self.keys += keys
	def return_keys(self):
		return keys
	def move(self, message):
		if message == "right":
			self.sprite.position.x += 10
			self.domain.update_position((self.sprite.position.x, self.sprite.position.y,
				self.sprite.position.z), (self.sprite.position.x+self.sprite.size.x,
					self.sprite.position.y+self.sprite.size.y,self.sprite.position.z
					+ self.sprite.size.z))
		if message == "left":
			self.sprite.position.x -= 10
			self.domain.update_position((self.sprite.position.x, self.sprite.position.y,
				self.sprite.position.z), (self.sprite.position.x+self.sprite.size.x,
					self.sprite.position.y+self.sprite.size.y,self.sprite.position.z
					+ self.sprite.size.z))
		if message == "up":
			y = self.sprite.position.y + 10
			if y < self.screen_height:
				self.sprite.position.y += 10
				self.domain.update_position((self.sprite.position.x, self.sprite.position.y,
					self.sprite.position.z), (self.sprite.position.x+self.sprite.size.x,
						self.sprite.position.y+self.sprite.size.y,self.sprite.position.z
						+ self.sprite.size.z))
		if message == "down":
			y = self.sprite.position.y - 10
			if y > 0:
				self.sprite.position.y -= 10
				self.domain.update_position((self.sprite.position.x, self.sprite.position.y,
					self.sprite.position.z), (self.sprite.position.x+self.sprite.size.x,
						self.sprite.position.y+self.sprite.size.y,self.sprite.position.z
						+ self.sprite.size.z))
	def draw(self):
		z1 = 0.0
		x1 = self.sprite.position.x
		y1 = self.sprite.position.y
		x2 = x1+self.sprite.size.x
		y2 = y1+self.sprite.size.y
		z2 = 0.0
		glBegin(GL_QUADS)
		glColor4fv(self.sprite.color)
		glVertex3f(x1, y1, z1)#Top left
		glVertex3f(x2, y1, z2) #Top right
		glVertex3f(x2, y2, z2) #Bottom right
		glVertex3f(x1, y2, z1)#Bottom left
		glEnd()
	def update(self, td):
		"""Update state of ball"""
		self.sprite.last_position = self.sprite.position
		self.sprite.last_velocity = self.sprite.velocity

class ball(object):
	"""draw a ball using glpoints"""
	def __init__(self, position=(210,100,0), velocity=(60,60,0),color=(0.0,0.0,1.0,1.0),size=(10.0,0.0,0.0)):
		self.sprite = Sprite(position=position, velocity=velocity, color=color, size=size)
		self.name ="ball"
		self.keys=None
		self.particle_group = None
		#We don't care if anything collides with the ball
		self.domain = None
	def move(self, message):
		print message
		if message == "a":
			self.sprite.position.x += 10
	def add_particle_group(self, group):
		"""Bind a particle group to this ball"""
		self.particle_group = group
	def draw(self):
		"""Render the particles as points"""
	#	x =  self.sprite.position.x
	#	y =  self.sprite.position.y
	#	glPointSize( self.sprite.size.x)
	#	glBegin(GL_POINTS)
	#	glColor4fv(self.sprite.color)
	#	glVertex3f(x, y, 0)
	#	glEnd()
	def reset_ball(self, x, y):
		"""reset ball to set location on the screen"""
		self.sprite.position.x = x
		self.sprite.position.y = y
	def update_particle_group(self, td):
		#print "update particle group"
		self.particle_group.template.position = (
			self.sprite.position.x,
			self.sprite.position.y,
			self.sprite.position.z)
	#	comet.template.velocity = (
	#		self.sprite.position.x*0.05 - self.sprite.last_position.x,
	#		self.sprite.position.y*0.05 - self.sprite.last_position.y,
	#		self.sprite.position.z*0.05 - self.sprite.last_position.z)
		default_system.update(td)
	def update(self, td):
		"""Update state of ball"""
		self.sprite.last_position = self.sprite.position
		self.sprite.last_velocity = self.sprite.velocity
		if self.particle_group != None:
			self.update_particle_group(td)

class Movement_Game(object):
	"""Updates the position and velocity of particles"""

	def __init__(self, acceleration=None, damping=None, max_velocity=None):
		"""Initialize the movement controller.

		acceleration -- A three-tuple representing the velocity change
		vector per unit time.

		damping -- A three-tuple velocity multiplier per unit time
		in each respective dimension. A scalar may also be specified
		if the damping is equal in all dimensions (thus .25 is equivilent
		to (.25, .25. .25))

		max_velocity -- Maximum velocity scalar. Particle velocity
		magnitudes are clamped to this value
		"""
		self.acceleration = acceleration
		self.damping = damping
		self.max_velocity = max_velocity

	def __call__(self, td, objects):
		accel = self.acceleration
		if accel is not None:
			accel_x, accel_y, accel_z = accel

		damping = self.damping
		if damping is not None:
			try:
				damp_x, damp_y, damp_z = damping
			except TypeError:
				# Not iterable, assume a scalar value
				damp_x = damp_y = damp_z = damping

		max_vel = self.max_velocity
		if max_vel is not None:
			max_vel_sq = max_vel**2

		for p in objects:
			#Change this to a list of names of objects/To/Move not move?
			"""Perhaps each sprite should have a list of controllers(behaviors) that apply to it? This list
			gets iterated by each controllor to see if this behavior applies to the sprite"""
			if p.name is "ball":
				vel = p.sprite.velocity
				if damping is not None:
					# XXX This is highly inaccurate for td > 1.0
					vel.x += (vel.x * damp_x - vel.x) * td
					vel.y += (vel.y * damp_y - vel.y) * td
					vel.z += (vel.z * damp_z - vel.z) * td
				if accel is not None:
					vel.x += accel_x * td
					vel.y += accel_y * td
					vel.z += accel_z * td
				if max_vel is not None:
					vel_sq = vel.x**2 + vel.y**2 + vel.z**2
					if vel_sq > max_vel_sq:
						vel_mag = math.sqrt(vel_sq)
						adjustment = max_vel / vel_mag
						vel.x *= adjustment
						vel.y *= adjustment
						vel.z *= adjustment
				pos = p.sprite.position
				pos.x += vel.x * td
				pos.y += vel.y * td
				pos.z += vel.z * td

class Bounce(object):
	"""Controller that bounces particles off the surface of a domain

	For best results this controller should be bound after other controllers
	that affect the position and velocity of particles.
	"""

	def __init__(self, domain = None, friction=0, callback=None):
		"""
		domain -- Particles that collide with the surface of this domain are
		redirected as if they bounced or reflected off the surface. This
		alters the position and velocity of the particle. The domain must have
		a non-zero area.

		friction -- The fraction of velocity lost after the bounce. If
		friction is negative, the particle will gain velocity. If friction is
		1, the particle will stop at the point of collision. If friction is
		greater than 1, the particle will appear to refract off of the surface
		rather than reflect.

		callback -- An optional function called when a particle collides
		with the domain. Must have the signature:
			callback(particle, group, controller, collision_point, collision_normal)
		collision_point is point on the domain where the collision occurred.
		collision_normal is the normal vector on the domain's surface at the
		point of collision.
		"""
		self.domain = domain
		self.friction = float(friction)
		self.callback = callback

	def __call__(self, td, objects):
		"""Check for global non object specific collisions"""
		bounce = 1.0 - self.friction
		callback = self.callback
		domains = set()
		if self.domain != None:
			for p1 in objects:
				check_score = self.domain.check_score(p1.sprite.last_position, p1.sprite.position, objects)
				if check_score != "score":
					collide_point, normal = self.domain.intersect(p1.sprite.last_position, p1.sprite.position)
					if collide_point is not None:
						reflect_vec = ( p1.sprite.position - collide_point).reflect(normal) * bounce
						p1.sprite.velocity = p1.sprite.velocity.reflect(normal) * bounce
						p1.sprite.position = reflect_vec + collide_point
					if callback is not None:
						callback(p1, objects, self, collide_point, normal)
		"""check for objects colliding with other objects"""
		for p in objects:
			if p.domain != None:
				domains.add(p.domain)
		for d in domains:
			domain = d
			for p1 in objects:
				collide_point, normal = domain.intersect(p1.sprite.last_position, p1.sprite.position)
				if collide_point is not None:
					reflect_vec = ( p1.sprite.position - collide_point).reflect(normal) * bounce
					p1.sprite.velocity = p1.sprite.velocity.reflect(normal) * bounce
					p1.sprite.position = reflect_vec + collide_point
				if callback is not None:
					callback(p1, objects, self, collide_point, normal)

class BoundryCheck(object):
	"""Boundary is a 4 sided box. Get the four points which make up the box.
	x1/y1---x2/1
	|	 |
	x1/y2---x2/y2
	If interesection occures bettween x1/y1-y2, don't bounce increment scores.
	If  interesection occures bettween x2/y1-y2, don't bounce increment scores.
	else bounce. see bouncy example
	"""
	def __init__(self, domain = None, friction=0, callback=None):
		self.domain = domain

class Domain(object):
	"""Domain abstract base class"""

	def generate(self):
		"""Return a point within the domain as a 3-tuple. For domains with a
		non-zero volume, 'point in domain' is guaranteed to return true.
		"""
		raise NotImplementedError

	def __contains__(self, point):
		"""Return true if point is inside the domain, false if not."""
		raise NotImplementedError

	def intersect(self, start_point, end_point):
		"""For the line segment defined by the start and end point specified
		(coordinate 3-tuples), return the point closest to the start point
		where the line segment intersects surface of the domain, and the
		surface normal unit vector at that point as a 2-tuple.  If the line
		segment does not intersect the domain, return the 2-tuple (None,
		None).

		Only 2 or 3 dimensional domains may be intersected.

		Note performance is more important than absolute accuracy with this
		method, so approximations are acceptable.
		"""
		raise NotImplementedError

class Box(Domain):
	"""Axis aligned rectangular prism"""

	def __init__(self, point1, point2):
		"""point1 and point2 define any two opposite corners of the box"""
		p1 = Vec3(*point1)
		p2 = Vec3(*point2)
		self.point1 = Vec3()
		self.point2 = Vec3()
		self.point1.x = min(p1.x, p2.x)
		self.point1.y = min(p1.y, p2.y)
		self.point1.z = min(p1.z, p2.z)
		self.point2.x = max(p1.x, p2.x)
		self.point2.y = max(p1.y, p2.y)
		self.point2.z = max(p1.z, p2.z)
		self.size_x = self.point2.x - self.point1.x
		self.size_y = self.point2.y - self.point1.y
		self.size_z = self.point2.z - self.point1.z

	def generate(self):
		"""Return a random point inside the box"""
		x, y, z = self.point1
		return (x + self.size_x * random(),
			y + self.size_y * random(),
			z + self.size_z * random())

	def __contains__(self, (px, py, pz)):
		"""Return true if the point is within the box"""
		x1, y1, z1 = self.point1
		x2, y2, z2 = self.point2
		return (x1 <= px <= x2 and y1 <= py <= y2 and z1 <= pz <= z2)

	def update_position(self, point1, point2):
		"""update the position of the box"""
		p1 = Vec3(*point1)
		p2 = Vec3(*point2)
		self.point1 = Vec3()
		self.point2 = Vec3()
		self.point1.x = min(p1.x, p2.x)
		self.point1.y = min(p1.y, p2.y)
		self.point1.z = min(p1.z, p2.z)
		self.point2.x = max(p1.x, p2.x)
		self.point2.y = max(p1.y, p2.y)
		self.point2.z = max(p1.z, p2.z)
		self.size_x = self.point2.x - self.point1.x
		self.size_y = self.point2.y - self.point1.y
		self.size_z = self.point2.z - self.point1.z
	def intersect(self, start_point, end_point):
		"""Intersect the line segment with the box return the first
		intersection point and normal vector pointing into space from
		the box side intersected.

		If the line does not intersect, or lies completely in one side
		of the box return (None, None)
		"""
		sx, sy, sz = start_point
		ex, ey, ez = end_point
		p1x, p1y, p1z = self.point1
		p2x, p2y, p2z = self.point2
		start_inside = start_point in self
		end_inside = end_point in self
		if start_inside != end_inside:
			if (end_inside and sy > p2y) or (start_inside and ey >= p2y) and (ey != sy):
				# Test for itersection with bottom face
				t = (sy - p2y) / (ey - sy)
				ix = (ex - sx) * t + sx
				iy = p2y
				iz = (ez - sz) * t + sz
				if p1x <= ix <= p2x and p1z <= iz <= p2z:
					return (ix, iy, iz), (0.0, (sy > p2y) * 2.0 - 1.0, 0.0)
			if (end_inside and sx < p1x) or (start_inside and ex <= p1x) and (ex != sx):
				# Test for itersection with left face
				t = (sx - p1x) / (ex - sx)
				ix = p1x
				iy = (ey - sy) * t + sy
				iz = (ez - sz) * t + sz
				if p1y <= iy <= p2y and p1z <= iz <= p2z:
					return (ix, iy, iz), ((sx > p1x) * 2.0 - 1.0, 0.0, 0.0)
			if (end_inside and sy < p1y) or (start_inside and ey <= p1y) and (ey != sy):
				# Test for itersection with top face
				t = (sy - p1y) / (ey - sy)
				ix = (ex - sx) * t + sx
				iy = p1y
				iz = (ez - sz) * t + sz
				if p1x <= ix <= p2x and p1z <= iz <= p2z:
					return (ix, iy, iz), (0.0, (sy > p1y) * 2.0 - 1.0, 0.0)
			if (end_inside and sx > p2x) or (start_inside and ex >= p2x) and (ex != sx):
				# Test for itersection with right face
				t = (sx - p2x) / (ex - sx)
				ix = p2x
				iy = (ey - sy) * t + sy
				iz = (ez - sz) * t + sz
				if p1y <= iy <= p2y and p1z <= iz <= p2z:
					return (ix, iy, iz), ((sx > p2x) * 2.0 - 1.0, 0.0, 0.0)
			if (end_inside and sz > p2z) or (start_inside and ez >= p2z) and (ez != sz):
				# Test for itersection with far face
				t = (sz - p2z) / (ez - sz)
				ix = (ex - sx) * t + sx
				iy = (ey - sy) * t + sy
				iz = p2z
				if p1y <= iy <= p2y and p1x <= ix <= p2x:
					return (ix, iy, iz), (0.0, 0.0, (sz > p2z) * 2.0 - 1.0)
			if (end_inside and sz < p1z) or (start_inside and ez <= p1z) and (ez != sz):
				# Test for itersection with near face
				t = (sz - p1z) / (ez - sz)
				ix = (ex - sx) * t + sx
				iy = (ey - sy) * t + sy
				iz = p1z
				if p1y <= iy <= p2y and p1x <= ix <= p2x:
					return (ix, iy, iz), (0.0, 0.0, (sz > p1z) * 2.0 - 1.0)
		return None, None

class Boundary(Box):
	"""The purpose of this domain, is to check when a ball goes
	through either the left or right side of the screen and to send a message
	accordingly."""
	def __init__(self, point1, point2):
		"""point1 and point2 define any two opposite corners of the box"""
		p1 = Vec3(*point1)
		p2 = Vec3(*point2)
		self.point1 = Vec3()
		self.point2 = Vec3()
		self.point1.x = min(p1.x, p2.x)
		self.point1.y = min(p1.y, p2.y)
		self.point1.z = min(p1.z, p2.z)
		self.point2.x = max(p1.x, p2.x)
		self.point2.y = max(p1.y, p2.y)
		self.point2.z = max(p1.z, p2.z)
		self.size_x = self.point2.x - self.point1.x
		self.size_y = self.point2.y - self.point1.y
		self.size_z = self.point2.z - self.point1.z
	def check_score(self, start_point, end_point, gamesystem):
		sx, sy, sz = start_point
		ex, ey, ez = end_point
		p1x, p1y, p1z = self.point1
		p2x, p2y, p2z = self.point2
		start_inside = start_point in self
		end_inside = end_point in self
		if start_inside != end_inside:
			if (end_inside and sx < p1x) or (start_inside and ex <= p1x) and (ex != sx):
				# Test for itersection with left face
				t = (sx - p1x) / (ex - sx)
				ix = p1x
				iy = (ey - sy) * t + sy
				iz = (ez - sz) * t + sz
				if p1y <= iy <= p2y and p1z <= iz <= p2z:
					gamesystem.send(message("score", "game", "right:score"))
					return "score"
			if (end_inside and sx > p2x) or (start_inside and ex >= p2x) and (ex != sx):
				# Test for itersection with right face
				t = (sx - p2x) / (ex - sx)
				ix = p2x
				iy = (ey - sy) * t + sy
				iz = (ez - sz) * t + sz
				if p1y <= iy <= p2y and p1z <= iz <= p2z:
					gamesystem.send(message("score", "game", "left:score"))
					return "score"
		return "no score"

if __name__ == '__main__':
	"""Paddle game."""
	win = pyglet.window.Window(resizable=True, visible=False)
	win.clear()
	paddle = Paddle((10,200,0), (1.0,0.0,0.0,1.0), (10.0,100.0,0.0), "paddle", win.height, keys=("up", "down"))
	ball = ball(position=(210,100,0), velocity=(200,200,0),color=(0.0,0.0,1.0,1.0),size=(10.0,0.0,0.0))
	paddle2 = Paddle((620,200,0), (1.0,0.0,0.0,1.0), (10.0,100.0,0.0), "paddle2", win.height, keys=("w", "s"))

	def resize(widthWindow, heightWindow):
		"""Initial settings for the OpenGL state machine, clear color, window size, etc"""
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

	glEnable(GL_BLEND)
	glShadeModel(GL_SMOOTH)
	glBlendFunc(GL_SRC_ALPHA,GL_ONE)
	glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
	glDisable(GL_DEPTH_TEST)

	comet = StaticEmitter(
		rate=150,
		template=Particle(
			size=(10,10,0),
			color=(1,1,0)
		),
		deviation=Particle(
			position=(0.1,0.1,0),
			velocity=(10,10,0.7),
			up=(0,0,math.pi),
			rotation=(0,0,math.pi),
			color=(0.5, 0.5, 0.5))
	)
	#Add group to ball
	ball.add_particle_group(comet)
	default_system.add_global_controller(
		Lifetime(1.75),
		#Gravity((0,-20,0)),
		Movement(min_velocity=20),
		Fader(max_alpha=0.7, fade_out_start=1, fade_out_end=1.75),
	)

	group_tex = []
	for i in range(4):
		group = ParticleGroup(controllers=[comet], renderer=BillboardRenderer())
		try:
			texture = image.load(os.path.join(os.path.dirname(__file__),
				'flare1.png')).texture#'flare%s.png' % (i+1))).get_mipmapped_texture()
		except NotImplementedError:
			#Problem with mips not being implemented everywhere (cygwin?)
			texture = image.load(os.path.join(os.path.dirname(__file__),
				'flare1.png')).texture
		group_tex.append((group, texture))
	win.resize = resize
	win.set_visible(True)
	win.resize(win.width, win.height)
	ball_size = 15
	screen_box = Boundary((ball_size/2.0, ball_size/2.0, 0),
		(win.width-ball_size/2.0,win.height-ball_size/2.0,0))

	messageHandler = game_system(window=win, objects=[ball, paddle, paddle2],
			controllers=[Movement_Game(max_velocity=200), Bounce(friction=0.0), Bounce(screen_box, friction=0.01)])

	pyglet.clock.schedule_interval(messageHandler.update, (1.0/30.0))

	@win.event
	def on_draw():
		win.clear()
		glLoadIdentity()
		messageHandler.draw()
		for group, texture in group_tex:
			glEnable(GL_BLEND)
			glEnable(texture.target)
			glTexParameteri(texture.target, GL_TEXTURE_WRAP_S, GL_CLAMP)
			glTexParameteri(texture.target, GL_TEXTURE_WRAP_T, GL_CLAMP)
			glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
			glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
			glBindTexture(texture.target, texture.id)
			group.draw()
			glDisable(texture.target)

	pyglet.app.run()


text:
//
//  SQLiteOperator.m
//  MetroDaily
//
//  Created by Algebra Lo on 10年9月13日.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SQLiteOperator.h"

@implementation SQLiteOperator
static SQLiteOperator *operator = nil;

NSString *DB_NAME = @"app_data";
NSString *DB_EXT = @".sqlite";

@synthesize database;

+ (SQLiteOperator *) sharedOperator{
	@synchronized(self) {
		if (operator == nil){
			operator = [[SQLiteOperator alloc] init];
			//[operator openDatabase];
		}
	}
	return operator;
}

+ (id)allocWithZone:(NSZone *)zone {
	@synchronized(self) {
		if (operator == nil) {
			operator = [super allocWithZone:zone];
			return operator;
		}
	}
	return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;
}

//- (void)release {
//    //do nothing
//}

- (id)autorelease {
    return self;
}

- (void) openDatabase{
	NSLog(@"openDatabase");
    if (!database){
		[self copyDatabaseIfNeeded];
		int result = sqlite3_open([[self getDatabaseFullPath] UTF8String], &database);
		if (result != SQLITE_OK){
			NSAssert(0, @"Failed to open database");
		}
	}

    /*
     NSString *sql = @"CREATE TABLE IF NOT EXISTS \"first_time\" (\"id\" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, \"value\" CHAR(256))";
     sqlite3_stmt *statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
     sqlite3_step(statement);

     sql = @"CREATE TABLE IF NOT EXISTS \"push\" (\"id\" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, \"type\" CHAR(256), \"value\" CHAR(256))";
     statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
     sqlite3_step(statement);

     sql = @"CREATE TABLE IF NOT EXISTS \"app_info\" (\"id\" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, \"app_version\" CHAR(256), \"contact_cached_time\" CHAR(256), \"facility_cached_time\" CHAR(256))";
     statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
     sqlite3_step(statement);

     sql = @"CREATE TABLE IF NOT EXISTS \"update_info\" (\"id\" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, \"last_check_xml_full_date\" CHAR(256), \"app_should_update\" CHAR(256),  \"contact_should_update\" CHAR(256), \"facility_should_update\" CHAR(256))";
     statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
     sqlite3_step(statement);
     */
	NSString *sql = @"CREATE TABLE IF NOT EXISTS \"favorite_station\" ( \"line_code\" CHAR, \"station_code\" CHAR, \"station_name_en\" CHAR, \"line_number\" CHAR )";
	sqlite3_stmt *statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
	sqlite3_step(statement);

	sql = @"CREATE TABLE IF NOT EXISTS \"read_tutorial\" ( \"tutorial_name\" CHAR, \"app_version\" CHAR, \"language\" CHAR )";
	statement = [[SQLiteOperator sharedOperator] executeQuery:sql];
	sqlite3_step(statement);

	NSLog(@"openDatabase done");
}

- (void) closeDatabase{
    if (database){
        sqlite3_close(database);
    }
}

- (void) copyDatabaseIfNeeded{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [self getDatabaseFullPath];
    BOOL success = [fileManager fileExistsAtPath:dbPath];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if([defaults valueForKey:@"SQLiteVersion"] && ![[defaults valueForKey:@"SQLiteVersion"] isEqualToString:[self appVersion]]){
        if(success && [fileManager removeItemAtPath:dbPath error:&error]){
            NSLog(@"Delete to delete old version db");

        }else{
            NSLog(@"Failed to delete old version db");
        }
        success = NO;
    }
    if(!success) {

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

        [defaults setObject:[self appVersion] forKey:@"SQLiteVersion"];

        [defaults synchronize];

        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", DB_NAME, DB_EXT]];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
        //        NSLog(@"Database file copied from bundle to %@", dbPath);

        if (!success){
//            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }

    } else {

        //        NSLog(@"Database file found at path %@", dbPath);

    }
}

- (NSString *) appVersion
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
}

- (NSString *) getDatabaseFullPath{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", DB_NAME, DB_EXT]];
	return path;
}

- (sqlite3_stmt *) executeQuery:(NSString *) query{
	sqlite3_stmt *statement;
	int result = sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil);
    if (result != SQLITE_OK)
    {
        DEBUGMSG(@"Execute SQL Error Code: {%i}, Message: {%s}", result, sqlite3_errmsg(database));
    }
	return statement;
}

#pragma mark - favorite_station functions
-(NSArray*)selectALLFromFavoriteStation
{
	NSString *sql =  @"SELECT * FROM favorite_station ORDER BY line_number";
	sqlite3_stmt *statement = [self executeQuery:sql];
	NSMutableArray *result_list = [NSMutableArray new];

    while (sqlite3_step(statement)==SQLITE_ROW) {
        NSMutableDictionary *record = [NSMutableDictionary new];
        int col_num = sqlite3_column_count(statement);
        for(int x = 0; x < col_num; x++){
            if(sqlite3_column_text(statement, x) != nil)
                [record setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, x)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(statement, x)]];
        }
		[result_list addObject:record];
        [record release];
	}

	NSArray *array = [NSArray arrayWithArray:result_list];
    [result_list release];
    return array;
}

-(NSArray*)selectRecordFromFavoriteStationWithLineCode:(NSString*)lineCode stationCode:(NSString*)stationCode
{
	NSString *sql = [NSString stringWithFormat:@"SELECT * FROM favorite_station WHERE line_code = '%@' AND station_code = '%@'", lineCode, stationCode];
	sqlite3_stmt *statement = [self executeQuery:sql];
	NSMutableArray *result_list = [NSMutableArray new];

    while (sqlite3_step(statement)==SQLITE_ROW) {
        NSMutableDictionary *record = [NSMutableDictionary new];
        int col_num = sqlite3_column_count(statement);
        for(int x = 0; x < col_num; x++){
            if(sqlite3_column_text(statement, x) != nil)
                [record setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, x)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(statement, x)]];
        }
		[result_list addObject:record];
        [record release];
	}

	NSArray *array = [NSArray arrayWithArray:result_list];
    [result_list release];
    return array;
}

-(void)insertRecordToFavoriteStationWithLineCode:(NSString*)lineCode stationCode:(NSString*)stationCode stationEnglishName:(NSString*)stationEnglishName lineNumber:(NSString*)lineNumber
{
	NSString *sql = [NSString stringWithFormat:@"INSERT INTO favorite_station (line_code, station_code, station_name_en, line_number) VALUES ('%@', '%@', '%@', '%@')", lineCode, stationCode, stationEnglishName, lineNumber];
	sqlite3_stmt *statement = [self executeQuery:sql];
    sqlite3_step(statement);
}

-(void)deleteRecordFromFavoriteStationWithLineCode:(NSString*)lineCode stationCode:(NSString*)stationCode
{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM favorite_station WHERE line_code = '%@' AND station_code = '%@'", lineCode, stationCode];
	sqlite3_stmt *statement = [self executeQuery:sql];
    sqlite3_step(statement);
}

-(void)updateLineNumber:(NSString*)lineNumber fromFavoriteStationWithLineCode:(NSString*)lineCode stationCode:(NSString*)stationCode
{
    NSString *sql = [NSString stringWithFormat:@"UPDATE favorite_station SET line_number = '%@' WHERE line_code = '%@' AND station_code = '%@'", lineNumber, lineCode, stationCode];
	sqlite3_stmt *statement = [self executeQuery:sql];
    sqlite3_step(statement);
}

-(double)selectMaxLineNumberFromFavoriteStation
{
    NSString *sql = @"SELECT MAX(line_number) FROM favorite_station";
	sqlite3_stmt *statement = [self executeQuery:sql];

    if (sqlite3_step(statement)==SQLITE_ROW) {

        //int col_num = sqlite3_column_count(statement);

        if(sqlite3_column_text(statement, 0) != nil)
        {
            NSString *countString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

            if (countString != nil)
            {
                return [countString doubleValue];
            }
        }
    }

    return 0.0;
}

#pragma mark - read_tutorial functions
-(BOOL)hasRecordInReadTutorialWithName:(NSString*)name appVersion:(NSString*)appVersion
{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM read_tutorial WHERE tutorial_name = '%@' AND app_version = '%@'", name, appVersion];
	sqlite3_stmt *statement = [self executeQuery:sql];

    if (sqlite3_step(statement)==SQLITE_ROW) {

        //int col_num = sqlite3_column_count(statement);

        if(sqlite3_column_text(statement, 0) != nil)
        {
            NSString *countString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

            if (countString != nil && [countString intValue] > 0)
            {
                return YES;
            }
        }
    }

    return NO;
}

-(void)insertRecordToReadTutorialWithName:(NSString*)name appVersion:(NSString*)appVersion language:(NSString*)language
{

    //sql = @"CREATE TABLE IF NOT EXISTS \"read_tutorial\" ( \"tutorial_name\" CHAR, \"app_version\" CHAR, \"language\" CHAR )";

	NSString *sql = [NSString stringWithFormat:@"INSERT INTO read_tutorial (tutorial_name, app_version, language) VALUES ('%@', '%@', '%@')", name, appVersion, language];
	sqlite3_stmt *statement = [self executeQuery:sql];
    sqlite3_step(statement);
}

@end


text: void test_modifiers();


text:
from etherscan.accounts import Account
import json

with open('../../api_key.json', mode='r') as key_file:
    key = json.loads(key_file.read())['key']

address = '0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a'

api = Account(address=address, api_key=key)
transactions = api.get_transaction_page(page=1, offset=10000, sort='des')
print(transactions)


text:
var gulp = require("gulp"),
  sass = require("gulp-sass"),
  uglify = require("gulp-uglify"),
  util = require("gulp-util"),
  concat = require("gulp-concat");

gulp.task("build-css", function() {
  return gulp.src("resources/scss/main.scss").
    pipe(sass()).
    pipe(concat("all.css")).
    pipe(gulp.dest("css"));
});

gulp.task("build-js", function() {
  return gulp.src([
    "bower_components/jquery/dist/jquery.js",
    "bower_components/materialize/dist/js/materialize.js",
    "resources/javascript/**/*.js"
  ]).pipe(concat("all.js")).
    pipe(util.env.type === "production" ? uglify() : util.noop()).
    pipe(gulp.dest("js"));
});

gulp.task("watch", function() {
  gulp.watch("resources/scss/**/*.scss", ["build-css"]);
  gulp.watch("resources/javascript/**/*.js", ["build-js"]);
});

gulp.task("deploy", ["build-css", "build-js"]);


text:
[![Dependency Status](https://david-dm.org/etpinard/etpinard.github.io.svg?style=flat-square)](https://david-dm.org/etpinard/etpinard.github.io)
[![devDependency Status](https://david-dm.org/etpinard/etpinard.github.io/dev-status.svg?style=flat-square)](https://david-dm.org/etpinard/etpinard.github.io?type=dev)

Personal web page.

### Deployment

Commit code to `source` branch, which is now the default branch on GitHub.

The `master` branch contains the built assets served on GitHub pages.

### Trick to shrink GIFs

```
sudo apt install gifsicle

# e.g
gifsicle old.gif "#0-70" -O3 --scale 0.5 --optimize --colors 16 -o new.gif

# 0-70 is the frame range
# find out how many frames there are in your gif using ImageMagick
identify old.gif
```

---

This site is hosted on GitHub Pages and built with yo-yo / tachyons / Hero Patterns.

2021 Étienne Tétreault-Pinard. MIT License

[![Standard - JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)


text:
.. Succinct Web Framework documentation master file, created by
   sphinx-quickstart on Fri Feb 18 15:00:56 2022.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Succinct Web Framework's documentation!
==================================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   usage/overview
   usage/quickstart
   usage/detailed

Indices and tables
==================

* :ref:`genindex`

..
    * :ref:`modindex`

* :ref:`search`


text:
Released July 5, 2020 ([2.0.0](https://github.com/jonahoffline/autoexpreso-cli/tree/v2.0.0)).

* Replace Old AutoExpreso (scraped) API with newly REST endpoints.
* Replace `mechanize` dependency for `faraday` and `typhoeus`.
* Replace `awesome_print` dependency to `awesome_print`.
* Add Typhoeus caching.
* Update gemspec to require Ruby version >= 2.4

### 1.0.2
Released August 5, 2017 ([1.0.2](https://github.com/jonahoffline/autoexpreso-cli/tree/v1.0.2)).

* Update all gemspec dependencies.
* Add `required_ruby_version` >= `2.2.2`.
* Cleanup travis: ruby versions.
* Add Hakiri (security) badge.
* Bump release version to 1.0.2.

### 1.0.1
Released November 28, 2014 ([1.0.1](https://github.com/jonahoffline/autoexpreso-cli/tree/v1.0.1)).

* Move repo from [riveralabs](https://github.com/jonahoffline/autoexpreso-cli) to [jonahoffline](https://github.com/jonahoffline/autoexpreso-cli)
* Update README, Changelog links to reflect repo change.
* Update `homepage` in gemspec to new repo home.
* Update `spec` from 2.14.0 to 3.1.0.
* Fix RSpec deprecation warning.
* Bump release version.

### 1.0.0
Released November 27, 2014 ([1.0.0](https://github.com/jonahoffline/autoexpreso-cli/tree/v1.0.0)).

* Fix issue preventing data from being returned.
* Add #account_details method to delegate printing (Hash or JSON).
* Add -j, --json flags for printing account details in json from CLI.
* Add welcome header to CLI.
* Update README with new flag documentation and example.
* Add wercker.yml for testing.
* Update .ruby-version from 2.0.0-p247 to 2.1.4
* Bump release version.

### 0.0.4
Released November 4, 2013 ([0.0.4](https://github.com/jonahoffline/autoexpreso-cli/tree/v0.0.4)).

* Update gemspec's dependency of awesome_print to 1.2.0

### 0.0.3
Released September 11, 2013 ([0.0.3](https://github.com/jonahoffline/autoexpreso-cli/tree/v0.0.3)).

* Fix typo in AutoExpreso::CLI's banner option.
* Add Gemnasium dependency status badge to README.

## 0.0.2

Released Aug 9, 2013 ([0.0.2](https://github.com/jonahoffline/autoexpreso-cli/tree/v0.0.2)).

* Fix issue with command-line application not showing help when called without arguments.
* Update documentation in README.
* Add Changelog.
* Bump release version.
* Update gemspec's author email, homepage, description and summary.
* Add BadgeFury and CodeClimate badges to README.
* Update Travis-CI badge in README.

## 0.0.1

Released Aug 8, 2013 ([0.0.1](https://github.com/jonahoffline/autoexpreso-cli/tree/v0.0.1)).

* Initial Release.


text:
import datetime
import json
from json.decoder import JSONDecodeError

from cumulusci.core.config import OrgConfig
from cumulusci.core.exceptions import SfdxOrgException
from cumulusci.core.sfdx import sfdx
from cumulusci.utils import get_git_config

nl = "\n"  # fstrings can't contain backslashes

class SfdxOrgConfig(OrgConfig):
    """Org config which loads from sfdx keychain"""

    @property
    def sfdx_info(self):
        if hasattr(self, "_sfdx_info"):
            return self._sfdx_info

        # On-demand creation of scratch orgs
        if self.create_org is not None and not self.created:
            self.create_org()

        username = self.config.get("username")
        assert username is not None, "SfdxOrgConfig must have a username"

        self.logger.info(f"Getting org info from Salesforce CLI for {username}")

        # Call force:org:display and parse output to get instance_url and
        # access_token
        p = sfdx("force:org:display --json", self.username)

        org_info = None
        stderr_list = [line.strip() for line in p.stderr_text]
        stdout_list = [line.strip() for line in p.stdout_text]

        if p.returncode:
            self.logger.error(f"Return code: {p.returncode}")
            for line in stderr_list:
                self.logger.error(line)
            for line in stdout_list:
                self.logger.error(line)
            message = f"\nstderr:\n{nl.join(stderr_list)}"
            message += f"\nstdout:\n{nl.join(stdout_list)}"
            raise SfdxOrgException(message)

        else:
            try:
                org_info = json.loads("".join(stdout_list))
            except Exception as e:
                raise SfdxOrgException(
                    "Failed to parse json from output.\n  "
                    f"Exception: {e.__class__.__name__}\n  Output: {''.join(stdout_list)}"
                )
            org_id = org_info["result"]["accessToken"].split("!")[0]

        sfdx_info = {
            "instance_url": org_info["result"]["instanceUrl"],
            "access_token": org_info["result"]["accessToken"],
            "org_id": org_id,
            "username": org_info["result"]["username"],
        }
        if org_info["result"].get("password"):
            sfdx_info["password"] = org_info["result"]["password"]
        self._sfdx_info = sfdx_info
        self._sfdx_info_date = datetime.datetime.utcnow()
        self.config.update(sfdx_info)

        sfdx_info.update(
            {
                "created_date": org_info["result"].get("createdDate"),
                "expiration_date": org_info["result"].get("expirationDate"),
            }
        )
        return sfdx_info

    @property
    def access_token(self):
        return self.sfdx_info["access_token"]

    @property
    def instance_url(self):
        return self.config.get("instance_url") or self.sfdx_info["instance_url"]

    @property
    def org_id(self):
        org_id = self.config.get("org_id")
        if not org_id:
            org_id = self.sfdx_info["org_id"]
        return org_id

    @property
    def user_id(self):
        if not self.config.get("user_id"):
            result = self.salesforce_client.query_all(
                f"SELECT Id FROM User WHERE UserName='{self.username}'"
            )
            self.config["user_id"] = result["records"][0]["Id"]
        return self.config["user_id"]

    @property
    def username(self):
        username = self.config.get("username")
        if not username:
            username = self.sfdx_info["username"]
        return username

    @property
    def password(self):
        password = self.config.get("password")
        if not password:
            password = self.sfdx_info["password"]
        return password

    @property
    def email_address(self):
        email_address = self.config.get("email_address")
        if not email_address:
            email_address = get_git_config("user.email")
            self.config["email_address"] = email_address

        return email_address

    def get_access_token(self, **userfields):
        """Get the access token for a specific user

        If no keyword arguments are passed in, this will return the
        access token for the default user. If userfields has the key
        "username", the access token for that user will be returned.
        Otherwise, a SOQL query will be made based off of the
        passed-in fields to find the username, and the token for that
        username will be returned.

        Examples:

        | # default user access token:
        | token = org.get_access_token()

        | # access token for 'test@example.com'
        | token = org.get_access_token(username='test@example.com')

        | # access token for user based on lookup fields
        | token = org.get_access_token(alias='dadvisor')

        """
        if not userfields:
            # No lookup fields specified? Return the token for the default user
            return self.access_token

        # if we have a username, use it. Otherwise we need to do a
        # lookup using the passed-in fields.
        username = userfields.get("username", None)
        if username is None:
            where = [f"{key} = '{value}'" for key, value in userfields.items()]
            query = f"SELECT Username FROM User WHERE {' AND '.join(where)}"
            result = self.salesforce_client.query_all(query).get("records", [])
            if len(result) == 0:
                raise SfdxOrgException(
                    "Couldn't find a username for the specified user."
                )
            elif len(result) > 1:
                raise SfdxOrgException(
                    "More than one user matched the search critiera."
                )
            else:
                username = result[0]["Username"]

        p = sfdx(f"force:org:display --targetusername={username} --json")
        if p.returncode:
            output = p.stdout_text.read()
            try:
                info = json.loads(output)
                explanation = info["message"]
            except (JSONDecodeError, KeyError):
                explanation = output

            raise SfdxOrgException(
                f"Unable to find access token for {username}\n{explanation}"
            )
        else:
            info = json.loads(p.stdout_text.read())
            return info["result"]["accessToken"]

    def force_refresh_oauth_token(self):
        # Call force:org:display and parse output to get instance_url and
        # access_token
        p = sfdx("force:org:open -r", self.username, log_note="Refreshing OAuth token")

        stdout_list = [line.strip() for line in p.stdout_text]

        if p.returncode:
            self.logger.error(f"Return code: {p.returncode}")
            for line in stdout_list:
                self.logger.error(line)
            message = f"Message: {nl.join(stdout_list)}"
            raise SfdxOrgException(message)

    def refresh_oauth_token(self, keychain):
        """ Use sfdx force:org:describe to refresh token instead of built in OAuth handling """
        if hasattr(self, "_sfdx_info"):
            # Cache the sfdx_info for 1 hour to avoid unnecessary calls out to sfdx CLI
            delta = datetime.datetime.utcnow() - self._sfdx_info_date
            if delta.total_seconds() > 3600:
                del self._sfdx_info

                # Force a token refresh
                self.force_refresh_oauth_token()

        # Get org info via sfdx force:org:display
        self.sfdx_info
        # Get additional org info by querying API
        self._load_orginfo()


text:
package playn.sample.hello.core.component;

import com.artemis.Component;

import java.io.Serializable;

/**
 * @author Daan van Yperen
 */
public class Angle extends Component implements Serializable {
    public static final int ORIGIN_AUTO = Integer.MIN_VALUE;
    public static final Angle NONE = new Angle();

    /** Rotation of animation. Rotates nothing else! We're cheap. */
    public float rotation = 0;

    /** Rotational X origin */
    public int ox = ORIGIN_AUTO; // rotational origin X
    /**  Rotational Y origin */
    public int oy = ORIGIN_AUTO; // rotational origin Y

    public Angle(float rotation) {
        this.rotation = rotation;
    }

    public Angle(float rotation, int ox, int oy) {
        this.rotation = rotation;
        this.ox = ox;
        this.oy = oy;
    }

    public Angle() {
    }
}


text:
package org.drools.workbench.screens.testscenario.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import org.drools.workbench.models.testscenarios.shared.ExecutionTrace;
import org.drools.workbench.models.testscenarios.shared.Fixture;
import org.drools.workbench.models.testscenarios.shared.Scenario;
import org.drools.workbench.screens.testscenario.client.resources.i18n.TestScenarioConstants;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracle;
import org.uberfire.ext.widgets.common.client.common.ImageButton;
import org.uberfire.ext.widgets.common.client.common.popups.FormStylePopup;

abstract class TestScenarioButton extends ImageButton {

    protected final Scenario scenario;
    protected final ScenarioParentWidget parent;
    protected final AsyncPackageDataModelOracle oracle;
    protected final ExecutionTrace previousEx;

    public TestScenarioButton( final Image img,
                               final String tooltip,
                               final ExecutionTrace previousEx,
                               final Scenario scenario,
                               final ScenarioParentWidget scenarioWidget,
                               final AsyncPackageDataModelOracle oracle ) {
        super( img,
               tooltip );
        this.previousEx = previousEx;
        this.scenario = scenario;
        this.parent = scenarioWidget;
        this.oracle = oracle;

        addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent event ) {
                final FormStylePopup pop = getPopUp();
                pop.show();
            }
        } );
    }

    protected abstract TestScenarioButtonPopup getPopUp();

    protected abstract class TestScenarioButtonPopup extends FormStylePopup {

        public TestScenarioButtonPopup( final Image image,
                                        final String text ) {
            super( image,
                   text );
        }

        protected abstract class BasePanel<T extends Widget> extends HorizontalPanel {

            protected final T valueWidget;
            protected final Button add = new Button( TestScenarioConstants.INSTANCE.Add() );

            public BasePanel() {
                valueWidget = getWidget();

                addAddButtonClickHandler();

                initWidgets();
            }

            protected void initWidgets() {
                add( valueWidget );
                add( add );
            }

            protected void addAddButtonClickHandler() {
                add.addClickHandler( new ClickHandler() {

                    public void onClick( ClickEvent event ) {
                        scenario.insertBetween( previousEx,
                                                getFixture() );
                        parent.renderEditor();
                        hide();
                    }
                } );
            }

            public abstract T getWidget();

            public abstract Fixture getFixture();

        }

        protected abstract class ListBoxBasePanel extends BasePanel<ListBox> {

            public ListBoxBasePanel( final List<String> listItems ) {
                super();
                fillWidget( listItems );
            }

            public ListBoxBasePanel( final String[] listItems ) {
                super();
                List<String> list = new ArrayList<String>();
                for ( String string : listItems ) {
                    list.add( string );
                }
                fillWidget( list );
            }

            protected void fillWidget( final List<String> listItems ) {
                for ( String item : listItems ) {
                    valueWidget.addItem( item );
                }
            }

            @Override
            public ListBox getWidget() {
                return new ListBox();
            }
        }
    }
}


text:
module Spree
  module Admin
    class ZonesController < ResourceController
      before_filter :load_data, :except => [:index]

      def new
        @zone.zone_members.build
        respond_with(@zone)
      end

      protected

        def collection
          params[:q] ||= {}
          params[:q][:s] ||= "ascend_by_name"
          @search = super.ransack(params[:q])
          @zones = @search.result.page(params[:page]).per(Spree::Config[:orders_per_page])
        end

        def load_data
          @countries = Country.order(:name)
          @states = State.order(:name)
          @zones = Zone.order(:name)
        end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

	<item value="0" key="org.eclipse.egit.ui.internal.clone.GitSelectWizardPageWizardSel"/>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/usr/local/google/buildbot/src/googleplex-android/mnc-supportlib-release/frameworks/support/v7/mediarouter/res/values-hr/strings.xml -->
    <eat-comment/>
    <string msgid="4324764887951330391" name="mr_button_content_description">"Emitiranje"</string>
    <string msgid="6349900579507521956" name="mr_chooser_searching">"Traženje uređaja"</string>
    <string msgid="414301941546135990" name="mr_chooser_title">"Emitiranje na"</string>
    <string msgid="4868457957151124867" name="mr_controller_casting_screen">"Emitiranje zaslona"</string>
    <string msgid="7333862312480583260" name="mr_controller_close_description">"Zatvaranje"</string>
    <string msgid="7924809056904240926" name="mr_controller_collapse_group">"Sažimanje"</string>
    <string msgid="1227264889412989580" name="mr_controller_disconnect">"Prekini vezu"</string>
    <string msgid="8062427022744266907" name="mr_controller_expand_group">"Proširivanje"</string>
    <string msgid="5585418471741142924" name="mr_controller_no_info_available">"Informacije nisu dostupne"</string>
    <string msgid="6547130360349182381" name="mr_controller_no_media_selected">"Nije odabran nijedan medij"</string>
    <string msgid="5451884435510905406" name="mr_controller_pause">"Pauziranje"</string>
    <string msgid="683634565969987458" name="mr_controller_play">"Reprodukcija"</string>
    <string msgid="4570331844078181931" name="mr_controller_stop">"Zaustavi emitiranje"</string>
    <string msgid="5441529851481176817" name="mr_system_route_name">"Sustav"</string>
    <string msgid="7498112907524977311" name="mr_user_route_category_name">"Uređaji"</string>
</resources>


text:
@implementation TYMVideoDescriptor

@end


text:
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

module React.Flux.Mui.Card.CardMedia where

import Protolude

import Data.Aeson
import Data.Aeson.Casing
import Data.String (String)
import React.Flux
import React.Flux.Mui.Util

data CardMedia = CardMedia
  { cardMediaActAsExpander :: !(Maybe Bool)
  , cardMediaExpandable :: !(Maybe Bool)
  } deriving (Generic, Show)

instance ToJSON CardMedia where
  toJSON = genericToJSON $ aesonDrop (length ("CardMedia" :: String)) camelCase

defCardMedia :: CardMedia
defCardMedia =
  CardMedia {cardMediaActAsExpander = Nothing, cardMediaExpandable = Nothing}

cardMedia_ ::
     CardMedia
  -> [PropertyOrHandler handler]
  -> ReactElementM handler ()
  -> ReactElementM handler ()
cardMedia_ args props =
  foreign_ "CardMedia" (fromMaybe [] (toProps args) ++ props)


text:
package android.support.v4.app;

import android.os.Bundle;

// Referenced classes of package android.support.v4.app:
//            ActivityOptionsCompat, ActivityOptionsCompat21

private static class mImpl extends ActivityOptionsCompat
{

    private final ActivityOptionsCompat21 mImpl;

    public Bundle toBundle()
    {
        return mImpl.toBundle();
    }

    public void update(ActivityOptionsCompat activityoptionscompat)
    {
        if (activityoptionscompat instanceof mImpl)
        {
            activityoptionscompat = (mImpl)activityoptionscompat;
            mImpl.update(((mImpl) (activityoptionscompat)).mImpl);
        }
    }

    (ActivityOptionsCompat21 activityoptionscompat21)
    {
        mImpl = activityoptionscompat21;
    }
}


text:
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LeapDayTinkering.RaspberryPi;
using Microsoft.Rest;

namespace LeapDayTinkering.RaspberryPi
{
    public static partial class DeviceExtensions
    {
        /// <param name='operations'>
        /// Reference to the LeapDayTinkering.RaspberryPi.IDevice.
        /// </param>
        /// <param name='deviceId'>
        /// Required.
        /// </param>
        public static bool Post(this IDevice operations, string deviceId)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IDevice)s).PostAsync(deviceId);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <param name='operations'>
        /// Reference to the LeapDayTinkering.RaspberryPi.IDevice.
        /// </param>
        /// <param name='deviceId'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public static async Task<bool> PostAsync(this IDevice operations, string deviceId, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Microsoft.Rest.HttpOperationResponse<bool> result = await operations.PostWithOperationResponseAsync(deviceId, cancellationToken).ConfigureAwait(false);
            return result.Body;
        }
    }
}


text:
/*
 * \file    gpio_v2.h
 *
 * \brief   This file contains the prototypes of the APIs present in the
 *          device abstraction layer file of GPIO belonging to AM335X SoC.
 *          This also contains some related macros.
 */

/*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
*/
/*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*    Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the
*    distribution.
*
*    Neither the name of Texas Instruments Incorporated nor the names of
*    its contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

#ifndef  _GPIO_V2_H_
#define  _GPIO_V2_H_

#include "hw_gpio_v2.h"

#ifdef __cplusplus
extern "C" {
#endif

/*****************************************************************************
**                       MACRO DEFINITIONS
*****************************************************************************/

/* Values used to configure the direction of GPIO pins. */
#define GPIO_DIR_INPUT                   (GPIO_OE_OUTPUTEN_DISABLED)
#define GPIO_DIR_OUTPUT                  (GPIO_OE_OUTPUTEN_ENABLED)

/* Values helping to decide the value on a GPIO pin. */
#define GPIO_PIN_LOW                     (0x0)
#define GPIO_PIN_HIGH                    (0x1)

/* Values denoting the Interrupt Line number to be used. */
#define GPIO_INT_LINE_1                  (0x0)
#define GPIO_INT_LINE_2                  (0x1)

/*
** Values used to enable/disable interrupt generation due to level
** detection on an input GPIO pin.
*/
#define GPIO_INT_TYPE_NO_LEVEL           (0x01)
#define GPIO_INT_TYPE_LEVEL_0            (0x04)
#define GPIO_INT_TYPE_LEVEL_1            (0x08)
#define GPIO_INT_TYPE_BOTH_LEVEL         (0x0C)

/*
** Values used to enable/disable interrupt generation due to edge
** detection on an input GPIO pin.
*/
#define GPIO_INT_TYPE_NO_EDGE            (0x80)
#define GPIO_INT_TYPE_RISE_EDGE          (0x10)
#define GPIO_INT_TYPE_FALL_EDGE          (0x20)
#define GPIO_INT_TYPE_BOTH_EDGE          (0x30)

/* Values used for Idle Mode configurations. */
#define GPIO_IDLE_MODE_FORCE_IDLE        (GPIO_SYSCONFIG_IDLEMODE_FORCEIDLE << \
                                          GPIO_SYSCONFIG_IDLEMODE_SHIFT)
#define GPIO_IDLE_MODE_NO_IDLE           (GPIO_SYSCONFIG_IDLEMODE_NOIDLE << \
                                          GPIO_SYSCONFIG_IDLEMODE_SHIFT)
#define GPIO_IDLE_MODE_SMART_IDLE        (GPIO_SYSCONFIG_IDLEMODE_SMARTIDLE << \
                                          GPIO_SYSCONFIG_IDLEMODE_SHIFT)
#define GPIO_IDLE_MODE_SMART_IDLE_WAKEUP (GPIO_SYSCONFIG_IDLEMODE_SMARTIDLEWAKEUP << \
                                          GPIO_SYSCONFIG_IDLEMODE_SHIFT)

/* Values used to enable/disable Auto-Idle mode. */
#define GPIO_AUTO_IDLE_MODE_ENABLE       (GPIO_SYSCONFIG_AUTOIDLE_AUTOMATIC)
#define GPIO_AUTO_IDLE_MODE_DISABLE      (GPIO_SYSCONFIG_AUTOIDLE_FREERUN)

/* Values used to configure the Gating Ratio. */
#define GPIO_GR_FUNC_CLK_INTER_CLK_BY_1  (GPIO_CTRL_GATINGRATIO_N_1 << \
                                          GPIO_CTRL_GATINGRATIO_SHIFT)
#define GPIO_GR_FUNC_CLK_INTER_CLK_BY_2  (GPIO_CTRL_GATINGRATIO_N_2 << \
                                          GPIO_CTRL_GATINGRATIO_SHIFT)
#define GPIO_GR_FUNC_CLK_INTER_CLK_BY_4  (GPIO_CTRL_GATINGRATIO_N_4 << \
                                          GPIO_CTRL_GATINGRATIO_SHIFT)
#define GPIO_GR_FUNC_CLK_INTER_CLK_BY_8  (GPIO_CTRL_GATINGRATIO_N_8 << \
                                          GPIO_CTRL_GATINGRATIO_SHIFT)

/* Values used to enable/disable Debouncing feature for an input pin. */
#define GPIO_DEBOUNCE_FUNC_ENABLE        (GPIO_DEBOUNCENABLE_DEBOUNCEENABLE_DEBOUNCE)
#define GPIO_DEBOUNCE_FUNC_DISABLE       (GPIO_DEBOUNCENABLE_DEBOUNCEENABLE_NODEBOUNCE)

/*
** Structure to store the GPIO context
*/
typedef struct gpioContext{
    unsigned int ctrl;
    unsigned int dir;
}GPIOCONTEXT;

/*****************************************************************************
**                       FUNCTION PROTOTYPES
*****************************************************************************/

extern void GPIOModuleReset(unsigned int baseAdd);
extern void GPIOModuleEnable(unsigned int baseAdd);
extern void GPIOModuleDisable(unsigned int baseAdd);
extern void GPIODirModeSet(unsigned int baseAdd,
                           unsigned int pinNumber,
                           unsigned int pinDirection);
extern unsigned int GPIODirModeGet(unsigned int baseAdd,
                                   unsigned int pinNumber);
extern void GPIOPinWrite(unsigned int baseAdd,
                         unsigned int pinNumber,
                         unsigned int pinValue);
extern unsigned int GPIOPinRead(unsigned int baseAdd,
                                unsigned int pinNumber);
extern void GPIOMultiplePinsWrite(unsigned int baseAdd,
                                  unsigned int setMask,
                                  unsigned int clrMask);
extern unsigned int GPIOMultiplePinsRead(unsigned int baseAdd,
                                         unsigned int readMask);
extern void GPIOPinIntEnable(unsigned int baseAdd,
                             unsigned int intLine,
                             unsigned int pinNumber);

extern void GPIOPinIntDisable(unsigned int baseAdd,
                              unsigned int intLine,
                              unsigned int pinNumber);
extern void GPIOIntTypeSet(unsigned int baseAdd,
                           unsigned int pinNumber,
                           unsigned int eventType);
extern unsigned int GPIOIntTypeGet(unsigned int baseAdd,
                                   unsigned int pinNumber);
extern unsigned int GPIOPinIntStatus(unsigned int baseAdd,
                                     unsigned int intLine,
                                     unsigned int pinNumber);
extern void GPIOPinIntClear(unsigned int baseAdd,
                            unsigned int intLine,
                            unsigned int pinNumber);
extern unsigned int GPIORawIntStatus(unsigned int baseAdd,
                                     unsigned int intLine,
                                     unsigned int readMask);
extern void GPIOTriggerPinInt(unsigned int baseAdd,
                              unsigned int intLine,
                              unsigned int pinNumber);
extern void GPIOAutoIdleModeControl(unsigned int baseAdd,
                                    unsigned int modeFlag);
extern void GPIOIdleModeConfigure(unsigned int baseAdd,
                                  unsigned int modeFlag);
extern void GPIOGatingRatioConfigure(unsigned int baseAdd,
                                     unsigned int configFlag);

extern void GPIODebounceFuncControl(unsigned int baseAdd,
                                    unsigned int pinNumber,
                                    unsigned int controlFlag);
extern void GPIODebounceTimeConfig(unsigned int baseAdd,
                                   unsigned int debounceTime);
extern void GPIOEndOfInterruptEnable(unsigned int baseAdd,
                                     unsigned int intLine);
extern unsigned int GPIORevisionInfoGet(unsigned int baseAdd);
extern void gpioContextSave(unsigned int baseAdd, GPIOCONTEXT *contextPtr);
extern void gpioContextRestore(unsigned int baseAdd, GPIOCONTEXT *contextPtr);

#ifdef __cplusplus
}
#endif

#endif

/********************************* End Of File ******************************/


text:
#ifndef avro_BufferDetailIterator_hh__
#define avro_BufferDetailIterator_hh__

#include "BufferDetail.hh"

/**
 * \file BufferDetailIterator.hh
 *
 * \brief The implementation details for the Buffer iterators.
 **/

namespace avro {

namespace detail {

/**
 * \brief Implements conversion from a chunk to asio::const_buffer
 *
 * Iterators for an InputBuffer will iterate over the avro of chunks, so
 * internally they contain an iterator.  But the iterator needs to be
 * convertable to an asio buffer for use in boost::asio functions.  This class
 * wraps the iterator with a cast operator to do this conversion.
 **/

struct InputIteratorHelper
{
    /// Construct a helper with an unnassigned iterator.
    InputIteratorHelper() :
        iter_()
    {}

    /// Construct a helper with an iterator.
    InputIteratorHelper(const BufferImpl::ChunkList::const_iterator &iter) :
        iter_(iter)
    {}

    /// The location of valid data in this chunk.
    const data_type *data() const {
        return iter_->tellReadPos();
    }

    /// The size of valid data in this chunk.
    size_type size() const {
        return iter_->dataSize();
    }

    /// Conversion operator.   It doesn't check for null, because the only
    /// the only time the chunk should be null is when it's the iterator
    /// end(), which should never be dereferenced anyway.
#ifdef HAVE_BOOST_ASIO
    operator ConstAsioBuffer() const {
        return ConstAsioBuffer(data(), size());
    }
#endif

    BufferImpl::ChunkList::const_iterator iter_; ///< the current iterator
};

/**
 * \brief Implements conversion from a chunk to asio::buffer
 *
 * Iterators for an OutputBuffer will iterate over the avro of chunks, so
 * internally they contain an iterator.  But the iterator needs to be
 * convertable to an asio buffer for use in boost::asio functions.  This class
 * wraps the iterator with a cast operator to do this conversion.
 */

struct OutputIteratorHelper
{
    /// Construct a helper with an unnassigned iterator.
    OutputIteratorHelper() :
            iter_()
    {}

    /// Construct a helper with an iterator.
    OutputIteratorHelper(const BufferImpl::ChunkList::const_iterator &iter) :
            iter_(iter)
    {}

    /// The location of the first writable byte in this chunk.
    data_type *data() const {
        return iter_->tellWritePos();
    }

    /// The size of area that can be written in this chunk.
    size_type size() const {
        return iter_->freeSize();
    }

    /// Conversion operator.   It doesn't check for null, because the only
    /// the only time the chunk should be null is when it's the iterator
    /// end(), which should never be dereferenced anyway.
#ifdef HAVE_BOOST_ASIO
    operator MutableAsioBuffer() const {
        return MutableAsioBuffer(data(), size());
    }
#endif

    BufferImpl::ChunkList::const_iterator iter_; ///< the current iterator
};

/**
 * \brief Implements the iterator for Buffer, that iterates through the
 * buffer's chunks.
 **/

template<typename Helper>
class BufferIterator
{

  public:

    typedef BufferIterator<Helper> this_type;

    /**
     * @name Typedefs
     *
     * STL iterators define the following declarations.  According to
     * boost::asio documentation, the library expects the iterator to be
     * bidirectional, however this implements only the forward iterator type.
     * So far this has not created any problems with asio, but may change if
     * future versions of the asio require it.
     **/

    //@{
    typedef std::forward_iterator_tag iterator_category; // this is a lie to appease asio
    typedef Helper value_type;
    typedef std::ptrdiff_t difference_type;
    typedef value_type* pointer;
    typedef value_type& reference;
    //@}

    /// Construct an unitialized iterator.
    BufferIterator() :
        helper_()
    { }

    /* The default implementations are good here
    /// Copy constructor.
    BufferIterator(const BufferIterator &src) :
        helper_(src.helper_)
    { }
    /// Assignment.
    this_type& operator= (const this_type &rhs) {
        helper_ = rhs.helper_;
        return *this;
    }
    */

    /// Construct iterator at the position in the buffer's chunk list.
    explicit BufferIterator(BufferImpl::ChunkList::const_iterator iter) :
        helper_(iter)
    { }

    /// Dereference iterator, returns InputIteratorHelper or OutputIteratorHelper wrapper.
    reference operator *() {
        return helper_;
    }

    /// Dereference iterator, returns const InputIteratorHelper or OutputIteratorHelper wrapper.
    const value_type &operator *() const {
        return helper_;
    }

    /// Dereference iterator, returns InputIteratorHelper or OutputIteratorHelper wrapper.
    pointer operator->() {
        return &helper_;
    }

    /// Dereference iterator, returns const InputIteratorHelper or OutputIteratorHelper wrapper.
    const value_type *operator->() const {
        return &helper_;
    }

    /// Increment to next chunk in list, or to end() iterator.
    this_type& operator++()
    {
        ++helper_.iter_;
        return *this;
    }

    /// Increment to next chunk in list, or to end() iterator.
    this_type operator++(int)
    {
        this_type ret = *this;
        ++helper_.iter_;
        return ret;
    }

    /// True if iterators point to same chunks.
    bool operator==(const this_type &rhs) const {
        return (helper_.iter_ == rhs.helper_.iter_);
    }

    /// True if iterators point to different chunks.
    bool operator!=(const this_type &rhs) const {
        return (helper_.iter_ != rhs.helper_.iter_);
    }

  private:

    Helper helper_;
};

typedef BufferIterator<InputIteratorHelper> InputBufferIterator;
typedef BufferIterator<OutputIteratorHelper> OutputBufferIterator;

} // detail namespace

} // namespace

#endif


text:
<?php
namespace deploydog\Slavedriver\Tests;

use deploydog\Slavedriver\Exception\InvalidLogLevel;
use deploydog\Slavedriver\Job;
use deploydog\Slavedriver\JobLogMessage;
use deploydog\Slavedriver\LogLevels;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;

class LogLevelsTest extends TestCase {
    public function test_setting_starting_and_finishing() {
        $logLevels = new LogLevels();
        $logLevels->setJobStartingAndFinishing(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getJobStartingAndFinishing()
        );
    }

    public function test_setting_error_exit_code() {
        $logLevels = new LogLevels();
        $logLevels->setErrorExitCode(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getErrorExitCode()
        );
    }

    public function test_setting_invalid_config() {
        $logLevels = new LogLevels();
        $logLevels->setInvalidConfig(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getInvalidConfig()
        );
    }

    public function test_setting_not_finished_when_expected() {
        $logLevels = new LogLevels();
        $logLevels->setNotFinishedWhenExpected(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getNotFinishedWhenExpected()
        );
    }

    public function test_setting_needing_to_be_killed() {
        $logLevels = new LogLevels();
        $logLevels->setNeedingToBeKilled(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getNeedingToBeKilled()
        );
    }

    public function test_setting_cannot_start_next() {
        $logLevels = new LogLevels();
        $logLevels->setCannotStartNextAsLastStillRunning(LogLevel::DEBUG);
        $this->assertSame(
            LogLevel::DEBUG,
            $logLevels->getCannotStartNextAsLastStillRunning()
        );
    }

    public function test_setting_invalid_starting_and_finishing() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setJobStartingAndFinishing('something-invalid');
    }

    public function test_setting_invalid_error_exit_code() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setErrorExitCode('something-invalid');
    }

    public function test_setting_invalid_invalid_config() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setInvalidConfig('something-invalid');
    }

    public function test_setting_invalid_not_finished_when_expected() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setNotFinishedWhenExpected('something-invalid');
    }

    public function test_setting_invalid_needing_to_be_killed() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setNeedingToBeKilled('something-invalid');
    }

    public function test_setting_invalid_cannot_start_next() {
        $this->expectException(InvalidLogLevel::class);
        $logLevels = new LogLevels();
        $logLevels->setCannotStartNextAsLastStillRunning('something-invalid');
    }
}