text:
package com.android.deskclock.alarms;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import yunos.support.v4.app.FragmentActivity;
import yunos.support.v4.app.FragmentManager;
import yunos.support.v4.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextClock;
import android.widget.TextView;

import com.android.deskclock.AlarmUtils;
import com.android.deskclock.AliAlarmScreen;
import com.android.deskclock.Log;
import com.android.deskclock.R;
import com.android.deskclock.SettingsActivity;
import com.android.deskclock.Utils;
import com.android.deskclock.provider.AlarmInstance;
import com.android.deskclock.widget.multiwaveview.GlowPadView;
import com.android.deskclock.AlarmFragment;
import com.android.deskclock.AlarmFeatureOption;

import com.aliyun.ams.systembar.SystemBarColorManager;
import com.aliyun.ams.ta.StatConfig;
import com.aliyun.ams.ta.TA;
import com.aliyun.ams.ta.Tracker;

import java.lang.reflect.Method;
/**
 * Alarm activity that pops up a visible indicator when the alarm goes off.
 */
public class AlarmActivity extends FragmentActivity {
    // AlarmActivity listens for this broadcast intent, so that other applications
    // can snooze the alarm (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String ALARM_SNOOZE_ACTION = "com.android.deskclock.ALARM_SNOOZE";

    // These defaults must match the values in res/xml/settings.xml
    private static final String DEFAULT_SNOOZE_MINUTES = "10";
    private final int SNOOZE_TIME = 10;
    private boolean mHasSnoozeDisplay = false;
    // AlarmActivity listens for this broadcast intent, so that other applications
    // can dismiss the alarm (after ALARM_ALERT_ACTION and before ALARM_DONE_ACTION).
    public static final String ALARM_DISMISS_ACTION = "com.android.deskclock.ALARM_DISMISS";

    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
    private Context mContext;

    private static AlarmInstance mInstance;
    private int mVolumeBehavior;
    //private GlowPadView mGlowPadView;
    private AudioManager mAudioManager;
    public static boolean mRecentAPP;

    public static AlarmInstance getAlarmInstance() {
        return mInstance;
    }

    //private GlowPadController glowPadController = new GlowPadController();
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.v("AlarmActivity - Broadcast Receiver - " + action);
            if (action.equals(ALARM_SNOOZE_ACTION)) {
                int snoozeTime = intent.getIntExtra("snoozeTime", SNOOZE_TIME);
                PreferenceManager.getDefaultSharedPreferences(context).edit().putString("SnoozeTime", String.valueOf(snoozeTime)).commit();
                TA.getInstance().getDefaultTracker().commitEvent("Page_AlarmAlert",
                        2101, "Button_Snooze", null, null, null);
                snooze();
            } else if (action.equals(ALARM_DISMISS_ACTION)) {
                TA.getInstance().getDefaultTracker().commitEvent("Page_AlarmAlert",
                        2101, "Button_Dismiss", null, null, null);
                dismiss();
                if (AlarmFeatureOption.YUNOS_QCOM_PLATFORM) {
                    boolean isShutDown = intent.getBooleanExtra("isShutDown", false);
                    if (isShutDown) {
                        final Handler shutDown = new Handler();
                        shutDown.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                shutdown();
                            }
                        }, 500);
                    }
                }
            } else if (action.equals(AlarmService.ALARM_DONE_ACTION)) {
                finish();
            } else {
                Log.i("Unknown broadcast in AlarmActivity: " + action);
            }
        }
    };

    private void shutdown() {
        try {
            //»ñµÃServiceManagerÀà
            Class<?> ServiceManager = Class
                .forName("android.os.ServiceManager");

            //»ñµÃServiceManagerµÄgetService·½·¨
            Method getService = ServiceManager.getMethod("getService", java.lang.String.class);

            //µ÷ÓÃgetService»ñÈ¡RemoteService
            Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);

            //»ñµÃIPowerManager.StubÀà
            Class<?> cStub = Class
                .forName("android.os.IPowerManager$Stub");
            //»ñµÃasInterface·½·¨
            Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
            //µ÷ÓÃasInterface·½·¨»ñÈ¡IPowerManager¶ÔÏó
            Object oIPowerManager = asInterface.invoke(null, oRemoteService);
            //»ñµÃshutdown()·½·¨
            Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,boolean.class);
            //µ÷ÓÃshutdown()·½·¨
            shutdown.invoke(oIPowerManager,false,true);
       } catch (Exception e) {
            Log.e("" + e.toString(), e);
       }
    }

    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                TA.getInstance().getDefaultTracker().commitEvent("Page_AlarmAlerting",2101, "Page_AlarmAlert_Button_Press_PowerKey_or_VolumeKey_to_Snooze", null, null, null);
                snooze();
            }
        }
    };

    private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
        final String SYSTEM_DIALOG_REASON_RECENT_APP = "recentapps";
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                Log.i("CLOSE_SYSTEM_DIALOGS reason is :" + reason);
                if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    snooze();
                }
                if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APP)) {
                    Log.i("SYSTEM_DIALOG_REASON_RECENT_APP");
                    mRecentAPP =  true;
                }
            }
        }
    };

    private void snooze() {
        AlarmStateManager.setSnoozeState(this, mInstance);
    }

    private void dismiss() {
        AlarmStateManager.setDismissState(this, mInstance);
    }

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mContext = this;

        //getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED,FLAG_HOMEKEY_DISPATCHED);

        long instanceId = AlarmInstance.getId(getIntent().getData());
        mInstance = AlarmInstance.getInstance(this.getContentResolver(), instanceId);
        Log.v("Displaying alarm for instance: " + mInstance);
        if (mInstance == null) {
            // The alarm got deleted before the activity got created, so just finish()
            Log.v("Error displaying alarm for intent: " + getIntent());
            finish();
            return;
        }

        // Get the volume/camera button behavior setting
        final String vol = SettingsActivity.DEFAULT_VOLUME_BEHAVIOR;

        mVolumeBehavior = Integer.parseInt(vol);

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //SystemBarColorManager systemBarManager = new SystemBarColorManager(this);
        //systemBarManager.setViewFitsSystemWindows(this, false);
        //systemBarManager.setStatusBarColor(mContext.getResources().getColor(R.color.alarm_clock_bg));

        // In order to allow tablets to freely rotate and phones to stick
        // with "nosensor" (use default device orientation) we have to have
        // the manifest start with an orientation of unspecified" and only limit
        // to "nosensor" for phones. Otherwise we get behavior like in b/8728671
        // where tablets start off in their default orientation and then are
        // able to freely rotate.
        if (!getResources().getBoolean(R.bool.config_rotateAlarmAlert)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        }
        //updateLayout();
        FrameLayout layout = new FrameLayout(this);
        layout.setId(android.R.id.custom);
        setContentView(layout);
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(android.R.id.custom, new AlarmFragment());
        transaction.commit();

        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(homePressReceiver, homeFilter);
        final IntentFilter powerfilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mBatInfoReceiver, powerfilter);
        // Register to get the alarm done/snooze/dismiss intent.
        final IntentFilter filter = new IntentFilter(AlarmService.ALARM_DONE_ACTION);
        filter.addAction(ALARM_SNOOZE_ACTION);
        filter.addAction(ALARM_DISMISS_ACTION);
        registerReceiver(mReceiver, filter);

    }

    private void updateTitle() {
        final String titleText = mInstance.getLabelOrDefault(this);
        //TextView tv = (TextView)findViewById(R.id.alertTitle);
        //tv.setText(titleText);
        super.setTitle(titleText);
    }

    private void updateLayout() {
        final LayoutInflater inflater = LayoutInflater.from(this);
        //final View view = inflater.inflate(R.layout.alarm_alert, null);
        final View view = new AliAlarmScreen(this.getApplicationContext());
        view.setId(android.R.id.custom);
        view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        setContentView(view);
        //updateTitle();
        //Utils.setTimeFormat((TextClock)(view.findViewById(R.id.digitalClock)),
                //(int)getResources().getDimension(R.dimen.bottom_text_size));

        // Setup GlowPadController
        //mGlowPadView = (GlowPadView) findViewById(R.id.glow_pad_view);
        //mGlowPadView.setOnTriggerListener(glowPadController);
        //glowPadController.startPinger();
    }

    private void ping() {
        //mGlowPadView.ping();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateLayout();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == TA.getInstance() || null == TA.getInstance().getDefaultTracker()) {
            StatConfig.getInstance().setContext(this.getApplicationContext());
            StatConfig.getInstance().turnOnDebug();
            Tracker lTracker = TA.getInstance().getTracker("21736479");
            lTracker.setAppKey("21736479");
            TA.getInstance().setDefaultTracker(lTracker);
        }
        TA.getInstance().getDefaultTracker().pageEnter("Page_AlarmAlert");
    }

    @Override
    protected void onPause() {
        super.onPause();
        TA.getInstance().getDefaultTracker().pageLeave("Page_AlarmAlert_leave");
    }

    @Override
    public void onBackPressed() {
        // Don't allow back to dismiss.
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // Do this on key down to handle a few of the system keys.
        Log.v("AlarmActivity - dispatchKeyEvent - " + event.getKeyCode());
        switch (event.getKeyCode()) {
            // Volume keys and camera keys dismiss the alarm
            case KeyEvent.KEYCODE_VOLUME_MUTE:
            case KeyEvent.KEYCODE_CAMERA:
            case KeyEvent.KEYCODE_FOCUS:
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Log.i("dispatchKeyEvent" + event.getKeyCode());
                if(!mHasSnoozeDisplay){
                    mHasSnoozeDisplay = true;
                    TA.getInstance().getDefaultTracker().commitEvent("Page_AlarmAlerting",2101, "Page_AlarmAlert_Button_Press_PowerKey_or_VolumeKey_to_Snooze", null, null, null);
                    snooze();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_MENU:
                break;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onDestroy() {
        if(null != mBatInfoReceiver){
            try {
                unregisterReceiver(mBatInfoReceiver);
            } catch (Exception e) {
                Log.e("unregisterReceiver mBatInfoReceiver failure :"+e.getCause());
            }
        }

        if(null != homePressReceiver){
            try {
                unregisterReceiver(homePressReceiver);
            } catch (Exception e) {
                Log.e("unregisterReceiver homePressReceiver failure :"+e.getCause());
            }
        }

        if(null != mReceiver) {
            try {
                unregisterReceiver(mReceiver);
            } catch (Exception e) {
                Log.e("unregisterReceiver mReceiver failure" + e.getCause());
            }
        }
        mHasSnoozeDisplay = false;
        super.onDestroy();
    }
}


text:
(function () {
    function Message($firebaseArray, Firebase, $cookies) {
      var Message = {};
      var ref = firebase.database().ref().child("messages");

      var messages = $firebaseArray(ref);

      Message.getByRoomId = function(room) {
        /*var roomId = ref.child("roomId");*/
        return $firebaseArray(ref.orderByChild("roomId").equalTo(room))
      };

      Message.send = function(newMessage, roomId) {
        var  username = $cookies.get("frontPorchCurrentUser"),
             timeStamp = Firebase.database.ServerValue.TIMESTAMP,
             chatRoom = roomId.$id,
             messages = $firebaseArray(ref.orderByChild('roomId').equalTo('room'));
             console.log(username);
             messages.$add({
                 username: username,
                 content: newMessage,
                 sentAt: timeStamp,
                 roomId: chatRoom
             })

      };

      return Message;

    }

    angular
      .module('frontPorch')
      .factory('Message', ['$firebaseArray', 'Firebase', '$cookies', Message]);

})();

redpajama_set_name: RedPajamaGithub


text:
module Dinamo
  class Model
    module Callback
      extend ActiveSupport::Concern

      def with_callback(kind, *args, &block)
        invoke_callbacks(:before, kind, *args)
        block.call
      ensure
        invoke_callbacks(:after, kind, *args)
      end

      def invoke_callbacks(type, kind, *args)
        ref = respond_to?(:callbacks) ? callbacks : self.class.callbacks
        current = ref[type][kind]
        return unless current
        current.each { |callback| instance_exec(*args, &callback) }
      end

      module ClassMethods
        def on(type, kind, &callback)
          (callbacks[type][kind] ||= []) << callback
        end

        def before(kind, &callback)
          on(:before, kind, &callback)
        end

        def after(kind, &callback)
          on(:after, kind, &callback)
        end

        def callbacks
          @callbacks ||= { before: {}, after: {} }
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Mobile Business Opportunities | RMB4U</title>

    <meta name="description" content="Earn a living with your own mobile business, from Waste & Recycling to Chauffeur & Private Hire" />
    <meta name="author" content="Ash Edwards Design (www.ashedwardsdesign.co.uk)" />
    <meta name="robots" content="index,follow" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <link rel="canonical" href="@@homepage@@__SOURCE_FILENAME__" />

    @@analytics

    @@nav

On the Road Business Opportunities

Earn a living with your own mobile business, from Waste & Recycling to Chauffeur & Private Hire

WASTE DISTRIBUTION

Are you looking for a waste collection franchise or a waste distribution franchise? Discover our Waste Distribution business model!

Just £11,995+VAT

                        FIND OUT MORE

SURFACE RESTORATION

Earn a fantastic living offering professional surface restoration services. Full training included.

Just £9,995+VAT

                        FIND OUT MORE

SANDWICH DELI

Are you looking to run your own sandwich delivery business with your own mobile deli van?

Only £5,995+VAT

                        FIND OUT MORE

MULTI-CLEAN

Are you looking for a Cleaning Franchise Opportunity? Multi-Clean is a business that will give you a fantastic income.

Only £11,995

                        FIND OUT MORE

CHAUFFEUR & PRIVATE HIRE

Are you looking to run your own chauffeur business or want to know how to start a chauffeur business?

From just £4,995+VAT

                        FIND OUT MORE

PORTABLE APPLIANCE TESTING

Are you looking for a PAT testing franchise or to start a PAT testing business? Discover our Portable Appliance Testing business opportunity!

Just £4,995+VAT

                        FIND OUT MORE

HIRE BAR

Are you looking to run your own mobile bar business or to buy a mobile bar? Our bar hire package could be for you!

Only £5,995+VAT

                        FIND OUT MORE

DJ & KARAOKE

Are you looking to run your own mobile DJ business or a karaoke franchise? Find out more about our DJ & Karaoke opportunity.

Just £5,995+VAT

                        FIND OUT MORE

HOME HELP

Are you looking for a home help business opportunity or a home help franchise? Make a living with our home help business opportunity.

From just £3,995+VAT

                        FIND OUT MORE

LOCKSMITH

Are you looking for a locksmith franchise or a locksmith business for sale? Find out more about our Locksmith business opportunity here!

Just £6,995+VAT

                        FIND OUT MORE

COMING SOON

This opportunity is coming soon. Check back regularly to see the new business opportunities we have on offer.

COMING SOON

This opportunity is coming soon. Check back regularly to see the new business opportunities we have on offer.

        @@footer


text:
package infrastructure

import (
	"strings"

	boshplat "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-agent/platform"
	bosherr "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/errors"
	boshlog "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/logger"
	boshsys "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/system"
)

type RegistryProvider interface {
	GetRegistry() (Registry, error)
}

type registryProvider struct {
	metadataService MetadataService
	useServerName   bool
	platform        boshplat.Platform
	fs              boshsys.FileSystem
	logTag          string
	logger          boshlog.Logger
}

func NewRegistryProvider(
	metadataService MetadataService,
	platform boshplat.Platform,
	useServerName bool,
	fs boshsys.FileSystem,
	logger boshlog.Logger,
) RegistryProvider {
	return &registryProvider{
		metadataService: metadataService,
		platform:        platform,
		useServerName:   useServerName,
		fs:              fs,
		logTag:          "registryProvider",
		logger:          logger,
	}
}

func (p *registryProvider) GetRegistry() (Registry, error) {
	registryEndpoint, err := p.metadataService.GetRegistryEndpoint()
	if err != nil {
		return nil, bosherr.WrapError(err, "Getting registry endpoint")
	}

	if strings.HasPrefix(registryEndpoint, "http") {
		p.logger.Debug(p.logTag, "Using http registry at %s", registryEndpoint)
		return NewHTTPRegistry(p.metadataService, p.platform, p.useServerName), nil
	}

	p.logger.Debug(p.logTag, "Using file registry at %s", registryEndpoint)
	return NewFileRegistry(registryEndpoint, p.fs), nil
}


text:
The main container containing all other views!

Nested views

To create a view within another view... just do it.

Create views with knockout foreach

Use the 'o-view-model' binding to assign a view model to a view dynamicaly.

Create views with knockout foreach from observable

Here views are created and then injected with a viewmodel/datacontext from the foreach loop. On removal the views and viewmodels are dosposed and removed completely.

A view inside a view...

A stupid example, but it works. Everything is created dynamicaly and disposed of on deletion.


text:
"""A sample job that prints string."""

from ndscheduler import job

class AwesomeJob(job.JobBase):

    @classmethod
    def meta_info(cls):
        return {
            'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
            'notes': 'This will print a string in your shell. Check it out!',
            'arguments': [
                # argument1
                {'type': 'string', 'description': 'First argument'},

                # argument2
                {'type': 'string', 'description': 'Second argument'}
            ],
            'example_arguments': '["first argument AAA", "second argument BBB"]'
        }

    def run(self, argument1, argument2, *args, **kwargs):
        print('Hello from AwesomeJob! Argument1: %s, Argument2: %s' % (argument1, argument2))

if __name__ == "__main__":
    # You can easily test this job here
    job = AwesomeJob.create_test_instance()
    job.run(123, 456)


text:
<!DOCTYPE html>

<base href="http://localhost/github/201507lanbao/" />

    <meta charset="UTF-8">
    <title></title>

access_token: {$access_token['access_token']}

expires_in: {$access_token['expires_in']}

token_type: {$access_token['token_type']}

scope: {$access_token['scope']}

<form enctype="multipart/form-data"  action="api.php/File/upload?access_token={$access_token['access_token']}" method="post">

    <input type="text" name="uid" >
    <input type="text" name="type" value="avatar" >

    <input type="file" name="image" >

    <button type="submit">上传文件</button>
</form>


text:
<?
/**
 * @author IbericaSoft
 * @abstract Gestión de Articulos de tienda
 * @version 1.0 08.2012 Creación
 * @version 2.0 02.2014 Personalización L&M
 * @version 3.0 03.2015 Evolución
 */
	class Articulos extends Applications {

		public $VERSION = 'Version: 3.0 (03.2015)

Evolución

IbericaSoft 2015';
		public $PATHCLASS = '/applications/articulos';
		public $id,$autor_variedad,$codigo,$dir_images=null,$subfamilias,$variedades,$iva,$autor,$tallas,$filtro_categoria,$filtro_familia,$filtro_subfamilia,$filtro_articulo,$filtro_autor,$filtro_campo="categoria",$filtro_orden="up",$filtro_pagina=1;

		/**
		 * Creación e inicialización del módulo
		 */
		public function __construct( DobleOS $system ){
			parent::__construct($system);
			$this->dir_images = Utils_OS::getValueAPP($this->oSystem->getConnection() , 'IMAGE_ARTICULOS_DIR');
		}

		/**
		 * Recuperar de la sesion esta clase implica invocar este metodo, no se vuelve a construir
		 */
		public function setInstance( DobleOS $system ){
			parent::setInstance($system);

			if ( isset($_REQUEST['id']) )
				$this->id 	= $_REQUEST['id'];
			if ( isset($_REQUEST['id_autor']) )
				$this->autor_variedad = $_REQUEST['id_autor'];//para gestion de la variedad
			if ( isset($_REQUEST['codigo']) )
				$this->codigo = $_REQUEST['codigo'];//para gestion de la variedad

			if ( isset($_REQUEST['_articulo']) )
				$this->filtro_articulo = $_REQUEST['_articulo'];
			if ( isset($_REQUEST['_categoria']) )
				$this->filtro_categoria = $_REQUEST['_categoria'];
			if ( isset($_REQUEST['_familia']) )
				$this->filtro_familia = $_REQUEST['_familia'];
			if ( isset($_REQUEST['_subfamilia']) )
				$this->filtro_subfamilia = $_REQUEST['_subfamilia'];
			if ( isset($_REQUEST['_autor']) )
				$this->filtro_autor = $_REQUEST['_autor'];
			if ( $_REQUEST['filtro_campo'] )
				$this->filtro_campo = $_REQUEST['filtro_campo'];
			if ( $_REQUEST['filtro_orden'] )
				$this->filtro_orden = $_REQUEST['filtro_orden'];
			if ( $_REQUEST['filtro_pagina'] )
				$this->filtro_pagina= $_REQUEST['filtro_pagina'];
		}

		/**
		 * Persiste esta clase en sesión
		 */
		public function __destruct(){
			if ( $this->isPesistance )
				$_SESSION[$this->oSystem->getOrderActionClass()->getClassSession()] = serialize( $this );
		}

		/**
		 * Datos de otros módulos
		 */
		public function bindingsData(){
			//categoria>familias>subfamilia
			$rows = array();
			$sql = "SELECT sfam.id, CONCAT(categoria,'/',familia,'/',subfamilia) subfamilia
				FROM subfamilias sfam LEFT JOIN familias fam ON (sfam.id_familia=fam.id) LEFT JOIN categorias cat ON (fam.id_categoria=cat.id)
				WHERE sfam.estado NOT IN ('XXX') ORDER BY subfamilia;";
			$result = $this->computeSQL($sql,null);
			while ( $row = $this->oSystem->getConnection()->getColumnas($result) )
				array_push( $rows, array_map("utf8_encode", $row) );
			$this->subfamilias = json_encode($rows);
			//ivas
			$rows = array();
			$result = $this->computeSQL("SELECT id, iva FROM iva WHERE estado IN ('ON');",null);
			while ( $row = $this->oSystem->getConnection()->getColumnas($result) )
				array_push( $rows, array_map("utf8_encode", $row) );
			$this->iva = json_encode($rows);
			//autores
			$rows = array();
			$result = $this->computeSQL("SELECT id, autor FROM autores WHERE estado IN ('ON');",null);
			while ( $row = $this->oSystem->getConnection()->getColumnas($result) )
				array_push( $rows, array_map("utf8_encode", $row) );
			$this->autor = json_encode($rows);
			//tallas
			$rows = array();
			$result = $this->computeSQL("SELECT id, talla FROM tallas WHERE estado IN ('ON');",null);
			while ( $row = $this->oSystem->getConnection()->getColumnas($result) )
				array_push( $rows, array_map("utf8_encode", $row) );
			$this->tallas = json_encode($rows);
		}

		public function start(){
			$this->computeTemplate(null, null, $this->pathApp . '/listado.html');
		}

		/**
		 * SQL posible a esta clase para buscar elementos
		 */
		public function filter(){
			$this->filtroSQL = "SELECT art.*, cat.categoria, fam.familia, sfam.subfamilia, autor
				,date_format(art.fmodificacion,'%d-%m-%Y %H:%i:%s') ffmodificacion
				,format(art.precio,2,'de_DE') fprecio
				,format(art.oferta,2,'de_DE') foferta
				,(select nombre from os_administradores adm where adm.id=art.id_administrador) gestor
				,(CASE art.estado WHEN 'ON' THEN 'Online' WHEN 'OFF' THEN 'Offline' ELSE 'Elimado/a' END) festado
				FROM articulos art
				LEFT JOIN subfamilias sfam ON art.id_subfamilia=sfam.id
				LEFT JOIN familias fam ON sfam.id_familia=fam.id
				LEFT JOIN categorias cat ON fam.id_categoria=cat.id
				LEFT JOIN autores aut ON art.id_autor=aut.id
				WHERE art.estado IN ('ON','OFF')";

			if ( $_REQUEST['_articulo'] )
				$this->filtroSQL .= " AND art.articulo LIKE '%$this->filtro_articulo%'";
			if ( $_REQUEST['_categoria'] )
				$this->filtroSQL .= " AND categoria LIKE '%$this->filtro_categoria%'";
			if ( $_REQUEST['_familia'] )
				$this->filtroSQL .= " AND familia LIKE '%$this->filtro_familia%'";
			if ( $_REQUEST['_subfamilia'] )
				$this->filtroSQL .= " AND subfamilia LIKE '%$this->filtro_subfamilia%'";
			if ( $_REQUEST['_autor'] )
				$this->filtroSQL .= " AND autor LIKE '%$this->filtro_autor%'";

			if ( $this->filtro_campo )
				$this->filtroSQL .=" ORDER BY $this->filtro_campo".($this->filtro_orden=="up"?"":" desc");
		}

		/**
		 * Recuperacion de datos
		 */
		public function listAll(){
			$this->filter();
			$key = strtolower(get_class($this));
			$datos = array();
			$resultados = $this->computeSQL($this->filtroSQL,false);
			while ( $row = $this->oSystem->getConnection()->getColumnas($resultados) )
				array_push( $datos, array_map("utf8_encode", $row) );

			if ( $this->oSystem->getOrderActionClass()->getChannel()=='json' ){
				$key = "json";
				$datos = json_encode($datos);
			}
			$this->oSystem->getDataTemplate()->addData($key, $datos);
		}

		/**
		 * Nuevo
		 */
		public function doNew(){
			$key = strtolower(get_class($this));
			$datos[operacion] = 'Alta';
			$datos[fecha] = date("d-m-Y");
			$datos[estado] = 'ACT';
			$template = $this->pathApp . '/edicion.html';
			$this->computeTemplate($key, $datos, $template);
			$this->bindingsData();//para cargar las categorias-familias
			$this->variedades = null;
		}

		/**
		 * Vista de dados
		 */
		public function doView(){
			$general = $this->getDatos();
			$key = strtolower(get_class($this));
			$datos = $general['datos'];
			$datos[operacion] = 'Consulta';
			$template = $this->pathApp . '/vista.html';
			$this->computeTemplate($key, $datos, $template);
			$this->variedades = $general['detalles'];
		}

		/**
		 * Edición de datos
		 */
		public function doModify(){
			$general = $this->getDatos();
			$key = strtolower(get_class($this));
			$datos = $general['datos'];
			$datos[operacion] = 'Edición';
			$template = $this->pathApp . '/edicion.html';
			$this->computeTemplate($key, $datos, $template);
			$this->oSystem->getDataTemplate()->addData("detalles", $general['detalles']);
			$this->bindingsData();//para cargar las categorias-familias
		}

		/**
		 * Recoger los datos de este módulo
		 */
		private function getDatos(){
			//master
			$sql = "SELECT art.*,(select nombre from os_administradores where id=sfam.id_administrador) usuario,
			CONCAT(categoria,'/',familia,'/',subfamilia) subfamilia
			,format(iva,2,'de_DE') fiva,format(peso,3,'de_DE') fpeso,format(precio,2,'de_DE') fprecio,format(oferta,2,'de_DE') foferta
			,autor
			,date_format(art.fmodificacion,'%d-%m-%Y %H:%i:%s') ffmodificacion
			,(CASE art.estado WHEN 'ON' THEN 'Online' WHEN 'OFF' THEN 'Offline' ELSE 'Elimado/a' END) festado
			FROM articulos art
				LEFT JOIN iva i ON art.id_iva=i.id
				LEFT JOIN autores aut ON art.id_autor=aut.id
				LEFT JOIN subfamilias sfam ON art.id_subfamilia=sfam.id
				LEFT JOIN familias fam ON sfam.id_familia=fam.id
				LEFT JOIN categorias cat ON fam.id_categoria=cat.id
				WHERE art.estado IN ('ON','OFF') AND art.id=$this->id;";
			$resultado1 = $this->computeSQL($sql,false);
			if ( !$this->oSystem->getConnection()->hayResultados() )
				throw new DobleOSException("",111,array("title"=>"Aviso de error","message"=>"El registro $this->categoria ¡no existe!

$sql","type"=>"error","class"=>get_class($this),"sessionclass"=>$this->oSystem->getOrderActionClass()->getClassSession(),"do"=>"start","report"=>"SQL no da resultados: $sql") );

			//detail
			$sql= "SELECT a.*,t.talla FROM articulos_variedad a LEFT JOIN tallas t ON (a.id_talla=t.id) WHERE a.id_articulo=$this->id;";
			$resultado2 = $this->computeSQL($sql,false);
			$datos = array();
			while ( $row = $this->oSystem->getConnection()->getColumnas($resultado2) )
				array_push( $datos, array_map("utf8_encode", $row) );
			return $resultados = array("datos"=>$this->oSystem->getConnection()->getColumnas($resultado1),"detalles"=>json_encode($datos));
		}

		/**
		 * Insercion de datos
		 */
		public function doInsert(){
			$datos = $this->prepareStatement();
			$datos['id'] = Utils_OS::getValueAPP($this->oSystem->getConnection() , 'CODIGO_ARTICULO');
			$datos[codigo]  = str_pad($datos['id'], 4,"0",STR_PAD_LEFT);
			Utils_OS::updateValueAPProl($this->oSystem->getConnection() , 'CODIGO_ARTICULO',($datos['id']+1),$this->oSystem->getUser()->getId());
			$this->id = $datos['id'];
			$this->codigo = $datos['codigo'];
			$this->autor_variedad = $datos['id_autor'];

			while(list($key,$val)= each($datos)){
				if ($sqlFields) {
					$sqlFields.=',';
					$sqlValues.=',';
				}
				$sqlFields .= "$key";
				$sqlValues .= "\"$val\"";
			}
			$sql = "INSERT INTO articulos ($sqlFields) VALUES ($sqlValues)";
			$this->executeStatement($sql);
			header("Location: ?class=$_REQUEST[class]&sessionclass=$_REQUEST[sessionclass]&do=start");
		}

		/**
		 * Modificación de datos
		 */
		public function doUpdate(){
			$datos = $this->prepareStatement();
			while(list($key,$val)= each($datos)){
				if ($sqlUpdate)
					$sqlUpdate .= ',';
				if ( substr($val,0,1)=='@' )
					$val=substr($val,1);
				else
					$val = "\"$val\"";
				$sqlUpdate .= "$key=$val";
			}
			$sql = "UPDATE articulos SET $sqlUpdate WHERE id='$this->id';";
			$this->executeStatement($sql);
			header("Location: ?class=$_REQUEST[class]&sessionclass=$_REQUEST[sessionclass]&do=start");
		}

		/**
		 * Datos que vienen en un formulario y que incluimos en un SQL
		 */
		private function prepareStatement(){
			$datos = array();
			$datos[articulo]	= trim(addslashes($_REQUEST[articulo]));
			$datos[id_subfamilia]	= $_REQUEST[id_subfamilia];
			$datos[id_iva]		= $_REQUEST[id_iva];
			$datos[id_autor]	= $_REQUEST[id_autor];
			//codigo-> es calculado
			$datos[codigo_proveedor]= trim(addslashes($_REQUEST[codigo_proveedor]));
			$datos[peso] 		= $_REQUEST[peso];
			$datos[precio] 		= $_REQUEST[precio];
			$datos[oferta] 		= ($_REQUEST[oferta]?$_REQUEST[oferta]:'0.00');
			$datos[vendible] 	= $_REQUEST[vendible];
			$datos[enlace] 		= $_REQUEST[enlace];
			$datos[estado] 		= $_REQUEST[estado];
			$datos[descripcion]	= trim(addslashes($_REQUEST[descripcion]));
			$datos[foto_1] 		= $_REQUEST[foto_1];
			if ( $_REQUEST[foto_2] )
				$datos[foto_2] 		= $_REQUEST[foto_2];
			if ( $_REQUEST[foto_3] )
				$datos[foto_3] 		= $_REQUEST[foto_3];
			if ( $_REQUEST[foto_4] )
				$datos[foto_4] 		= $_REQUEST[foto_4];
			/** Auditores */
			$datos[falta]			= date("Y-m-d H:i:s");
			$datos[fmodificacion]	= date("Y-m-d H:i:s");
			$datos[id_administrador]= $this->oSystem->getUser()->getId();
			//variedades-> se trata aparte
			return $datos;
		}

		/**
		 * Ejecución de SQLs bajo transacción
		 */
		private function executeStatement($sql,$varieties=true){
			try {
				$this->computeSQL("START TRANSACTION", false);
				$this->computeSQL($sql, false);
				if ( !$this->oSystem->getConnection()->lastQueryIsOK(1) )
					throw new Exception('Error en los datos. Detalles: '.addslashes($this->oSystem->getConnection()->getError()));
				if ($varieties)
					$this->variety(); //variedades del articulo
				$this->computeSQL("COMMIT", false);
			} catch(Exception $e) {
				$this->computeSQL("ROLLBACK", false);
				$this->oSystem->getLogger()->error( $e->getMessage() );
				throw new DobleOSException($e->getMessage(),0,array("title"=>"Aviso de error","message"=>$e->getMessage(),"type"=>"error","class"=>get_class($this),"sessionclass"=>$this->oSystem->getOrderActionClass()->getClassSession(),"do"=>"start","report"=>"") );
			}
		}

		/**
		 * Inserta/actualiza las lineas de detalle (variedades)
		 */
		private function variety(){
			$this->oLogger->debug("tratando variedades");
			$detalles = utf8_encode($_REQUEST['lista_variedades']);
			$detalles = json_decode($detalles);
			$adm = $this->oSystem->getUser()->getId();

			if ( count($detalles)==0 )
				throw new Exception("No hay variedades");

			foreach ( $detalles as $detalle ){
				$sql = "SELECT * FROM articulos_variedad WHERE id_articulo=$this->id AND id_talla=$detalle->talla;";
				$this->computeSQL($sql, false);
				$codigo = str_pad($this->autor_variedad, 3,"0",STR_PAD_LEFT) . $this->codigo . str_pad($detalle->talla, 2,"0",STR_PAD_LEFT);

				if ( !$this->oSystem->getConnection()->hayResultados() ){
					$sql = "INSERT INTO articulos_variedad (id_articulo,id_talla,codigo,stock,estado,falta,fmodificacion,id_administrador)
								VALUES ($this->id,$detalle->talla,'$codigo',$detalle->stock,'$detalle->estado',now(),now(),$adm);";
				} else {
					$sql = "UPDATE articulos_variedad SET stock=$detalle->stock,estado='$detalle->estado',codigo='$codigo',fmodificacion=now(),id_administrador=$adm
								WHERE id_articulo=$this->id AND id_talla=$detalle->talla;";
				}
				$this->computeSQL($sql, false);
				if ( !$this->oSystem->getConnection()->lastQueryIsOK(1) )
					throw new Exception($this->oSystem->getConnection()->getError());
			}
		}
		/**
		 * Baja de datos
		 */
		public function doDelete(){
			/** Si de esta subfamilia depende algun articulo activo no se puede borrar */
			$sql = "SELECT * FROM pedidos_detalle FROM id_articulo=$this->id LIMIT 5;";
			$resultado = $this->computeSQL($sql, false);
			if ( $this->oSystem->getConnection()->hayResultados() ){
			$message = 'No es posible eliminar el artículo porque se ha vendido. Puede dejarlo en estado offline';
			while ( $datos = $this->oSystem->getConnection()->getColumnas($resultado) )
				$message .= addslashes( "
$datos[articulo]
" );
				throw new DobleOSException($message,0,array("title"=>"Aviso de error","message"=>$message,"type"=>"error","class"=>get_class($this),"sessionclass"=>$this->oSystem->getOrderActionClass()->getClassSession(),"do"=>"start") );
			}
			/** marcamos registro como eliminado */
			$adm= $this->oSystem->getUser()->getId();
			$sql = "UPDATE articulos SET estado='XXX',fmodificacion=now(),id_administrador=$adm WHERE id=$this->id;";
			$this->executeStatement($sql,false);
			header("Location: ?class=$_REQUEST[class]&sessionclass=$_REQUEST[sessionclass]&do=start");
		}

		/**
		* Generar fichero CSV
		*/
		public function exportCSV(){
			$this->filter();
			parent::generalExportCSV( 'csv', array('Id','Categoria','Familia','Subfamilia','Precio','Oferta','Posición','Descripción','Estado','Modificado','Gestor'),
				array('id','categoria','familia','subfamilia','fprecio','foferta','posicion','descripcion','festado','ffmodificacion','gestor'),$this->pathClass . '/csv.html' );
		}

		/**
		* Generar fichero PDF
		*/
		public function doListPrint(){
		 	$this->filter();
		 	parent::pdfGenericList(array('articulo','categoria','familia','subfamilia','autor','fprecio'),"../_commons/css","Listado-Artículos.pdf");
		 }
	}
?>


text:
package com.innovaee.eorder.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.junit.Test;

import com.innovaee.eorder.entity.Dish;
import com.innovaee.eorder.exception.CategoryNotFoundException;
import com.innovaee.eorder.exception.DishNotFoundException;
import com.innovaee.eorder.exception.DuplicateNameException;
import com.innovaee.eorder.exception.InvalidPageSizeException;
import com.innovaee.eorder.exception.PageIndexOutOfBoundExcpeiton;
import com.innovaee.eorder.utils.Constants;
import com.innovaee.eorder.utils.MessageUtil;
import com.innovaee.eorder.vo.DishVO;

/**
 * @Title: DishServiceTest
 * @Description: DishService 单元测试类
 *
 * @version V1.0
 */
public class DishServiceTest extends BaseSpringTestCase {

    @Resource
    private DishService dishService;

    /**
     * 单元测试 - 通过错误的菜品ID获取菜品
     */
    @Test
    public void getDishByInvalidIdTest() {
        try {
            dishService.getDishById(1000L);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 通过正确的菜品ID获取菜品
     */
    @Test
    public void getDishByIdTest() throws DishNotFoundException {
        Dish dish = dishService.getDishById(1L);

        assertEquals(dish.getName(), "手撕包菜");
    }

    /**
     * 单元测试 - 通过错误的菜品名获取菜品
     */
    @Test
    public void getDishByInvalidNameTest() {
        try {
            dishService.getDishByName("手撕包菜1");
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 通过正确的菜品名获取菜品
     */
    @Test
    public void getDishByNameTest() throws DishNotFoundException {
        Dish dish = dishService.getDishByName("手撕包菜");

        assertNotNull(dish);
    }

    /**
     * 单元测试 - 添加重名菜品
     */
    @Test
    public void addDishWithDuplicateNameTest() {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜");
       dishVO.setPrice(150.00f);
        dishVO.setPicPath("");

        try {
            dishService.addDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DuplicateNameException.class);
        }
    }

    /**
     * 添加错误分类的菜品信息
     */
    @Test
    public void addDishWithInvalidCategoryTest() {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜1");
       dishVO.setPrice(150.00f);
        dishVO.setPicPath("");

        try {
            dishService.addDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), CategoryNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 添加菜品信息
     *
     * @throws CategoryNotFoundException
     * @throws DuplicateNameException
     */
    @Test
    public void addDishTest() throws DuplicateNameException,
            CategoryNotFoundException {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜1");
       dishVO.setPrice(150.00f);
        dishVO.setPicPath("");

        Dish dish = dishService.addDish(dishVO);

        assertNotNull(dish);
        assertTrue(dish.getId() > 0L);
    }

    /**
     * 单元测试 - 使用已存在的菜品名更新菜品
     *
     * @throws DishNotFoundException
     */
    @Test
    public void updateDishWithDuplicateNameTest() throws DishNotFoundException {
        String duplicateName = "无油版左公鸡";
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(dish.getCategory().getId());
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(duplicateName);
        dishVO.setPicPath(dish.getPicPath());
       dishVO.setPrice(dish.getPrice());

        try {
            dishService.updateDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DuplicateNameException.class);
        }
    }

    /**
     * 单元测试 - 使用错误的菜品分类信息更新菜品
     *
     * @throws DishNotFoundException
     */
    @Test
    public void updateDishWithInvalidCategoryTest()
            throws DishNotFoundException {
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(1000L);
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(dish.getName());
        dishVO.setPicPath(dish.getPicPath());
       dishVO.setPrice(dish.getPrice());

        try {
            dishService.updateDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), CategoryNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 更新菜品信息
     *
     * @throws DishNotFoundException
     * @throws CategoryNotFoundException
     * @throws DuplicateNameException
     */
    @Test
    public void updateDishTest() throws DishNotFoundException,
            CategoryNotFoundException, DuplicateNameException {
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(dish.getCategory().getId());
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(dish.getName());
        dishVO.setPicPath(dish.getPicPath());
       dishVO.setPrice(dish.getPrice());

        dishService.updateDish(dishVO);
    }

    /**
     * 单元测试 - 删除非法ID指定的菜品信息
     */
    @Test
    public void deleteDishWithInvalidIdTest() {
        try {
            dishService.deleteDish(1000L);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 删除菜品信息
     */
    @Test
    public void deleteDishTest() throws DishNotFoundException {
        dishService.deleteDish(1L);
    }

    /**
     * 单元测试 - 菜品分页总数
     *
     * @throws InvalidPageSizeException
     * @throws CategoryNotFoundException
     */
    @Test
    public void getDishPageCountTest() throws InvalidPageSizeException,
            CategoryNotFoundException {
        Long categoryId = 1L;

        int pageCount = dishService.getDishPageCount(5, categoryId);

        assertEquals(2, pageCount);
    }

    /**
     * 单元测试 - 菜品分页数
     *
     * @throws InvalidPageSizeException
     * @throws CategoryNotFoundException
     */
    @Test
    public void getDishesByPageTest() throws InvalidPageSizeException,
            CategoryNotFoundException {
        Long categoryId = 5L;

        List<Dish> dishes = null;
        try {
            dishes = dishService.getDishesByPage(1, 5, categoryId);
            for (Dish dish : dishes) {
                System.out.println("dish: "
                        + ToStringBuilder.reflectionToString(dish));
            }
        } catch (PageIndexOutOfBoundExcpeiton e) {
            LOGGER.error(MessageUtil.getMessage("invalid_page_size_exception",
                    Constants.PAGE_SIZE.toString()));
        }
        assertNotNull(dishes);
        assertEquals(5, dishes.size());
    }

    /**
     * 单元测试 - 菜品分页数
     *
     * @throws InvalidPageSizeException
     * @throws CategoryNotFoundException
     */
    @Test
    public void getDishCountByIdTest() throws InvalidPageSizeException,
            CategoryNotFoundException {
        Long categoryId = 1L;

        Integer count = dishService.getDishCountById(categoryId);
        System.out.println("count: " + count);
    }

}


text:
{-# LANGUAGE ScopedTypeVariables #-}
module Handler.Global where

import Import

menu :: Route Hermes -> Widget
menu current = [whamlet|

            ^{createLink PostsR current "Posts"}

            ^{createLink (SPageR "idea") current "Idea"}

            ^{createLink (SPageR "roadmap") current "Roadmap"}
|]

createLink :: Route Hermes -> Route Hermes -> String -> Widget
createLink specific current label = [whamlet|
    $if current == specific
        #{label}
    $else
        #{label}
|]

emptyWidget :: Widget
emptyWidget = toWidget [hamlet|nu|]

frontIncludes :: Widget
frontIncludes = do
--  addStylesheet (StaticR style_css)
    addScriptRemote "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
    addScriptRemote "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"
    addScript (StaticR js_sh_main_min_js)
    addStylesheet (StaticR css_sh_bright_min_css)

frontWidget :: (Widget, Widget, Widget) -> Widget
frontWidget (menuWidget, sidebarWidget, contentWidget) = [whamlet|
    ^{frontIncludes}
    ^{recaptchaOptions (RecaptchaOptions (Just "clean") Nothing)}

                Hermes

            ^{menuWidget}

                ^{contentWidget}

                ^{sidebarWidget}

            --respect for the design creators! o/
            Web design released by Flash Gallery GHandler Hermes Hermes RepHtml
specificLayout (a, b, c) = defaultLayout $ frontWidget (a, b, c)

getAdminR :: Handler RepHtml
getAdminR = do
    posts <- runDB $ selectList [] [Desc PostCreated]
    pages <- runDB $ selectList [] [Desc SPageTitle]
    comments <- runDB $ selectList [] [Desc CommentCreated]
    tags <- runDB $ selectList ([] :: [Filter Tag]) []
    specificLayout (menu AdminR, emptyWidget, [whamlet|

Add content

                Create Post

                Create page

Change content

Posts
                $forall post <- posts

                        Edit
                        Delete
                        #{postTitle (entityVal post)}

Pages
                $forall page <- pages

                        Edit
                        Delete
                        #{sPageTitle (entityVal page)}

Comments
                $forall comment <- comments

                        Delete
                        #{commentAuthor (entityVal comment)}
                        #{commentBody (entityVal comment)}

Tags
                $forall tag <- tags

                        Delete
                        #{tagName (entityVal tag)}

|])

test :: forall a. (Integral a) => a -> Int
test _ = 1

getDeleteCommentR :: CommentId -> Handler RepHtml
getDeleteCommentR commentId = do
    _ <- runDB $ delete commentId
    redirect $ AdminR

getDeleteTagR :: TagId -> Handler RepHtml
getDeleteTagR tagId = do
    let aasd = approot :: Approot Hermes
    y <- getYesod
    case aasd of
        ApprootStatic t -> setMessage $ toHtml t
        ApprootMaster f -> setMessage $ toHtml $ f y
        _ -> setMessage "a"
    runDB $ deleteWhere [PostTagTag ==. tagId]
    _ <- runDB $ delete tagId
    redirect $ AdminR

getRssR :: Handler RepRss
getRssR = do
    t <- liftIO getCurrentTime
    posts <- runDB $ selectList [] [Desc PostCreated]
    let entries = map (\p -> (FeedEntry (PostR $ postSlug $ entityVal p) (postCreated $ entityVal p) (postTitle $ entityVal p) (postBody $ entityVal p))) posts
    rssFeed $ Feed "Hermes" RssR PostsR (toHtml ("An attempt to create a simple blog in Yesod" ::String)) "en" t entries


text:
package plugins

import (
	"encoding/json"
	"errors"
	"html"
	"log"
	"regexp"
	"strings"
)

var VimeoNoResultsError = errors.New("Vimeo: No results")
var VimeoEmptyResultsError = errors.New("Vimeo: Some of the fields were empty :(")

type resultWrapper struct {
	Results []jsonResult
}

type jsonResult struct {
	User  string `json:"user_name"`
	Title string `json:"title"`
}

type Vimeo struct {
	plugin
	spoiler *regexp.Regexp
}

func (plug *Vimeo) Setup(write chan IRCMessage, conf PluginConf) {
	plug.write = write
	plug.match = regexp.MustCompile(`(?:https?://|)(?:www\.|)(?:vimeo.com/)(\S+)`)
	plug.spoiler = regexp.MustCompile(`(?i)(.*spoil.*)`)
	plug.event = make(chan IRCMessage, 1000)
	scrapeAndSend(plug)
	return
}

func (plug *Vimeo) FindUri(candidate *string) (uri *string, err error) {
	uri, err = GetFirstMatch(plug.match, candidate)
	if err != nil {
		uri = nil
		return
	}
	full := "http://vimeo.com/api/v2/video/" + *uri + ".json"
	uri = &full
	return
}

func (plug Vimeo) Write(msg *IRCMessage, body *string) (err error) {
	var result []jsonResult
	log.Println(*body)
	err = json.Unmarshal([]byte(*body), &result)
	if err != nil {
		return
	}

	if len(result) != 1 {
		err = VimeoNoResultsError
		return
	}

	title := strings.TrimSpace(result[0].Title)
	user := strings.TrimSpace(result[0].User)
	if title == "" || user == "" {
		err = VimeoEmptyResultsError
		return
	}

	_, notFound := GetFirstMatch(plug.spoiler, &title)
	if notFound != nil {
		plug.write <- IRCMessage{Channel: msg.Channel, User: msg.User, When: msg.When,
			Msg: "[Vimeo] " + html.UnescapeString(title+" uploaded by "+user)}
	} else {
		plug.write <- IRCMessage{Channel: msg.Channel, User: msg.User, When: msg.When,
			Msg: "[Vimeo] [[Title omitted due to possible spoilers]] uploaded by " + user}
	}

	return
}

func (plug Vimeo) Match(msg *IRCMessage) bool {
	return plug.match.MatchString(msg.Msg)
}

func (plug Vimeo) Event() chan IRCMessage {
	return plug.event
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<spring:beans xmlns="http://www.citrusframework.org/schema/testcase"
              xmlns:spring="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                  http://www.citrusframework.org/schema/testcase http://www.citrusframework.org/schema/testcase/citrus-testcase.xsd">
    <testcase name="CallTemplateParserTest">
        <actions>
            <call-template name="print">
                <parameter name="invalidParam"></parameter>
            </call-template>
        </actions>
    </testcase>

</spring:beans>


text:
namespace Cooking
{
    using System;
    using System.Collections.Generic;
    using Cooking.Food;

    public class Bowl
    {
        private IEnumerable<NaturalFood> products;

        public Bowl()
        {
            this.products = new List<NaturalFood>();
        }

        public void Add(NaturalFood product)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package org.jvnet.hyperjaxb3.ejb.strategy.model.base;

import org.jvnet.hyperjaxb3.ejb.schemas.customizations.JaxbContext;
import org.jvnet.hyperjaxb3.ejb.strategy.model.ProcessModel;
import org.jvnet.hyperjaxb3.xjc.generator.bean.field.SingleMarshallingReferenceField;
import org.jvnet.jaxb2_commons.util.OutlineUtils;

import com.sun.tools.xjc.generator.bean.ClassOutlineImpl;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.TypeUse;
import com.sun.tools.xjc.outline.FieldOutline;

public class AdaptSingleWildcardReference extends AbstractAdaptBuiltinPropertyInfo {

	public AdaptSingleWildcardReference(TypeUse propertyType) {
		super(propertyType);
	}

	@Override
	public String getDefaultGeneratedPropertyName(ProcessModel context,
			CPropertyInfo propertyInfo) {
		// TODO Allow for customization
		return propertyInfo.getName(true) + "Object";
	}

	@Override
	protected FieldOutline generateField(final ProcessModel context,
			CPropertyInfo core, ClassOutlineImpl classOutline,
			CPropertyInfo propertyInfo) {

		final JaxbContext jaxbContext = context.getCustomizing()
				.getJaxbContext(propertyInfo);

		final String contextPath = (jaxbContext == null || jaxbContext
				.getContextPath() == null) ? OutlineUtils
				.getContextPath(classOutline.parent()) : jaxbContext
				.getContextPath();

		final boolean _final = (jaxbContext == null
				|| jaxbContext.getField() == null || jaxbContext.getField()
				.isFinal() == null) ? true : jaxbContext.getField().isFinal();

		final SingleMarshallingReferenceField fieldOutline = new SingleMarshallingReferenceField(
				classOutline, propertyInfo, core, contextPath, _final);
		fieldOutline.generateAccessors();
		return fieldOutline;
	}
}


text:
package io.deepreader.java.commons.util.collections;

/*************************************************************************
 *  Compilation:  javac Stack.java
 *  Execution:    java Stack < input.txt
 *
 *  A generic stack, implemented using a singly-linked list.
 *  Each stack element is of type Item.
 *
 *  This version uses a static nested class Node (to save 8 bytes per
 *  Node), whereas the version in the textbook uses a non-static nested
 *  class (for simplicity).
 *
 *  % more tobe.txt
 *  to be or not to - be - - that - - - is
 *
 *  % java Stack < tobe.txt
 *  to be not that or be (2 left on stack)
 *
 *************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 *  The <tt>Stack</tt> class represents a last-in-first-out (LIFO) stack of generic items.
 *  It supports the usual push and pop operations, along with methods
 *  for peeking at the top item, testing if the stack is empty, and iterating through
 *  the items in LIFO order.
 *

 *  This implementation uses a singly-linked list with a static nested class for
 *  linked-list nodes. See {@link } LinkedStack for the version from the
 *  textbook that uses a non-static nested class.
 *  The push, pop, peek, size, and is-empty
 *  operations all take constant time in the worst case.
 *

 *  For additional documentation, see Section 1.3 of
 *  Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class Stack<Item> implements Iterable<Item> {
    private int N;                // size of the stack
    private Node<Item> first;     // top of stack

    // helper linked list class
    private static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    /**
     * Initializes an empty stack.
     */
    public Stack() {
        first = null;
        N = 0;
    }

    /**
     * Is this stack empty?
     * @return true if this stack is empty; false otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in the stack.
     * @return the number of items in the stack
     */
    public int size() {
        return N;
    }

    /**
     * Adds the item to this stack.
     * @param item the item to add
     */
    public void push(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    /**
     * Removes and returns the item most recently added to this stack.
     * @return the item most recently added
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        N--;
        return item;                   // return the saved item
    }

    /**
     * Returns (but does not remove) the item most recently added to this stack.
     * @return the item most recently added to this stack
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        return first.item;
    }

    /**
     * Returns a string representation of this stack.
     * @return the sequence of items in the stack in LIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this)
            s.append(item + " ");
        return s.toString();
    }

    // Iterator Sample
    /**
     * Returns an iterator to this stack that iterates through the items in LIFO order.
     * @return an iterator to this stack that iterates through the items in LIFO order.
     */
    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<Item>(first);
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator<Item> implements Iterator<Item> {
        private Node<Item> current;

        public ListIterator(Node<Item> first) {
            current = first;
        }

        @Override
        public boolean hasNext()  { return current != null;                     }

        @Override
        public void remove()      { throw new UnsupportedOperationException();  }

        @Override
        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    /**
     * Unit tests the <tt>Stack</tt> data type.
     */
    public static void main(String[] args) {
        Stack<String> s = new Stack<String>();
        Scanner sc = new Scanner(System.in);  // does not handle \n
        while (sc.hasNext()) {
            String item = sc.next();
            if (!item.equals("-"))
                s.push(item);
            else if (!s.isEmpty())
                System.out.print(s.pop() + " ");
        }
        System.out.println("(" + s.size() + " left on stack)");
    }
}


text:
Animated-Expanding-ListView
===========================

Animated Expanding ListView provides a fancy animation on expanding or collapsing the content of a listview item.

It works in all version of Android and it's very easy to adapt to your project.

## How to use with Gradle

Simply add the repository to your build.gradle file:
```groovy
repositories {
	jcenter()
	maven { url 'https://github.com/leonardocardoso/mvn-repo/raw/master/maven-deploy' }
}
```

And you can use the artifacts like this:
```groovy
dependencies {
	compile 'com.leocardz:aelv:1.1@aar'
	// ...
}
```

## Important

 Your list adapter must extend ArrayAdapter<? yourListItem ?>

 Your listview item must extend from AelvListItem

 Right after you create your listview item, you need to call yourItem.setUp(int collapsedHeight, int currentHeight, int expandedHeight, boolean isOpen); to setup the dimensions.

 Your listview item view holder must extend from AelvListViewHolder

 Right after you instantiate your view holder you need to call yourHolder.setViewWrap(viewWrap); and tell adapter that you are updating the item size calling holder.getViewWrap().setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, listItem.getCurrentHeight()));.

 Right before you return the view on your custom adapter, you must call yourItem.setHolder(yourHolder);

You need to instantiate Aelv aelv = new Aelv(isAccordion, animationDuration, yourListItems, yourListView, yourAdapter); right after you setup your listview.

Last thing: your must implement listview.setOnItemClickListener(); and insert this aelv.toggle(view, position); inside the listener and voilà!

Just check the app example to see it clearly.

For more details, visit http://android.leocardz.com/animated-expanding-listview/

![Normal](https://dl.dropbox.com/s/2uppozbz8436jrk/not_closing.gif)

![Accordion](https://dl.dropboxusercontent.com/s/guvz7me3tbx973g/accordion.gif)

Contact
=================================
If you are using this lib, let me know contacting me at android@leocardz.com then I add your app here in a list

License
=================================

    Copyright 2014 Leonardo Cardoso

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
using NUnit.Framework;
using RingCentral.Http;
using System.Linq;

namespace RingCentral.Test
{
    [TestFixture]
    class APIVersionsTest : BaseTest
    {
        [Test]
        public void BaseURL()
        {
            var request = new Request("/restapi/");
            var response = sdk.Platform.Get(request);
            var uriString = (string)response.GetJson().SelectToken("apiVersions").First().SelectToken("uriString");
            Assert.AreEqual("v1.0", uriString);
        }
    }
}


text:
import itertools
import subprocess
import sys

import pytest

from arca import Arca, Task, CurrentEnvironmentBackend
from arca.utils import logger
from arca.exceptions import BuildError
from common import BASE_DIR, RETURN_COLORAMA_VERSION_FUNCTION, SECOND_RETURN_STR_FUNCTION, TEST_UNICODE

def _pip_action(action, package):
    if action not in ["install", "uninstall"]:
        raise ValueError(f"{action} is invalid value for action")

    cmd = [sys.executable, "-m", "pip", action]

    if action == "uninstall":
        cmd += ["-y"]

    cmd += [package]

    logger.info("Installing requirements with command: %s", cmd)

    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    out_stream, err_stream = process.communicate()

    out_stream = out_stream.decode("utf-8")
    err_stream = err_stream.decode("utf-8")

    logger.debug("Return code is %s", process.returncode)
    logger.debug(out_stream)
    logger.debug(err_stream)

@pytest.mark.parametrize(
    ["requirements_location", "file_location"], list(itertools.product(
        (None, "requirements/requirements.txt"),
        (None, "test_package"),
    ))
)
def test_current_environment_backend(temp_repo_func, requirements_location, file_location):
    """ Tests the basic stuff around backends, if it can install requirements from more locations,
        launch stuff with correct cwd, works well with multiple branches, etc
    """
    kwargs = {}

    if requirements_location is not None:
        kwargs["requirements_location"] = requirements_location

    if file_location is not None:
        kwargs["cwd"] = file_location

    backend = CurrentEnvironmentBackend(verbosity=2, **kwargs)

    arca = Arca(backend=backend, base_dir=BASE_DIR)

    if file_location is None:
        filepath = temp_repo_func.file_path
    else:
        filepath = temp_repo_func.repo_path / file_location / "test_file.py"
        filepath.parent.mkdir(exist_ok=True, parents=True)
        temp_repo_func.file_path.replace(filepath)

        temp_repo_func.repo.index.remove([str(temp_repo_func.file_path)])
        temp_repo_func.repo.index.add([str(filepath)])
        temp_repo_func.repo.index.commit("Initial")

    task = Task("test_file:return_str_function")

    assert arca.run(temp_repo_func.url, temp_repo_func.branch, task).output == "Some string"

    filepath.write_text(SECOND_RETURN_STR_FUNCTION)
    temp_repo_func.repo.create_head("new_branch")
    temp_repo_func.repo.create_tag("test_tag")
    temp_repo_func.repo.index.add([str(filepath)])
    temp_repo_func.repo.index.commit("Updated function")

    assert arca.run(temp_repo_func.url, temp_repo_func.branch, task).output == TEST_UNICODE

    # in the other branch there's still the original
    assert arca.run(temp_repo_func.url, "new_branch", task).output == "Some string"
    # test that tags work as well
    assert arca.run(temp_repo_func.url, "test_tag", task).output == "Some string"

    temp_repo_func.repo.branches.master.checkout()

    requirements_path = temp_repo_func.repo_path / backend.requirements_location
    requirements_path.parent.mkdir(exist_ok=True, parents=True)
    requirements_path.write_text("colorama==0.3.9")

    filepath.write_text(RETURN_COLORAMA_VERSION_FUNCTION)

    temp_repo_func.repo.index.add([str(filepath), str(requirements_path)])
    temp_repo_func.repo.index.commit("Added requirements, changed to version")

    # check that it's not installed from previous tests
    _pip_action("uninstall", "colorama")

    with pytest.raises(ModuleNotFoundError):
        import colorama  # noqa

    # CurrentEnv fails because it ignores requirements
    with pytest.raises(BuildError):
        assert arca.run(temp_repo_func.url, temp_repo_func.branch, task).output == "0.3.9"

    # but when it's installed locally then it succeeds
    _pip_action("install", "colorama==0.3.9")

    assert arca.run(temp_repo_func.url, temp_repo_func.branch, task).output == "0.3.9"

    # cleanup

    _pip_action("uninstall", "colorama")

    with pytest.raises(ModuleNotFoundError):
        import colorama  # noqa


text:
@interface SYBViewController ()

@property (nonatomic, strong)SYBSignatureView *signView;

@end

@implementation SYBViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _signView = [[SYBSignatureView alloc] initWithFrame:CGRectMake(0, 0, 280, 280)];
    _signView.backgroundColor = [UIColor clearColor];
    _signView.center = self.view.center;
    [self.view addSubview:_signView];
    _signView.layer.borderColor = [[UIColor blackColor] CGColor];
    _signView.layer.borderWidth = 1.0f;

    UIButton *clean = [[UIButton alloc] initWithFrame:CGRectMake(20, 60, 240, 40)];
    [clean setTitle:@"clean" forState:UIControlStateNormal];
    [clean setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [clean addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clean];

    UIButton *save = [[UIButton alloc] initWithFrame:CGRectMake(20, 100, 240, 40)];
    [save setTitle:@"save" forState:UIControlStateNormal];
    [save setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [save addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:save];
}

- (void)cancel
{
    [_signView earseSignature];
}

- (void)save
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];

    NSString *filePath = [path stringByAppendingString:@"demo.svg"];

    //get svg file
    NSData *svgfile = [_signView getSvgFile];
    NSError *error;

    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
    [svgfile writeToFile:filePath options:NSDataWritingAtomic error: &error];

    if (error) {
        NSLog(@"save %@ has error %@", filePath, error);
    } else {
        NSLog(@"the svg file has saved as %@ ", filePath);
    }
}
@end


text:
require 'test_helper'

class StaticPagesControllerTest < ActionController::TestCase
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
F-Index
</TITLE>

<META NAME="date" CONTENT="2013-03-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M O P R S V W X

F

FieldAnnotationInflater - Class in self.philbrown.AbLE.annotations
This class handles declared fields during layout inflation.
FieldAnnotationInflater(AbLEActivity) -
Constructor for class self.philbrown.AbLE.annotations.FieldAnnotationInflater

Instantiate the inflater

findViewById(int) -
Method in class self.philbrown.AbLE.AbLEActivity

This is a replacement for Activity#findViewById(int), that handles the id query
 based on the annotations-based layout scheme.

format(String, Object...) -
Static method in class self.philbrown.AbLE.AbLEUtil

Handles String format for the default (US) Locale.

formatStackTrace(StackTraceElement) -
Static method in class self.philbrown.AbLE.AbLEUtil

Formats a stack trace into a single line that provides relevant information for debugging

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M O P R S V W X


text:
[![CI Status](http://img.shields.io/travis/Casey Brumbaugh/CBCompare.svg?style=flat)](https://travis-ci.org/Casey Brumbaugh/CBCompare)
[![Version](https://img.shields.io/cocoapods/v/CBCompare.svg?style=flat)](http://cocoapods.org/pods/CBCompare)
[![License](https://img.shields.io/cocoapods/l/CBCompare.svg?style=flat)](http://cocoapods.org/pods/CBCompare)
[![Platform](https://img.shields.io/cocoapods/p/CBCompare.svg?style=flat)](http://cocoapods.org/pods/CBCompare)

![Alt text](/../screenshots/demo.gif?raw=true "Demo")

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

CBCompare is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "CBCompare"
```

## Author

Casey Brumbaugh, caseybbrumbaugh@gmail.com

## License

CBCompare is available under the MIT license. See the LICENSE file for more info.