text:
var chai = require('chai');
var assert = chai.assert;

var defaultConfig = require('../config/defaults');

var Worker = require('../lib/worker');
var Monitor = require('../lib/monitor');

describe('Worker', function () {
    var testWorker = null, testMonitor = null;

    before(function () {
        testMonitor = new Monitor();
        testMonitor.start();
        defaultConfig.refreshRate = 10;
    });

    beforeEach(function getTestWorker() {
        testMonitor.clear();
        testWorker = new Worker({refreshRate: 10});
    });

    afterEach(function (done) {
        testWorker.stop(done);
    });

    after(function () {
        testMonitor.stop();
        testMonitor = null;
        testWorker = null;
    });

    it('should construct default worker', function () {
        assert.isNotNull(testWorker, 'worker object is NULL');
    });

    it('should construct default worker monitor', function () {
        assert.isNotNull(testMonitor, 'worker monitor object is NULL');
    });

    it('should contain default config', function () {
        assert.deepEqual(testWorker.config, defaultConfig, 'config object does not equal to defaults');
    });

    it('should not be active by default', function () {
        assert.isFalse(testWorker.active, 'active flag should be true');
    });

    it('should be startable', function () {
        testWorker.start();
        assert.isTrue(testWorker.active, 'active flag should be false after pausing');
    });

    it('should be able to pause from active state', function () {
        testWorker.start();
        testWorker.pause();

        assert.isFalse(testWorker.active, 'active flag should be true after resuming work');
    });

    it('should create a job with no data', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            worker.createJob('testJob', {}, function (job) {
                assert.equal(JSON.stringify(job.data), '{}', 'data object should not be null when no data was supplied');
                done();
            });
        });
    });

    it('should get an existing job object', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            worker.createJob('testJob', {}, function (job) {
                worker.getJob('testJob', 1, function (existingJob) {
                    assert.deepEqual(job, existingJob, 'existing job should be equal to created job');
                    done();
                });
            });
        });
    });

    it('should get all queues stats', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            worker.process('testJob2', function (job, jobDone) {
                jobDone();
            });

            worker.getStats(function (stats) {
                assert.deepEqual(stats, [
                    {type: 'testJob', active: 0, pending: 0, success: 0, failed: 0, avg_duration: null},
                    {type: 'testJob2', active: 0, pending: 0, success: 0, failed: 0, avg_duration: null}
                ], 'stats object should contain 2 queues');
                done();
            });
        });
    });

    it('should know how to process jobs of type \'testJob\'', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            assert.isDefined(worker.queues['testJob'], 'no definition for \'testJob\' exists');
            assert.equal(worker.queues['testJob'].concurrency, 1, 'default concurrency definition should be 1');
            done();
        });
    });

    it('should calculate free work slots', function () {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            var slots = worker.getFreeSlots();
            assert.deepEqual(slots, [
                {type: 'testJob', available: 1}
            ], 'testJob should have 1 free slots');
        });
    });

    it('should process concurrency correctly', function () {
        testWorker.ready(function (worker) {
            worker.process('testJob', 10, function (job, jobDone) {
                jobDone();
            });

            var slots = worker.getFreeSlots();
            assert.equal(
                JSON.stringify(slots),
                JSON.stringify([
                    {type: 'testJob', available: 10}
                ]),
                'testJob should have 10 free slots');
        });
    });

    it('should create a valid done method for job processing', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', 10, function (job, jobDone) {
                jobDone();
            });

            worker.createJob('testJob', {}, function (job) {
                var doneMethod = worker.createDoneMethod(job);

                assert.isFunction(doneMethod, 'done method must be a function');
                done();
            });
        });
    });

    it('should create a done method for failed job processing', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
            });

            worker.createJob('testJob', {}, function (job) {
                var doneMethod = worker.createDoneMethod(job, function () {
                    testWorker.getJob(job.type, job.id, function (doneJob) {
                        assert.equal(doneJob.status, 'failed', 'job should fail when providing done method with an error');
                        assert.equal(doneJob.err, 'testing message', 'error should reflect the message input in done method');
                        done();
                    });
                });

                doneMethod('testing message');
            });
        });
    });

    it('should create a done method for successful job processing', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            worker.createJob('testJob', {}, function (job) {
                var doneMethod = worker.createDoneMethod(job, function () {
                    testWorker.getJob(job.type, job.id, function (doneJob) {
                        assert.equal(doneJob.status, 'success', 'job should succeed when providing proper done method');
                        done();
                    });
                });

                doneMethod();
            });
        });
    });

    it('should report correct job end time', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone();
            });

            worker.createJob('testJob', {}, function (job) {
                var doneMethod = worker.createDoneMethod(job, function () {
                    testWorker.getJob(job.type, job.id, function (doneJob) {
                        assert.isNotNull(doneJob.endTime, 'job should succeed when providing proper done method');
                        done();
                    });
                });

                doneMethod();
            });
        });
    });

    it('should fetch a job result', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (innerJob, jobDone) {
                jobDone(null, {result: 1});
            });

            worker.createJob('testJob', {}, function (job) {
                var jobStatusCheck = setInterval(function () {
                    worker.getJob(job.type, job.id, function (innerJob) {
                        if (innerJob.status === 'success') {
                            clearInterval(jobStatusCheck);
                            worker.getJobResult(innerJob.type, innerJob.id, function (result) {
                                assert.deepEqual(result, {result: 1}, 'job did not execute properly');
                                done();
                            });
                        }
                    });
                }, 20);
            });

            worker.start();
        });
    });

    it('should fetch an empty result from a job without results', function (done) {
        testWorker.ready(function (worker) {
            worker.createJob('testJob2', {}, function (job) {
                worker.getJobResult(job.type, job.id, function (result) {
                    assert.deepEqual(result, [], 'job did not execute properly');
                    done();
                });
            });
        });
    });

    it('should wait for all child jobs to complete', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (innerJob, jobDone) {
                jobDone(null, {result: 2});
            });

            worker.process('testJobChildren', function (job, jobDone) {
                worker.createJob('testJob', {}, function (childJob) {
                    job.addChild(childJob);

                    job.waitForChildren(function (result) {
                        assert.deepEqual(result, [
                            {result: 2}
                        ]);
                        jobDone();
                        done();
                    });
                });
            });
            worker.createJob('testJobChildren', {});
            worker.start();
        });
    });

    it('should wait for all child jobs to fail', function (done) {
        testWorker.ready(function (worker) {
            worker.process('testJob', function (job, jobDone) {
                jobDone('error');
            });

            worker.process('testJobChildren', function (job, jobDone) {
                worker.createJob('testJob', {}, function (childJob) {
                    job.addChild(childJob);

                    job.waitForChildren(function (result) {
                        jobDone();
                        done();
                    });
                });
            });
            worker.createJob('testJobChildren', {});
            worker.start();
        });
    });

    it('should crash job with unhandled exception', function (done) {
        testWorker.ready(function (worker) {
            worker.process('crashingJob', function (job, jobDone) {
                throw(new Error('crashed due to unhandled exception'));
            });

            worker.createJob('crashingJob', {}, function (job) {
                var jobInterval = setInterval(function () {
                    testWorker.getJob(job.type, job.id, function (updatedJob) {
                        if (updatedJob.status === 'crashed') {
                            clearInterval(jobInterval);
                            assert.equal(updatedJob.err, 'Error: crashed due to unhandled exception', 'error object should hold the details of the unhandled exception');
                            done();
                        }
                    });
                }, 100);
            });

            worker.start();
        });
    });

    it('should remove expired job objects', function (done) {
        testWorker.config.job.ttl = 0;
        testWorker.ready(function (worker) {
            worker.process('testCleanUpJob', function (job, jobDone) {
                assert.equal(worker.queues['testCleanUpJob'].jobs.length, 1, 'worker queue should contain 1 instance of \'testCleanUpJob\'');
                worker.activeJobCleanUp();
                assert.equal(worker.queues['testCleanUpJob'].jobs.length, 0, 'worker queue should contain no instance of \'testCleanUpJob\' after clean up');
                jobDone();
                done();
            });

            worker.start();
            worker.createJob('testCleanUpJob');
        });
    });

    it('should remove job from monitor on success', function (done) {
        testWorker.ready(function (worker) {
            worker.process('removedJob', function (job, jobDone) {
                jobDone();
            }, true);

            worker.createJob('removedJob', {}, function (job) {
                var jobInterval = setInterval(function () {
                    testWorker.getJob(job.type, job.id, function (updatedJob) {
                        if (updatedJob.err === 'No job found matching the criteria (type: removedJob, id: 1)') {
                            clearInterval(jobInterval);
                            assert.equal(updatedJob.err, 'No job found matching the criteria (type: removedJob, id: 1)');
                            done();
                        }
                    });
                }, 100);
            });

            worker.start();
        });
    });
});


text:
<BroadcastMonitor>
  <updated>2015-08-03T22:27:57</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-03T22:27:57</startTime>
    <itemId>1000080561:1242610</itemId>
    <titleId>216138805</titleId>
    <itemCode>10657</itemCode>
    <itemReference></itemReference>
    <titleName>Chapman For President</titleName>
    <artistName>Eef van Breen</artistName>
    <albumName></albumName>
    <CategoryCode>888</CategoryCode>
    <CategoryName>MUZIEK</CategoryName>
    <itemDuration>235</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-03T22:31:53</startTime>
    <itemId>1000080561:1242604</itemId>
    <titleId>216138807</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>Chapman (DE BUS)</titleName>
    <artistName>Eef van Breen</artistName>
    <albumName></albumName>
    <CategoryCode>888</CategoryCode>
    <CategoryName>MUZIEK</CategoryName>
    <itemDuration>128</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

void extract_error(char *fn,
		   SQLHANDLE handle,
		   SQLSMALLINT type)
{
  SQLINTEGER i = 0;
  SQLINTEGER native;
  SQLCHAR state[ 7 ];
  SQLCHAR text[256];
  SQLSMALLINT len;
  SQLRETURN ret;

  fprintf(stderr,
	  "\n"
	  "The driver reported the following diagnostics whilst running "
	  "%s\n\n",
	  fn);

  do
    {
      ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
			  sizeof(text), &len );
      if (SQL_SUCCEEDED(ret))
	printf("%s:%ld:%ld:%s\n", state, i, native, text);
    }
  while( ret == SQL_SUCCESS );
}

main() {
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret; /* ODBC API return status */
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;

  /* Allocate an environment handle */
  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
  /* We want ODBC 3 support */
  SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
  /* Allocate a connection handle */
  SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
  /* Connect to the DSN mydsn */
  ret = SQLDriverConnect(dbc, NULL, "DSN=odbc_tutorial;", SQL_NTS,
			 outstr, sizeof(outstr), &outstrlen,
			 SQL_DRIVER_COMPLETE);
  if (SQL_SUCCEEDED(ret)) {
    printf("Connected\n");
    printf("Returned connection string was:\n\t%s\n", outstr);
    if (ret == SQL_SUCCESS_WITH_INFO) {
      printf("Driver reported the following diagnostics\n");
      extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
    }
    SQLDisconnect(dbc);/* disconnect from driver */
  } else {
    fprintf(stderr, "Failed to connect\n");
    extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
  }
  /* free up allocated handles */
  SQLFreeHandle(SQL_HANDLE_DBC, dbc);
  SQLFreeHandle(SQL_HANDLE_ENV, env);
}


text:
package quic

import (
	"errors"
	"fmt"
	"sync"

	"github.com/lucas-clemente/quic-go/handshake"
	"github.com/lucas-clemente/quic-go/protocol"
	"github.com/lucas-clemente/quic-go/qerr"
)

type streamsMap struct {
	mutex sync.RWMutex

	perspective          protocol.Perspective
	connectionParameters handshake.ConnectionParametersManager

	streams map[protocol.StreamID]*stream
	// needed for round-robin scheduling
	openStreams     []protocol.StreamID
	roundRobinIndex uint32

	nextStream                protocol.StreamID // StreamID of the next Stream that will be returned by OpenStream()
	highestStreamOpenedByPeer protocol.StreamID
	nextStreamOrErrCond       sync.Cond
	openStreamOrErrCond       sync.Cond

	closeErr           error
	nextStreamToAccept protocol.StreamID

	newStream newStreamLambda

	numOutgoingStreams uint32
	numIncomingStreams uint32
}

type streamLambda func(*stream) (bool, error)
type newStreamLambda func(protocol.StreamID) *stream

var (
	errMapAccess = errors.New("streamsMap: Error accessing the streams map")
)

func newStreamsMap(newStream newStreamLambda, pers protocol.Perspective, connectionParameters handshake.ConnectionParametersManager) *streamsMap {
	sm := streamsMap{
		perspective:          pers,
		streams:              map[protocol.StreamID]*stream{},
		openStreams:          make([]protocol.StreamID, 0),
		newStream:            newStream,
		connectionParameters: connectionParameters,
	}
	sm.nextStreamOrErrCond.L = &sm.mutex
	sm.openStreamOrErrCond.L = &sm.mutex

	if pers == protocol.PerspectiveClient {
		sm.nextStream = 1
		sm.nextStreamToAccept = 2
	} else {
		sm.nextStream = 2
		sm.nextStreamToAccept = 1
	}

	return &sm
}

// GetOrOpenStream either returns an existing stream, a newly opened stream, or nil if a stream with the provided ID is already closed.
// Newly opened streams should only originate from the client. To open a stream from the server, OpenStream should be used.
func (m *streamsMap) GetOrOpenStream(id protocol.StreamID) (*stream, error) {
	m.mutex.RLock()
	s, ok := m.streams[id]
	m.mutex.RUnlock()
	if ok {
		return s, nil // s may be nil
	}

	// ... we don't have an existing stream
	m.mutex.Lock()
	defer m.mutex.Unlock()
	// We need to check whether another invocation has already created a stream (between RUnlock() and Lock()).
	s, ok = m.streams[id]
	if ok {
		return s, nil
	}

	if m.perspective == protocol.PerspectiveServer {
		if id%2 == 0 {
			if id <= m.nextStream { // this is a server-side stream that we already opened. Must have been closed already
				return nil, nil
			}
			return nil, qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("attempted to open stream %d from client-side", id))
		}
		if id <= m.highestStreamOpenedByPeer { // this is a client-side stream that doesn't exist anymore. Must have been closed already
			return nil, nil
		}
	}
	if m.perspective == protocol.PerspectiveClient {
		if id%2 == 1 {
			if id <= m.nextStream { // this is a client-side stream that we already opened.
				return nil, nil
			}
			return nil, qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("attempted to open stream %d from server-side", id))
		}
		if id <= m.highestStreamOpenedByPeer { // this is a server-side stream that doesn't exist anymore. Must have been closed already
			return nil, nil
		}
	}

	// sid is the next stream that will be opened
	sid := m.highestStreamOpenedByPeer + 2
	// if there is no stream opened yet, and this is the server, stream 1 should be openend
	if sid == 2 && m.perspective == protocol.PerspectiveServer {
		sid = 1
	}

	for ; sid <= id; sid += 2 {
		_, err := m.openRemoteStream(sid)
		if err != nil {
			return nil, err
		}
	}

	m.nextStreamOrErrCond.Broadcast()
	return m.streams[id], nil
}

func (m *streamsMap) openRemoteStream(id protocol.StreamID) (*stream, error) {
	if m.numIncomingStreams >= m.connectionParameters.GetMaxIncomingStreams() {
		return nil, qerr.TooManyOpenStreams
	}
	if id+protocol.MaxNewStreamIDDelta < m.highestStreamOpenedByPeer {
		return nil, qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("attempted to open stream %d, which is a lot smaller than the highest opened stream, %d", id, m.highestStreamOpenedByPeer))
	}

	if m.perspective == protocol.PerspectiveServer {
		m.numIncomingStreams++
	} else {
		m.numOutgoingStreams++
	}

	if id > m.highestStreamOpenedByPeer {
		m.highestStreamOpenedByPeer = id
	}

	s := m.newStream(id)
	m.putStream(s)
	return s, nil
}

func (m *streamsMap) openStreamImpl() (*stream, error) {
	id := m.nextStream
	if m.numOutgoingStreams >= m.connectionParameters.GetMaxOutgoingStreams() {
		return nil, qerr.TooManyOpenStreams
	}

	if m.perspective == protocol.PerspectiveServer {
		m.numOutgoingStreams++
	} else {
		m.numIncomingStreams++
	}

	m.nextStream += 2
	s := m.newStream(id)
	m.putStream(s)
	return s, nil
}

// OpenStream opens the next available stream
func (m *streamsMap) OpenStream() (*stream, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	if m.closeErr != nil {
		return nil, m.closeErr
	}
	return m.openStreamImpl()
}

func (m *streamsMap) OpenStreamSync() (*stream, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	for {
		if m.closeErr != nil {
			return nil, m.closeErr
		}
		str, err := m.openStreamImpl()
		if err == nil {
			return str, err
		}
		if err != nil && err != qerr.TooManyOpenStreams {
			return nil, err
		}
		m.openStreamOrErrCond.Wait()
	}
}

// AcceptStream returns the next stream opened by the peer
// it blocks until a new stream is opened
func (m *streamsMap) AcceptStream() (*stream, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	var str *stream
	for {
		var ok bool
		if m.closeErr != nil {
			return nil, m.closeErr
		}
		str, ok = m.streams[m.nextStreamToAccept]
		if ok {
			break
		}
		m.nextStreamOrErrCond.Wait()
	}
	m.nextStreamToAccept += 2
	return str, nil
}

func (m *streamsMap) Iterate(fn streamLambda) error {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	openStreams := append([]protocol.StreamID{}, m.openStreams...)

	for _, streamID := range openStreams {
		cont, err := m.iterateFunc(streamID, fn)
		if err != nil {
			return err
		}
		if !cont {
			break
		}
	}
	return nil
}

// RoundRobinIterate executes the streamLambda for every open stream, until the streamLambda returns false
// It uses a round-robin-like scheduling to ensure that every stream is considered fairly
// It prioritizes the crypto- and the header-stream (StreamIDs 1 and 3)
func (m *streamsMap) RoundRobinIterate(fn streamLambda) error {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	numStreams := uint32(len(m.streams))
	startIndex := m.roundRobinIndex

	for _, i := range []protocol.StreamID{1, 3} {
		cont, err := m.iterateFunc(i, fn)
		if err != nil && err != errMapAccess {
			return err
		}
		if !cont {
			return nil
		}
	}

	for i := uint32(0); i < numStreams; i++ {
		streamID := m.openStreams[(i+startIndex)%numStreams]
		if streamID == 1 || streamID == 3 {
			continue
		}

		cont, err := m.iterateFunc(streamID, fn)
		if err != nil {
			return err
		}
		m.roundRobinIndex = (m.roundRobinIndex + 1) % numStreams
		if !cont {
			break
		}
	}
	return nil
}

func (m *streamsMap) iterateFunc(streamID protocol.StreamID, fn streamLambda) (bool, error) {
	str, ok := m.streams[streamID]
	if !ok {
		return true, errMapAccess
	}
	return fn(str)
}

func (m *streamsMap) putStream(s *stream) error {
	id := s.StreamID()
	if _, ok := m.streams[id]; ok {
		return fmt.Errorf("a stream with ID %d already exists", id)
	}

	m.streams[id] = s
	m.openStreams = append(m.openStreams, id)
	return nil
}

// Attention: this function must only be called if a mutex has been acquired previously
func (m *streamsMap) RemoveStream(id protocol.StreamID) error {
	s, ok := m.streams[id]
	if !ok || s == nil {
		return fmt.Errorf("attempted to remove non-existing stream: %d", id)
	}

	if id%2 == 0 {
		m.numOutgoingStreams--
	} else {
		m.numIncomingStreams--
	}

	for i, s := range m.openStreams {
		if s == id {
			// delete the streamID from the openStreams slice
			m.openStreams = m.openStreams[:i+copy(m.openStreams[i:], m.openStreams[i+1:])]
			// adjust round-robin index, if necessary
			if uint32(i) < m.roundRobinIndex {
				m.roundRobinIndex--
			}
			break
		}
	}

	delete(m.streams, id)
	m.openStreamOrErrCond.Signal()
	return nil
}

func (m *streamsMap) CloseWithError(err error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	m.closeErr = err
	m.nextStreamOrErrCond.Broadcast()
	m.openStreamOrErrCond.Broadcast()
	for _, s := range m.openStreams {
		m.streams[s].Cancel(err)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 	<!-- Spring MVC配置 -->
    <context:annotation-config />
	<!-- 开启aop,对类代理 -->
	<aop:config proxy-target-class="true"></aop:config>
	<!-- 开启shiro注解支持 -->
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>

	<!-- 配置自定扫描的包 -->
	<context:component-scan base-package="com.hwh" use-default-filters="false">
		 <context:include-filter type="annotation"
                expression="org.springframework.stereotype.Controller"/>
         <context:include-filter type="annotation"
                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>

	<!-- spring会用默认的Servlet来响应静态文件 -->
	 <mvc:default-servlet-handler/>

	<!-- 把images/**映射到ResourceHttpRequestHandler进行处理 -->
	<mvc:resources mapping="js/**" location="js/"/>
    <mvc:resources mapping="css/**" location="css/"/>
    <mvc:resources mapping="images/**" location="images/"/>
    <mvc:resources mapping="easyui/**" location="easyui/"/>
    <mvc:resources mapping="index.html" location="index.html"/>
 	<!-- 在实际开发中通常都需配置 mvc:annotation-driven 标签 -->
 	<!-- 支持注解的handlerMapping\adpater\exceptionResolver等 -->
 	<!-- 支持@conversionService和校验的注
 	 -->
 	<!-- 使得在配置view-controller时handlerMapping也能起作用 -->
	<mvc:annotation-driven></mvc:annotation-driven>
<!-- 	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>	 -->

	<!-- 配置 ConversionService -->
<!-- 	<bean id="conversionService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<ref bean="employeeConverter"/>
			</set>
		</property>
	</bean> -->

	<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/view/" />
		<property name="suffix" value=".jsp" />
		<!-- <property name="order" value="20"></property>  -->
	</bean>

	<!-- 配置视图 BeanNameViewResolver 解析器: 使用视图的名字来解析视图 -->
	<!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 -->
	<!-- 不定义默认为最大值 -->
	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
		<property name="order" value="100"></property>
	</bean>

	<!-- 配置国际化资源文件 -->
	<!-- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18n"></property>
	</bean> -->

	<!-- 定义统一异常处理器 -->
	<bean class="com.hwh.exception.CustomExceptionResolver"></bean>

	<!-- 配置直接转发的页面 -->
	<!-- 可以直接相应转发的页面, 而无需再经过 Handler 的方法. -->
	<!-- <mvc:view-controller path="/log/login" view-name="login"/> -->
	<mvc:view-controller path="/test" view-name="index1"/>
</beans>


text:
import { Component } from '@angular/core';
import * as RealtimeRx from 'realtime-rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  message = 'Waiting for Realtime message ...';

  constructor() {
    // Instantiates a new Realtime client connection
    const rxConnection = new RealtimeRx.ObservableConnection();

    // Sets the connection metadata (optional)
    rxConnection.setConnectionMetadata("Realtime RxJs example");

    // Establishes the connection to the Realtime server
    // Note: we are using our demo appkey, you should replace it with your own Realtime appkey
    rxConnection.connect("2Ze1dz", "token");

    // Observe channel and subscribe to receive messages
    rxConnection.observeChannel("myChannel")
      .subscribe((message) => {
        console.log("Received message: " + message);

        // Add message to the component title
        this.message = message;
      });

    // Send a message
    rxConnection.send("myChannel", "... and Realtime Observables are working too!")
  }
}


text:
package com.example.shuip.talk.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.shuip.talk.R;
import com.example.shuip.talk.db.dao.service.ContactService;
import com.example.shuip.talk.db.dao.service.RequestMsgService;
import com.example.shuip.talk.http.BaseResponse;
import com.example.shuip.talk.http.RequestListener;
import com.example.shuip.talk.http.VolleyHttpClient;
import com.example.shuip.talk.model.Contact;
import com.example.shuip.talk.model.RequestAnswerMsg;
import com.example.shuip.talk.model.RequestMsg;
import com.example.shuip.talk.sys.Constant;
import com.example.shuip.talk.util.ImageUtil;
import com.example.shuip.talk.util.Pinyin4j;
import com.example.shuip.util.android.PreferencesUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 15-9-22.
 */
public class RequestMsgAdapter extends AbstractAdapter<RequestMsg> {

    private VolleyHttpClient mHttpClient;
    private ContactService mContactService;
    private RequestMsgService mRequestMsgService;

    public RequestMsgAdapter(Context context, List<RequestMsg> datas) {
        super(context, datas);
        this.mHttpClient = new VolleyHttpClient(context);
        this.mContactService = ContactService.getInstance();
        this.mRequestMsgService = RequestMsgService.getInstance();
    }

    @Override
    IViewHolder<RequestMsg> getViewHolder(int viewType) {
        return new ViewHolder();
    }

    @Override
    int getViewLayout(int viewType) {
        return R.layout.template_request_msg;
    }

    private final class ViewHolder implements IViewHolder<RequestMsg>{
        private TextView txtName;
        private TextView txtHandle;
        private TextView txtMsg;
        private Button btnHandle;
        private ImageView imageviewHead;
        @Override
        public void bindData(final RequestMsg msg, final int position) {
            txtName.setText(msg.getContactname());
            String requestMsg = TextUtils.isEmpty(msg.getRequestmsg()) ? mContext.getString(R.string.friend_ask_you_be) : msg.getRequestmsg();
            txtMsg.setText(requestMsg);

            if (msg.getStatus() == RequestMsg.STATUS_UN_HANDLE){
                btnHandle.setVisibility(View.VISIBLE);
                txtHandle.setVisibility(View.GONE);

                btnHandle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        acceptRequest(msg, position);
                    }
                });
            }else {
                btnHandle.setVisibility(View.GONE);
                txtHandle.setVisibility(View.VISIBLE);
                if (msg.getStatus() == RequestMsg.STATUS_AGREE){
                    txtHandle.setText(R.string.accepted);
                }else if (msg.getStatus() == RequestMsg.STATUS_REFUSE){
                    txtHandle.setText(R.string.refused);
                }
            }

            ImageUtil.displayImageUseDefOption(msg.getContactheadmid(),imageviewHead);
        }

        private void acceptRequest(final RequestMsg msg, final int position) {
            Map<String,String> params = new HashMap<String,String>();
            params.put("requestid",msg.getRequestid() + "");
            params.put("answer", RequestAnswerMsg.TYPE_AGREE + "");
            params.put("token", PreferencesUtils.getString(mContext, Constant.ACCESS_TOKEN));

            mHttpClient.post(Constant.API.URL_FRIENDS_REQUEST_ANSWER, params, R.string.sending, new RequestListener() {
                @Override
                public void onPreRequest() {

                }

                @Override
                public void onRequestSuccess(BaseResponse response) {
                    if (response.isSuccess()) {
                        msg.setStatus(RequestMsg.STATUS_AGREE);
                        mRequestMsgService.update(msg);

                        saveFriend(msg);

                        mDatas.remove(msg);
                        mDatas.add(position,msg);
                        notifyDataSetChanged();
                    }
                }

                @Override
                public void onRequestError(int code, String msg) {

                }

                @Override
                public void onRequestFail(int code, String msg) {

                }
            });
        }

        private void saveFriend(RequestMsg msg) {
            Contact friend = new Contact();
            friend.setMemberid(msg.getMemberid());
            friend.setContactid(msg.getContactid());

            friend.setPinyin(Pinyin4j.getPingYin(msg.getContactname(), true).toUpperCase());
            friend.setCreatetime(new Date());
            friend.setEmail(msg.getContactemail());
            friend.setName(msg.getContactname());
            friend.setHeadbig(msg.getContactheadbig());
            friend.setHeadmid(msg.getContactheadmid());
            friend.setHeadsmall(msg.getContactheadsmall());

            mContactService.save(friend);
        }
    }
}


text:
package io.reneses.tela.core.dispatcher.exceptions;

/**
 * ActionBadDefinedException class.
 */
public class ActionBadDefinedException extends IllegalArgumentException {

    /**
     * Constructor for ActionBadDefinedException.
     *
     * @param actionName Action name
     */
    public ActionBadDefinedException(String actionName) {
        super("The action '" + actionName + "' is bad defined");
    }

    /**
     * Constructor for ActionBadDefinedException.
     *
     * @param actionName Action name
     * @param message Error message
     */
    public ActionBadDefinedException(String actionName, String message) {
        super("The action '" + actionName + "' is bad defined: " + message);
    }
}


text:
package uk.gov.dstl.baleen.annotators.templates;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.resource.ResourceInitializationException;
import org.junit.Before;
import org.junit.Test;

import uk.gov.dstl.baleen.types.templates.TemplateField;
import uk.gov.dstl.baleen.types.templates.TemplateRecord;

public class TemplateValidatorTest extends AbstractRecordAnnotatorTest {

  public TemplateValidatorTest() {
    super(TemplateValidator.class);
  }

  @Override
  @Before
  public void setup() throws IOException {
    super.setup();

    TemplateRecord otherRecord = new TemplateRecord(jCas);
    otherRecord.setBegin(53);
    otherRecord.setEnd(105);
    otherRecord.setName("otherRecord");
    otherRecord.setSource("other");
    otherRecord.addToIndexes();

    TemplateField otherField = new TemplateField(jCas);
    otherField.setBegin(53);
    otherField.setEnd(68);
    otherField.setName("otherField");
    otherField.setSource("other");
    otherField.setValue("default");
    otherField.addToIndexes();
  }

  @Test
  public void testRecordWithAllFieldsRemains()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);
    addOptionalField(source);
    addRequiredField(source);

    try {
      processJCas(TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY, tempDirectory.toString());

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(1, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(2, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithOnlyRequiredFiledRemains()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);
    addRequiredField(source);

    try {
      processJCas(TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY, tempDirectory.toString());

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(1, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(1, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsRemoved()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);

    try {
      processJCas(TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY, tempDirectory.toString());

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(0, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(0, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsRemovedWhenSourceSpecified()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);

    try {
      processJCas(
          TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY,
          tempDirectory.toString(),
          TemplateValidator.PARAM_SOURCE,
          source);

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(0, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(0, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsRemovedWhenRecordSpecified()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);

    try {
      processJCas(
          TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY,
          tempDirectory.toString(),
          TemplateValidator.PARAM_RECORDS,
          new String[] {"record"});

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(0, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(0, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsRemovedWhenSourceAndRecordSpecified()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);

    try {
      processJCas(
          TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY,
          tempDirectory.toString(),
          TemplateValidator.PARAM_SOURCE,
          source,
          TemplateValidator.PARAM_RECORDS,
          new String[] {"record"});

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(0, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(0, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsNotRemovedWhenOtherSourceSpecified()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);
    addOptionalField(source);

    try {
      processJCas(
          TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY,
          tempDirectory.toString(),
          TemplateValidator.PARAM_SOURCE,
          "other",
          TemplateValidator.PARAM_RECORDS,
          new String[] {"record"});

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(1, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(1, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testRecordWithMissingRequiredFieldIsNotRemovedWhenOtherRecordSpecified()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();
    String source = definitionFile.toFile().getName();
    addRecord(source);
    addOptionalField(source);

    try {
      processJCas(
          TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY,
          tempDirectory.toString(),
          TemplateValidator.PARAM_SOURCE,
          source,
          TemplateValidator.PARAM_RECORDS,
          new String[] {"other"});

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(1, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(1, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  @Test
  public void testOptionalFieldsFromRecordWithMissingRequiredFiledAreRemoved()
      throws AnalysisEngineProcessException, ResourceInitializationException, IOException {

    Path definitionFile = createRecordDefinitionWithRequiredField();

    String source = definitionFile.toFile().getName();
    addRecord(source);
    addOptionalField(source);

    try {
      processJCas(TemplateAnnotator.PARAM_RECORD_DEFINITIONS_DIRECTORY, tempDirectory.toString());

      Collection<TemplateRecord> records =
          removeOtherRecord(JCasUtil.select(jCas, TemplateRecord.class));
      assertEquals(0, records.size());

      Collection<TemplateField> fields =
          removeOtherField(JCasUtil.select(jCas, TemplateField.class));
      assertEquals(0, fields.size());

    } finally {
      Files.delete(definitionFile);
    }
  }

  private Collection<TemplateRecord> removeOtherRecord(Collection<TemplateRecord> selected) {
    Collection<TemplateRecord> remaining = new ArrayList<>();
    for (TemplateRecord r : selected) {
      if (!"otherRecord".equals(r.getName())) {
        remaining.add(r);
      }
    }
    assertTrue(remaining.size() < selected.size());
    return remaining;
  }

  private Collection<TemplateField> removeOtherField(Collection<TemplateField> selected) {
    Collection<TemplateField> remaining = new ArrayList<>();
    for (TemplateField r : selected) {
      if (!"otherField".equals(r.getName())) {
        remaining.add(r);
      }
    }
    assertTrue(remaining.size() < selected.size());
    return remaining;
  }

  private Path createRecordDefinitionWithRequiredField() throws IOException {
    TemplateFieldConfiguration notRequiredField =
        new TemplateFieldConfiguration("optional", "Paragraph:nth-of-type(3)");
    TemplateFieldConfiguration requiredField =
        new TemplateFieldConfiguration("required", "Paragraph:nth-of-type(2)");
    requiredField.setRequired(true);
    return createRecord("record", notRequiredField, requiredField);
  }

  private void addRecord(String source) {
    TemplateRecord record1 = new TemplateRecord(jCas);
    record1.setBegin(52);
    record1.setEnd(212);
    record1.setName("record");
    record1.setSource(source);
    record1.addToIndexes();
  }

  private void addRequiredField(String source) {
    TemplateField field = new TemplateField(jCas);
    field.setBegin(53);
    field.setEnd(105);
    field.setName("required");
    field.setSource(source);
    field.setValue(PARA2);
    field.addToIndexes();
  }

  private void addOptionalField(String source) {
    TemplateField field = new TemplateField(jCas);
    field.setBegin(122);
    field.setEnd(125);
    field.setName("optional");
    field.setSource(source);
    field.setValue("rat");
    field.addToIndexes();
  }
}


text:
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>
<link rel="stylesheet" type="text/css" href="style.css" />


text:
#include<sys/types.h>
#include<sys/socket.h>			/* for connect() bind() sendmsg() recvmsg() */
#include<sys/un.h>			/* for sockaddr_un */
#include<unistd.h>			/* for close() fstat() fork() */
#include<sys/wait.h>			/* for waitpid() */
#include<fcntl.h>			/* for fcntl() AT_FDCWD */
#include<stdlib.h>			/* for _exit() */
#include<string.h>			/* for strcpy()) */
#include<limits.h>			/* for LONG_MAX */
#include<errno.h>

/* helper functions */

static int popproperties(int fd)
{
	int getfd;
	getfd = fcntl(fd, F_GETFD);
	if(getfd==-1)
		return -1;

	int getfl;
	getfl = fcntl(fd, F_GETFL);
	if(getfl==-1)
		return -1;

	int properties;
	if((getfd & FD_CLOEXEC) == FD_CLOEXEC)
		properties = O_CLOEXEC;
	else
		properties = 0;

	properties = properties | (getfl & O_NONBLOCK);

	return properties;
}
static int pushproperties(int fd, int properties)
{
	int err;

	int setfd;
	if((properties&O_CLOEXEC)==O_CLOEXEC)
		setfd = FD_CLOEXEC;

	err = fcntl(fd,F_SETFD,setfd);
	if(err==-1)
		return -1;

	int setfl;
	if((properties&O_NONBLOCK)==O_NONBLOCK)
		setfl = O_NONBLOCK;

	return fcntl(fd,F_SETFL,setfl);
}

static int give(int fd, int rw)
{
	char byte;
	byte = '\0';
	struct iovec unused;
	unused.iov_base = &byte;
	unused.iov_len = sizeof(char);

	struct body
	{
		struct cmsghdr body;
		int rwfd;
		int rofd;
	};

	struct msghdr head;
	struct body body;
	memset(&body,0,sizeof(struct body));

	head.msg_name = NULL;
	head.msg_namelen = 0;
	head.msg_flags = 0;
	head.msg_iov = &unused;
	head.msg_iovlen = 1;

	head.msg_control = &body;
	head.msg_controllen = sizeof(body);

	struct cmsghdr *interface;
	interface = CMSG_FIRSTHDR(&head);

	interface->cmsg_level = SOL_SOCKET;
	interface->cmsg_type = SCM_RIGHTS;

	interface->cmsg_len = CMSG_LEN(1*sizeof(int));

	int*data;
	data = (int*)CMSG_DATA(interface);
	data[0] = rw;

	long err;
	for(;;)
	{
		err = sendmsg(fd, &head, MSG_WAITALL);
		if(err==-1)
		{
			if(errno==EWOULDBLOCK|| errno==EAGAIN|| errno==EINTR)
				continue;
			else
				return -1;
		}
		else if(err==1)
			break;
	}

	return 0;
}
static int take(int fd, int*rw)
{
	char byte;
	byte = '\0';
	struct iovec unused;
	unused.iov_base = &byte;
	unused.iov_len = sizeof(char);

	struct body
	{
		struct cmsghdr body;
		int fd;
	};

	struct msghdr head;
	struct body body;
	memset(&body,0,sizeof(struct body));

	head.msg_name = NULL;
	head.msg_namelen = 0;
	head.msg_flags = 0;
	head.msg_iov = &unused;
	head.msg_iovlen = 1;

	head.msg_control = &body;
	head.msg_controllen = sizeof(body);

	struct cmsghdr *interface;
	interface = CMSG_FIRSTHDR(&head);

	interface->cmsg_level = SOL_SOCKET;
	interface->cmsg_type = SCM_RIGHTS;

	interface->cmsg_len = CMSG_LEN(1*sizeof(int));

	long err;
	for(;;)
	{
		err = recvmsg(fd, &head, MSG_WAITALL);
		if(err==-1)
		{
			if(errno==EWOULDBLOCK|| errno==EAGAIN|| errno==EINTR)
				continue;
			else
				return -1;
		}
		else if(err==1)
			break;
	}

	if(interface->cmsg_len != CMSG_LEN(1*sizeof(int)))
		/*
		FIXME check and see if we have
		actually received them?  do we
		need to close them?  how do we
		find out how many we recieved?
		*/
		return -1;

	int*data;
	data = (int*)CMSG_DATA(interface);

	if(rw!=NULL)
		*rw = data[0];
	else
		close(data[0]);

	return 0;
}

static int bindat(int fs, int sck, struct sockaddr*data, size_t datalen)
{
	int err;
	int tmp;
	int com[2];
	int boundsocket;
	int status;
	int sock;

	boundsocket = -1;

	/* make a socket for communicating back to this process */
	err = socketpair(AF_LOCAL, SOCK_STREAM, 0, com);
	if(err==-1)
		return -1;

	pid_t child;
	child = fork();
	if(child == -1)
	{
		tmp = errno;
			close(com[0]);
			close(com[1]);
		errno = tmp;
		return -1;
	}

	if(child == 0)
	{
		/* this code is run in the child process */
		close(com[0]);

		err = fchdir(fs);
		if(err==-1)
			goto failsubp;
		close(fs);

		/* create a new socket that we'll pass back to the parent. */
		sock = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
		if(sock==-1)
			goto failsubp;

		err = bind(sock, data, datalen);
		if(err==-1)
			goto failsubp;

		err = give(com[1], sock);
		if(err==-1)
			goto failsubp;

		_exit(EXIT_SUCCESS);
	}

	/* this code is run in the parent process */
	close(com[1]);

	/*
	first we check if the child failed or succeeded,
	if it suceeded, then we read the fd from the socket.
	*/

	/* wait for the child to exit */
	err = waitpid(child, &status, 0);
	if(err==-1)
		goto fail;

	if(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS)
	{
		err = take(com[0], &boundsocket);
		/* FIXME manage err -- should crash with err if child has exited */
	}
	else
	{
		read(com[0],&tmp,sizeof(int));
		errno = tmp;
		goto fail;
	}

	close(com[0]);
	com[0] = -1;
	/* the child is now gone */

	/* cache the properties of socket */
	int cache;
	cache = popproperties(sck);
	if(cache==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;

	/* rename boundsocket sck | replace the socket we've been given with the new bound socket */
	err = dup2(boundsocket, sck);
	if(err==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;
	close(boundsocket);
	boundsocket = -1;

	/* set the new socket to behave like the old one */
	err = pushproperties(sck, cache);
	if(err==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;

	return 0;

fail:
	tmp = errno;
		if(com[0]!=-1) close(com[0]);
		if(boundsocket!=-1) close(boundsocket);
	errno = tmp;

	return -1;

failsubp:
	tmp = errno;
	write(com[1],&tmp,sizeof(int));
	_exit(EXIT_FAILURE);

	/* unreachable */
	return -1;
}
static int connectat(int fs, int sck, struct sockaddr*data, size_t datalen)
{
	int err;
	int tmp;
	int com[2];
	int connectedsocket;
	int status;

	connectedsocket = -1;

	/* make a socket for communicating back to this process */
	err = socketpair(AF_LOCAL, SOCK_STREAM, 0, com);
	if(err==-1)
		return -1;

	pid_t child;
	child = fork();
	if(child == -1)
	{
		tmp = errno;
			close(com[0]);
			close(com[1]);
		errno = tmp;
		return -1;
	}
	if(child == 0)
	{
		/* this code is run in the child process */
		close(com[0]);

		err = fchdir(fs);
		if(err==-1)
			goto failsubp;
		close(fs);

		/* create a new socket that we'll pass back to the parent. */
		int sock;
		sock = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
		if(sock==-1)
			goto failsubp;

		err = connect(sock, data, datalen);
		if(err==-1)
			goto failsubp;

		err = give(com[1], sock);
		if(err==-1)
			goto failsubp;

		_exit(EXIT_SUCCESS);
	}

	/* this code is run in the parent process */
	close(com[1]);

	err = waitpid(child, &status, 0);
	if(err==-1)
		goto fail;
	if(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS)
	{
		err = take(com[0],&connectedsocket);
		/* FIXME handle error */
	}
	else
	{
		read(com[0],&tmp,sizeof(int));
		errno = tmp;
		goto fail;
	}

	close(com[0]);
	com[0] = -1;
	/* the child is now gone */

	/* cache the properties of the input socket */
	int cache;
	cache = popproperties(sck);
	if(cache==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;

	/* replace the input socket with the new bound socket */
	err = dup2(connectedsocket, sck);
	if(err==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;

	close(connectedsocket);
	connectedsocket = -1;

	err = pushproperties(sck, cache);
	if(err==-1)
		/* FIXME retry iff EINTR or EBUSY */
		goto fail;

	return 0;

fail:
	tmp = errno;
		if(com[0]!=-1) close(com[0]);
		if(connectedsocket!=-1) close(connectedsocket);
	errno = tmp;

	return -1;

failsubp:
	tmp = errno;
	write(com[1],&tmp,sizeof(int));
	_exit(EXIT_FAILURE);

	/* unreachable */
	return -1;
}

/***
this is a temporary (and poor) mechanism for
getting a unique identifier for the AF_LOCALAT
socket, that won't clash with existing constants.
it should and will be improved later.
***/
static long unique = -1;
long localat_family(void)
{
	/*
	this approach should have a better chance of
	working if localat is used ontop of another
	library that provides extra families using the
	same mechanism as localat, and has them linked or
	#defined to overload the socket() function.

	instead of picking the first number that isn't
	any of the known families, we pick the first
	number that does gives an error with whichever
	socket function we wind up using.  this means
	that we'll never accidentally clobber any
	overloaded socket function's new families, and
	any two threads that wind up calling localat_family()
	will return the same value.

	of course, this approach will break if localat
	is compiled ontop of another library that provides
	extra types, since we're only checking the known
	types.  so be warned.
	*/

	int err;
	short i;

	i = -1;
retry:
	++i;

	if(unique!=-1)
		return unique;

	err = socket(i,SOCK_STREAM,0);
	if(err!=-1)
	{
		close(err);
		goto retry;
	}

	if(unique!=-1)
		return unique;

	err = socket(i,SOCK_DGRAM,0);
	if(err!=-1)
	{
		close(err);
		goto retry;
	}

#ifdef SOCK_SEQPACKET
	/* linux only, apparantly */
	if(unique!=-1)
		return unique;

	err = socket(i,SOCK_SEQPACKET,0);
	if(err!=-1)
	{
		close(err);
		goto retry;
	}
#endif

	if(unique!=-1)
		return unique;

	err = socket(i,SOCK_RAW,0);
	if(err!=-1)
	{
		close(err);
		goto retry;
	}

	if(unique!=-1)
		return unique;

	err = socket(i,SOCK_RDM,0);
	if(err!=-1)
	{
		close(err);
		goto retry;
	}

	unique = i;
	return unique;
}
#define AF_UNIXAT localat_family()
#define AF_LOCALAT localat_family()

struct sockaddr_unat
{
	sa_family_t sunat_family;
	int sunat_fd;
	char sunat_path[108];
};

int socket2(int domain, int type, int protocol)
{
	if(domain == AF_LOCALAT)
		return socket(AF_LOCAL,type,protocol);
	else
		return socket(domain,type,protocol);
}
int connect2(int socket, void*sockaddr, socklen_t addrlen)
{
	struct sockaddr_unat*addr;
	addr = sockaddr;

	if(addr->sunat_family != AF_LOCALAT)
		return connect(socket,(struct sockaddr*)sockaddr,addrlen);

	/* FIXME this either clips the path if it runs over, or overflows, and mangles @len */
	struct sockaddr_un sock;
	sock.sun_family = AF_LOCAL;
	strcpy(sock.sun_path,addr->sunat_path);

	if(addr->sunat_fd == AT_FDCWD || addr->sunat_path[0]=='/' || addr->sunat_path[0]=='\0')
		return connect(socket,(struct sockaddr*)&sock, sizeof(struct sockaddr_un));

	return connectat(addr->sunat_fd, socket, (struct sockaddr*)&sock, sizeof(struct sockaddr_un));
}
int bind2(int socket, void*sockaddr, socklen_t addrlen)
{
	struct sockaddr_unat*addr;
	addr = sockaddr;

	if(addr->sunat_family != AF_LOCALAT)
		return bind(socket,(struct sockaddr*)sockaddr,addrlen);

	/* FIXME this either clips the path if it runs over, or overflows, and mangles @len */
	struct sockaddr_un sock;
	sock.sun_family = AF_LOCAL;
	strcpy(sock.sun_path,addr->sunat_path);

	if(addr->sunat_fd == AT_FDCWD || addr->sunat_path[0]=='/' || addr->sunat_path[0]=='\0')
		return bind(socket,(struct sockaddr*)&sock, sizeof(struct sockaddr_un));

	return bindat(addr->sunat_fd, socket, (struct sockaddr*)&sock, sizeof(struct sockaddr_un));
}


text:
#!/usr/bin/perl
#

use strict;

my ($include_dir, $data_dir, $feature_file);

if( @ARGV ) {
    die "Invalid number of arguments" if scalar @ARGV != 3;
    ($include_dir, $data_dir, $feature_file) = @ARGV;

    -d $include_dir or die "No such directory: $include_dir\n";
    -d $data_dir or die "No such directory: $data_dir\n";
} else {
    $include_dir = 'include/mbedtls';
    $data_dir = 'scripts/data_files';
    $feature_file = 'library/version_features.c';

    unless( -d $include_dir && -d $data_dir ) {
        chdir '..' or die;
        -d $include_dir && -d $data_dir
            or die "Without arguments, must be run from root or scripts\n"
    }
}

my $feature_format_file = $data_dir.'/version_features.fmt';

my @sections = ( "System support", "mbed TLS modules",
                 "mbed TLS feature support" );

my $line_separator = $/;
undef $/;

open(FORMAT_FILE, "$feature_format_file") or die "Opening feature format file '$feature_format_file': $!";
my $feature_format = <FORMAT_FILE>;
close(FORMAT_FILE);

$/ = $line_separator;

open(CONFIG_H, "$include_dir/config.h") || die("Failure when opening config.h: $!");

my $feature_defines = "";
my $in_section = 0;

while (my $line = <CONFIG_H>)
{
    next if ($in_section && $line !~ /#define/ && $line !~ /SECTION/);
    next if (!$in_section && $line !~ /SECTION/);

    if ($in_section) {
        if ($line =~ /SECTION/) {
            $in_section = 0;
            next;
        }

        my ($define) = $line =~ /#define (\w+)/;
        $feature_defines .= "#if defined(${define})\n";
        $feature_defines .= "    \"${define}\",\n";
        $feature_defines .= "#endif /* ${define} */\n";
    }

    if (!$in_section) {
        my ($section_name) = $line =~ /SECTION: ([\w ]+)/;
        my $found_section = grep $_ eq $section_name, @sections;

        $in_section = 1 if ($found_section);
    }
};

$feature_format =~ s/FEATURE_DEFINES\n/$feature_defines/g;

open(ERROR_FILE, ">$feature_file") or die "Opening destination file '$feature_file': $!";
print ERROR_FILE $feature_format;
close(ERROR_FILE);


text:
import requests
from app import app
from flask import request

@app.route('/stock', methods=['GET', 'POST'])
def get_stock():
    print request.args
    ticker = request.args.get('text')
    channel = request.args.get('channel_name')
    r = requests.get("http://finance.yahoo.com/d/quotes.csv?s="+ticker+"&f=csl1d1t1c1ohgv&e=.csv")
    stock_info = r.content.split(",")
    ret_string = "\nSymbol: " + stock_info[1][1:-1]
    ret_string += "\nCurrent price: " + stock_info[2]
    ret_string += "\nPrice retrieved at: " + stock_info[4][1:-1]
    ret_string += "\nToday's open: " + stock_info[6]
    ret_string += "\nToday's high: " + stock_info[7]
    ret_string += "\nToday's low: " + stock_info[8]
    ret_string += "\nVolume: " + stock_info[9]
    ret_string += "\nhttp://chart.finance.yahoo.com/z?s="+stock_info[1][1:-1]+"&t=1d&q=l&l=on&z=s&p=m50,m200"
    r = requests.post('https://algorerhythms.slack.com/services/hooks/slackbot?token=cORCNdAEH7fhNaWndKUDu9Mw&channel=%23'+channel, ret_string)
    return ''


text:
package org.jboss.seam.faces.event;

import java.util.List;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.PreDestroyApplicationEvent;
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;

import org.jboss.solder.logging.Logger;

/**
 * Provide CDI injection to SystemEventListener artifacts by delegating through this class.
 *
 * @author Lincoln Baxter, III
 */
public class DelegatingSystemEventListener extends AbstractListener<SystemEventListener> implements SystemEventListener {
    private transient final Logger log = Logger.getLogger(DelegatingSystemEventListener.class);

    @Override
    public boolean isListenerForSource(final Object source) {
        return true;
    }

    @Override
    public void processEvent(final SystemEvent event) throws AbortProcessingException {
        if (event instanceof PreDestroyApplicationEvent && !isBeanManagerAvailable()) {
            log.info("BeanManager no longer available; Cannot notify CDI-managed listeners of "
                    + PreDestroyApplicationEvent.class.getSimpleName());
            return;
        }

        for (SystemEventListener l : getEventListeners()) {
            if (l.isListenerForSource(event.getSource())) {
                l.processEvent(event);
            }
        }
    }

    @SuppressWarnings("unchecked")
    private List<SystemEventListener> getEventListeners() {
        return getListeners(SystemEventBridge.class);
    }

}


text:
/**
 * File contains functions for creating, updating and deleting a Tag.
 *
 * @author: Dejan Dežman <dejan.dezman@cosylab.com>
 */

/**
 * Generate a Tag object, check if object is valid and create it.
 */
function createTagHandler() {
	var tag = generateTagObject();

	if(isValidTag(tag) === true) {
		createTag(tag);
	}
}

/**
 * Generate a Tag object, check if object is valid and modify it.
 */
function modifyTagHandler() {
	var tag = generateTagObject();
	var originalName = $('#new_tag_name_original').val();

	if(isValidTag(tag) === true) {
		modifyTag(tag, originalName);
	}
}

/**
 * Generate a Tag object, check if object is valid and delete it.
 */
function deleteTagHandler() {
	var originalName = $('#name_original').val();
	deleteTag(originalName);
}

/**
 * Generate a Tag object and set data from create/modify modal window
 */
function generateTagObject() {
	var tag = {"tag":[{
		"name":"",
		"state":"Active"
	}]};

	var name = $('#new_tag_name').val();

	// Set name
	tag.tag[0].name = name;

	return tag;
}

/**
 * Check if Tag object is valid and show error if it is not
 * @param {type} tag current Logbook object
 */
function isValidTag(tag){
	var errorBlock = $('#new_logbook_error_block');
	var errorX = $('#new_logbook_error_x');
	var errorBody = $('#new_logbook_error_body');

	errorX.click(function(e){
		errorBlock.hide("fast");
	});

	var errorString = "";

	// Check data
	if(tag.tag[0].name.length === 0) {
		errorString += "Tag name should not be empty!<br/>";
	}

	if(errorString.length === 0) {
		return true;

	} else {
		errorBody.html(errorString);
		errorBlock.show("fast");
		return false;
	}
}


text:
#if DEBUG
using NUnit.Framework;

namespace Logy.MwAgent.DotNetWikiBot.Smw.Tests
{
    [TestFixture]
    public class PersonPropertiesTests
    {
        [Test]
        public void MakeCondition()
        {
            Assert.AreEqual(
                "[[Birthday::+]] OR [[BirthdayText::+]] OR [[Deathday::+]] OR [[Sex::+]] OR [[Description::+]]|?Birthday|?BirthdayText|?Deathday|?Sex|?Description",
                PersonProperties.MakeCondition);
        }
    }
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<aop:config>
		<aop:aspect ref="serviceMonitorableInterceptor">
			<aop:pointcut id="aroundServiceMonitorable" expression="@annotation(com.github.xyc.monitor.ServiceMonitorable) and @annotation(monitorable)" />
			<aop:around pointcut-ref="aroundServiceMonitorable" method="doAround" arg-names="monitorable" />
		</aop:aspect>
	</aop:config>

	<bean id="serviceMonitorableInterceptor" class="com.github.xyc.monitor.ServiceMonitorableInterceptor" />

</beans>


text:
Main website: [HTML5 Magnets!](http://html5magnets.elfsternberg.com)

Happy results: [@HTML5Magnets](https://twitter.com/#!/html5magnets)

## Main Idea

Fridgemagnets is a straightforward simulation of a relaxing
refrigerator poem tileset.  It was inspired by
[TwitterMagnets](http://twittermagnets.com/), a Flash app written by the
brilliant graphic designers at
[PlusGood](http://www.plusgood.co.uk/).  I have a bit of Flash envy,
since I'm not an Adobe developer, and the TwitterMagnets application
bugged me.  It didn't resize, it didn't do mobile very well, and
nobody has a space reserved on their fridge for the poem: a "poem" is
just a meaningful arrangement of words deliberately placed in close
proximity that seems to convey meaning.

Fridgemagnets has a lot of new and fun technologies: it uses the audio
API, it involves all manner of write-only-DOM tricks to make resizing
work well, and it's my first major piece of express.js software.  (I
originally thought of using Zappa, but decided against it; dispatch is
not the biggest thing Node has to deal with, and express by itself
works just fine in Coffee.)

I can now add the Twitter API, the HTML5 Audio API, and some basic
game mechanics ([Separate Axis
Theorem](http://www.metanetsoftware.com/technique/tutorialA.html) for
collision management, anyone?) to my resume.

This is known to work in later versions of Chrome, Firefox, and IE8+
under Windows XP.  No promise is implied of it working on your version
of those, or any other browser.  It's not (yet) phone-ready.

## Requirements

Node.js.  Most of the subsidiary requirements can be found in the two
package.json files.  For development purposes Coffeescript, LessCSS,
and HAML are in heavy use.

If you're running the server, you need MySQL.  The schema for the
MySQL database can be found in the server folder.

A config file.  There's an example in the server folder.

A twitter developer's account.  Get one at dev.twitter.com.

If you're going to be using the test/deploy routine, inotify-tools and
python's "fabric" program are very useful.

If you're going to make this publicly available, I strongly recommend
you run this as its own user in a low-permissions container, behind
Nginx and a lot of smarts.  Also, the Node.js program "forever" is
very useful in keeping the server up.

## Acknowledgements

[PlusGood](http://www.plusgood.co.uk/), for the inspiration.

[Emily Richards aka Snowflake](http://ccmixter.org/people/snowflake),
for her beautiful music.

The entire crew at [Nodejitsu](http://nodejitsu.com/), for all the
encouragement, even if I don't use their services.

## CREDITS

"Ethereal Space" is copyright (c) 2011 Snowflake, licensed under a
Creative Commons 3.0 Attribution-Required license.

jQuery, jQuery UI and associated assets, Buzz.js, and jQuery CSS
Transform are copyright their respective owners, and available under
a permissive MIT license.

## LICENSE AND COPYRIGHT NOTICE: NO WARRANTY GRANTED OR IMPLIED

Copyright (c) 2012 Elf M. Sternberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

	- Elf M. Sternberg <elf@pendorwright.com>


text:
<?php

use MongoDB\Client;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\DI\FactoryDefault;
use Phalcon\Exception as PhalconException;
use Phalcon\Http\Request;
use Phalcon\Incubator\MongoDB\Mvc\Collection\Manager as MongoDBCollectionManager;
use Phalcon\Loader;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Model\MetaData\Apc;
use Phalcon\Mvc\Model\MetaData\Memory;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;

define('APP_PATH', realpath('..'));
require APP_PATH . "/vendor/autoload.php";

try {
    // Load the config
    $config = include APP_PATH . "/app/config/config.php";

    // Register an autoloader
    $loader = new Loader();
    $loader->registerDirs([
        $config->application->controllersDir,
        $config->application->modelsDir,
        $config->application->collectionsDir,
    ])->register();

    // Create a DI
    $di = new FactoryDefault();

    // Setting up the router
    $di->setShared('router', require APP_PATH . '/app/config/routes.php');

    //MetaData
    $di->setShared('modelsMetadata', function () {
        if (function_exists('apc_store')) {
            return new Apc();
        }

        return new Memory([
            'metaDataDir' => APP_PATH . "/app/compiled-templates/"
        ]);
    });

    // Setting up the view component (seems to be required even when not used)
    $di->setShared('view', function () use ($config) {
        $view = new View();
        $view->setViewsDir($config->application->viewsDir);
        $view->registerEngines([
            ".volt" => function ($view) {
                $volt = new Volt($view);
                $volt->setOptions([
                    "path" => APP_PATH . "/app/compiled-templates/",
                    "extension" => ".compiled",
                    "separator" => '_',
                ]);

                return $volt;
            }
        ]);

        return $view;
    });

    // Setting up the database connection
    $di->setShared('db', function () use ($config) {
        $database = $config->database;

        return new Mysql([
            'host' => $database->host,
            'username' => $database->username,
            'password' => $database->password,
            'dbname' => $database->name,
            'options' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                PDO::ATTR_PERSISTENT => true,
            ],
        ]);
    });

    // Setting up the mongodb connection
    $di->setShared('mongo', function () use ($config) {
        $mongodbConfig = $config->mongodb;
        $mongo = new Client($mongodbConfig->url);

        return $mongo->selectDatabase($mongodbConfig->db);
    });

    // Registering the mongoDB CollectionManager service
    $di->setShared('collectionsManager', function () {
        return new MongoDBCollectionManager();
    });

    // Handle the request
    $request = new Request();
    $application = new Application();
    $application->setDI($di);
    $application->handle($request->getURI())->send();
} catch (PhalconException $e) {
    echo "PhalconException: ", $e->getMessage();
}


text:
var Language = Backbone.Model.extend({
  defaults: function(){
    return {
      name : '',
      iso639 : '',
      alphabet : [],
      punctuationPATTERN : "[\-,\?\.\!\…]",
      letterNames : []
    }
  },

  initialize:  function(options){
    _.bindAll(this, 'phonemize', 'depunctuate', 'tokenize')
  },

  // Split a string into phonemes.
  //
  // Compare:
  //
  //     phonemize('ngalan') → ['ng', 'a', 'l', 'a', 'n']
  //     phonemize('namon') → ['n','a','m','o','n']
  //
  // Note that «ng» happens to be treated as a 'letter' in Hiligaynon.
  phonemize: function(text){
    var alphabet = this.get('alphabet')
    // we want to match «ng» before «n», so sort by length.
    var letters = alphabet.sort(function(a,b){ return b.length-a.length});
    var phonemeRE = new RegExp('(' + letters.join('|') + ')' );
    return text.match(phonemeRE);
  },

  // Delete punctuation characters.
  //
  // _Language-specific._
  depunctuate:  function(text){
    var punctuationRE = new RegExp(this.get('punctuationPATTERN'), 'g');
    return text.split(punctuationRE).join(' ');
  },

  // Depunctuate and then split into words
  //
  // _Language-specific._
  tokenize:  function(text){
    var depunctuated = this.depunctuate(text).trim();
    return depunctuated.split(/[ ]+/);
  }

})

// App
// ---
//
// App object for wrapping core elements and providing single point of entry
var App = {};

// Word
// ----
//
// A `Word` is initialized with at least a `token` attribute. It automatically
// looks itself up by that token in the `Lexicon` and populates its other fields.
//
// `Word`s consist of:
// 1. **token** - the phonetic representation of the Word, e.g. **naglumpat**
// 2. **morphology** - the morphological representation of the Word, e.g. **nag-lumpat**
// 3. **gloss** - the gloss of the Word, e.g. **TRANS.PERFECT-jump**
//
// For information on glossing see [The Leipzig Glossing Rules](http://www.eva.mpg.de/lingua/resources/glossing-rules.php)
//
App.Word = Backbone.Model.extend({

  defaults: {
    token: '',
    morphology: '',
    gloss: ''
  },

  initialize: function(options){
    _.bindAll(this, 'populate', 'update')
    //this.populate();
    this.on('change', this.update, this);
  },

  update : function(){
    console.log(JSON.stringify(this.attributes,null,2));
  },

  populate : function(){
    //var match = text.lexicon.lookup({token: this.get('token')})
    this.set(match.attributes);
  }

})

// Lexicon
// -------
//
// The `Lexicon` is the repository for all lexical information.
// `Word`s look themselves up here via `token` immediately upon instantiation.
App.Lexicon = Backbone.Collection.extend({
   model : App.Word,

   initialize: function(options){
     _.bindAll(this, 'lookup');
   },

   comparator: function(word){
     return word.get('token').toLowerCase();
   },

   // If the word isn't found in the `Lexicon`, add it.
   lookup: function(attrs){
     if(_.isString(attrs)){
       attrs = {token: attrs};
     }

     // For now, we don't support homonymy!
     var match = this.findWhere(attrs); // returns 1 result

     if(match){
       return match;
     } else {
       this.add(attrs)
       return this.lookup(attrs);
     }
   }
})

// Sentence
// --------
//
// A `Sentence` contains:
//
// 1. A `transcription` : a transcribed stretch of speech (String)
// 2. A `translation` : a free translation into the description language (String)
// 3. `tokens` : a list of strings (not a collection) derived automatically from `transcription`
//
// The `SentenceView` watches this model for changes to the `tokens` list, which it
//
App.Sentence = Backbone.Model.extend({

  defaults: function(){
    return {
      transcription : '',
      translation : '',
      tokens : [],
    }
  },

  initialize: function(options){
    _.bindAll(this, 'tokenize');
    this.on('change:transcription', this.tokenize, this);
  },

  // Use the `Language.tokenize` to split `Sentence.transcription` into words
  tokenize : function(){
    var tokens = text.language.tokenize(this.get('transcription'));
    this.set('tokens', tokens);
    Backbone.trigger('sentence:tokenize', tokens);
    //var words = tokens.map(function(token){ return {token: token}});
  }
})

// Sentences
// ---------
//
// Container to add to `Text` object.
App.Sentences = Backbone.Collection.extend({
  model: App.Sentence
})

// Text
// ----
//
// A `Text` is the top-level model (until we build a `Corpus` model). It contains
// references to the `Lexicon` collection, the `Language`, and the `Sentences`
// collection.
//
// A `Text` consists of:
//
// 1. An optional title
// 2. A collection of `Sentence` models
// 3. A reference to a `Language` model instance, which contains language-specific information
// 4. A reference to a `Lexicon` model instance, which lexical information in the `Language`.
//
// Depends on `Lexicon` > `Word`, `Sentences`, `Language`
App.Text = Backbone.Model.extend({
  initialize: function(options){
    _.bindAll(this, 'addSentence', 'log');

    this.sentences = new Sentences(),
    this.language = new Language(options.language);
    this.lexicon = new Lexicon(options.lexicon);

  },

  log: function(){
    console.log(JSON.stringify(this.toJSON(),null, 2));
  },

  addSentence: function(sentence){
    this.sentences.add(sentence);
  }

})

// Analysis
// --------
//
// Collection of `Word`s. Can be thought of as a small subset of
// `Lexicon`. These are not stored with the `Sentence` objects;
// rather, they are populated as needed from the `Lexicon`.
//
// Inefficient: we need to cache these objects onto the
// `Sentence` down the road..
App.Analysis = Backbone.Collection.extend({
  model: App.Word
})

// AnalysisView
// ------------
//
// Edit apparatus of words with lexical information, wraps `WordView`s.
//
App.AnalysisView = Backbone.View.extend({

  events: {
  },

  initialize: function(options){
    _.bindAll(this, 'render')
    this.el.innerHTML = '';
  },

  render: function(sentence){
    var self = this;
    var fragment = document.createDocumentFragment();

    this.collection.each(function(word){
      var wordView = new WordView({model: word});
      fragment.appendChild(wordView.el);
    })

    this.$('#analysis').append(fragment);
    return this;

    return this;
  }

})

// SentenceView
// --------
//
// Index view of `Sentence` object
// (subview of `TextView`)
//
App.SentenceView = Backbone.View.extend({

  events: {
    'click': function(){ console.log(JSON.stringify(this.model.attributes))}
  },

  className: 'sentence',

  model: App.Sentence,

  initialize: function(options){
    _.bindAll(this, 'render')
    this.template = _.template($('#sentenceTemplate').html());
  },

  // `Sentence`s  are responsible for rendering themselves
  render: function(sentence){
    var self = this;
    this.$el.html(self.template(this.model.toJSON()));
    return this;
  }

})

// TextView
// --------
//
// Index view of `Text` object
//
App.TextView = Backbone.View.extend({

  el: $('#text'),

  initialize: function(options){
    _.bindAll(this, 'render')
    this.template = _.template($('#sentenceTemplate').html());
    this.listenTo(this.model.sentences, 'add', this.render);
  },

  // Responsible for rendering `Sentences` collection.
  render: function(){
    var self = this;
    var fragment = document.createDocumentFragment();
    this.el.innerHTML = '';

    this.model.sentences.each(function(sentence){
      var sentence = new SentenceView({model: sentence}).render().el;
      fragment.appendChild(sentence);
      //self.$el.find('#sentences').append(self.template(sentence.toJSON()));
    })
    this.el.appendChild(fragment);
    return this;
  }
})

// WordView
// ----
App.WordView = Backbone.View.extend({
  tagName: 'li',

  events : {
    'keyup input.morphology' : 'keyupMorphology',
    'keyup input.gloss' : 'keyupGloss',
    'keyup input' : 'keyup',
    'click' : function(){ console.log(JSON.stringify(this.model.attributes))}
  },

  initialize : function(options){
    _.bindAll(this, 'keyupGloss', 'keyupMorphology', 'readAll');
    this.listenTo(this.model, 'change', this.render);
    this.render();
  },

  // collect all
  readAll: function(ev){
    var morphology = this.$('input.morphology').val().trim();
    var gloss = this.$('input.gloss').val().trim();
    var token = this.model.get('token');
    return {
      morphology: morphology,
      token: token,
      gloss: gloss
    }
  },

  keyupGloss: function(ev){
    switch(ev.which){
     case 13: // ENTER
       var values = this.readAll();
       this.model.set(values);
       text.lexicon.add(this.model);
       break;
     case 40: // DOWN ARROW
       ev.target.value = this.model.get('token')
       break;
    }
  },

  keyupMorphology: function(ev){
    switch(ev.which){
     case 13: // ENTER
       var morphology = this.$('input.morphology').val().trim();
       this.model.set('morphology', morphology);
       text.lexicon.add(this.model);
       break;
     case 40: // DOWN ARROW
       ev.target.value = this.model.get('token')
       break;
    }
  },

  render: function(){
    var template  = _.template($('#wordTemplate').html());
    this.$el.html(template(this.model.toJSON()));
    return this;
  }
})

// EditorView
// ----------
//
// Interface for editing, glossing, and saving `Sentence`s.
App.EditorView = Backbone.View.extend({

  events: {
    'keyup textarea' : 'keyup',
    'click #addSentence' : 'addSentence'
  },

  el : '#editor',

  model : new App.Sentence(),

  initialize: function(options){
    _.bindAll(this, 'keyup', 'updateParallelText', 'clear');

    this.$('.transcription').attr('lang',  text.language.get('iso639'));
    this.$('.translation').attr('lang',  options.translationLang);

    this.model.on('change', this.render, this);

    this.analysisView = new AnalysisView({
      collection: new Analysis(),
      el: this.$('#analysis')
    })
  },

  // When the
  keyup: function(ev){
    if(ev.which == 13){ // ENTER
      this.updateParallelText();
    }
  },

  // Edit the `transcription` and `translation` attributes on the current `Sentence`.
  updateParallelText: function(){
    var transcription = this.$('textarea.transcription').val().trim();
    var translation = this.$('textarea.translation').val().trim();

    this.model.set({
      'transcription': transcription,
      'translation': translation
    });

    this.$('textarea.transcription').val(transcription);
    this.$('textarea.translation').val(translation);

    this.$('.transcription').focus();

  },

  clear: function(){
    this.$('textarea.transcription').val('');
    this.$('textarea.translation').val('');
    this.analysisView.el.innerHTML = '';
    this.analysisView = new AnalysisView({
      collection: new Analysis(),
      el: this.$('#analysis')
    })

    this.model = new Sentence();

    this.$('.transcription').focus();
  },

  addSentence: function(){
    text.sentences.add(this.model);
    this.clear();
  },

  log: function(options){
    console.log(JSON.stringify(this.model.toJSON(), null, 2))
  },

  render: function(options){
    var fragment = document.createDocumentFragment();

    this.model.get('tokens').forEach(function(token){
      var word = new Word({token: token});
      var wordView = new WordView({model: word});
      fragment.appendChild(wordView.el);
    })

    this.$('#analysis').html(fragment);
    return this;
  }
})

// LexiconView
// -----------
//
// A searchable view of the `Lexicon`.
App.LexiconView = Backbone.View.extend({
  initialize: function(options){
    _.bindAll(this, 'render');
    this.$ol = this.$el.find('ol');
    this.render();
    this.listenTo(this.collection, 'add remove', this.render);
    this.listenTo(Backbone, 'analyze:sentence', this.render);
  },

  render : function(){
    var self = this;
    var inlineWordTemplate =  $('#inlineWordTemplate').html(); //'
<%- token %>
';
    this.$ol.html('');
    this.collection.each(function(word){
      self.$ol.append(_.template(inlineWordTemplate, word.toJSON()));
    })
    return this;
  }
})

// text instance
// -------------
//
// refactor to init
App.text = new Text({
  lexicon : [
    { token: 'kumusta',  morphology: 'kumusta', gloss: 'how.are.you' },
    { token: 'ka',  morphology: 'ka', gloss: '1.ERG.SG' },
    { token: 'ang',  morphology: 'ang', gloss: 'the' }
  ],
  title: 'A Wicked Hiligaynon Production',
  language: {
    name: 'Hiligaynon',
    iso639: 'hil',
    punctuationPATTERN : '[\,\?\.\!\…]',
    alphabet: 'a b k d e g h i l m n ng o p r s t u w y'.split(' '),
    letterNames : "a ba ka da e ga ha i la ma na nga o pa ra sa ta u wa ya".split(' ')
  }
}),

// textView instance
// -----------------
//
// refactor to init
App.textView = new App.TextView({model: App.text});

// editorView instance
// -----------------
//
// refactor to init
App.editorView = new App.EditorView({

   translationLang : 'en'

});

// lexiconView instance
// -----------------
//
// refactor to init
App.lexiconView = new App.LexiconView({
  el: '#lexicon',
  collection: text.lexicon
})

// Router
// ------
App.Router = Backbone.Router.extend({

  routes : {
    '' : 'index',
    'text' : 'text',
    'sentences/:id' : 'showSentence',
    'sentences/search/:query' : 'searchSentences',
    'words/search/:query' : 'searchWords'
  },

  initialize: function(options){
    _.bindAll(this, 'index', 'text', 'showSentence', 'searchWords',  'searchSentences' )
  },

  index: function(){
    alert('index');
    App.textView.render();
  },

  text: function(){
  },

  showSentence: function(id){
  },

  searchWords: function(query){
  },

  searchSentences: function(query){
  }

})

app.router = new Router();
Backbone.history.start();

// }).call(this)


text:
title: "Indieweb Summit 2019"
layout: post
date: 2019-05-28 00:44:41
---
<data class="p-rsvp" value="yes">RSVP yes</data> to Indieweb Summit 2019


text:
package com.vendelligence.webapp.searchmanager.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.vendelligence.webapp.searchmanager.config.SearchConfig;
import com.vendelligence.webapp.searchmanager.config.VendorConfig;

/*
 * Service for Remote Google Custom Search API search methods. This build uses the Google CSE API.
 *
 * This uses ResponseEntity<String>. While this works fine for the Javascript AJAX
 * request to the API, we will want to consider a stricter data type specifically
 * for used libraries: Jackson. Using List/Map/Hashmap is more common in most of
 * the Stack Overflow forums on the topic.
 *
 */

@Service
public class SearchService implements ISearchService
{
	// autowire the search configuration so we can flip from free to paid api on demand
	@Autowired
	SearchConfig sc;

	// autowire the vendor configuration so the repository of vendors can be searched
	@Autowired
	VendorConfig vc;

	// autowire the rest template from spring
	@Autowired
	RestTemplate restTemplate;

	private final Logger log = LoggerFactory.getLogger(getClass());

	// Holding off on switch to StringBuilder (singlethreaded) OR StringBuffer (multithreaded) optimization as JVM compiler will normally
	// switch below concatenation to StringBuilder if it deems optimization is required at compile time
	// Web References:
	// https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
	// https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
	// http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java

	// define constants for api service endpoint url construction
	private static final String API_INIT_URL = "https://www.googleapis.com/customsearch/v1?key=";
	private static final String SELECT_FIELDS = "&fields=context,searchInformation,items&cx=";
	private static final String QUERY_MARKER = "&q=";
	private static final String NUMBER_START_INDEX_MARKER = "&num=10&start=";
	private static final String WHITE_SPACE = " ";

	// search using generic search request for paginator requests
	public ResponseEntity<String> searchVendorRepositoryWithFilter(String q, String vendor, int startIndex) throws Exception
	{
		String vendorFilter = vc.getVendor().get(vendor);

		// service endpoint using dynamic parameters in http request from client
		String googleCseApiUrl = API_INIT_URL + sc.getApiFreeKey() + SELECT_FIELDS + vendorFilter + QUERY_MARKER + q
				+ NUMBER_START_INDEX_MARKER + startIndex;

		// modified this url to remove the "/1" string value in the parameter list as it was breaking the google cse api url
		ResponseEntity<String> response = restTemplate.getForEntity(googleCseApiUrl, String.class);

		log.info("Google CSE API Response: " + response);

		return response;
	}

	// refine the vendor repository search - only available for vendor-filter-driven searches
	public ResponseEntity<String> refineSearchResults(String q, String vendor, String rlabel) throws Exception
	{
		String vendorFilter = vc.getVendor().get(vendor);
		// https://developers.google.com/custom-search/docs/xml_results#xml-results-for-regular-and-advanced-search-queries
		String googleCseApiUrl = API_INIT_URL + sc.getApiFreeKey() + SELECT_FIELDS + vendorFilter + QUERY_MARKER + q
				+ WHITE_SPACE + rlabel;

		// log the refined url
		log.info("Refined API URL: " + googleCseApiUrl);

		// modified this url to remove the "/1" string value in the parameter list as it was breaking the google cse api url
		ResponseEntity<String> response = restTemplate.getForEntity(googleCseApiUrl, String.class);

		// log the response from the searchservice
		log.info("Google CSE API Response from Refined Search Results: " + response);

		return response;
	}

	// clone of previous method to test using refinement search AND startIndex for pagination option
	public ResponseEntity<String> refineSearchResultsWithStartIndex(String q, String vendor, String rlabel, int startIndex) throws Exception
	{
		String vendorFilter = vc.getVendor().get(vendor);

		// https://developers.google.com/custom-search/docs/xml_results#xml-results-for-regular-and-advanced-search-queries
		String googleCseApiUrl = API_INIT_URL + sc.getApiFreeKey() + SELECT_FIELDS + vendorFilter + QUERY_MARKER + q +
				WHITE_SPACE + rlabel + NUMBER_START_INDEX_MARKER + startIndex;

		// log the refined url
		log.info("Refined API URL: " + googleCseApiUrl);

		// modified this url to remove the "/1" string value in the parameter list as it was breaking the google cse api url
		ResponseEntity<String> response = restTemplate.getForEntity(googleCseApiUrl, String.class);

		// log the response from the searchservice
		log.info("Google CSE API Response from Refined Search Results: " + response);

		return response;
	}
}


text:
<?php

include(dirname(__FILE__).'/../bootstrap/unit.php');
initializeDatabase();

$configuration = ProjectConfiguration::getApplicationConfiguration( 'fe', 'unittest', true);
$database_manager = new sfDatabaseManager($configuration);
Doctrine::loadData(sfConfig::get('sf_test_dir').'/fixtures/fixtures_permission_unittest.yml');

$t = new lime_test(3, new lime_output_color());

$searchTask = new searchPermissionsForActions(new sfEventDispatcher(), new sfFormatter());
$searchTask->run(array(), array('--dir=test/fixtures/ --env=unittest --application=fe'));

$permissions = Doctrine::getTable('sfGuardPermission')->findAll(Doctrine::HYDRATE_ARRAY);
$t->is(count($permissions), 6, 'searchTask added to the table permission the right number of new permissions.');

$searchTask->run(array(), array('--dir=test/fixtures/ --env=unittest --application=fe'));
$permissions = Doctrine::getTable('sfGuardPermission')->findAll(Doctrine::HYDRATE_ARRAY);
$t->is(count($permissions), 6, 'searchTask do not add already present permissions.');

$t->info('Check if admin group has the right number of permission at the end');

$sggroup_admin = Doctrine::getTable('sfGuardGroup')
                            ->createQuery()
                            ->from('sfGuardGroup sgg')
                            ->where('sgg.name = ?', 'admin')
                            ->fetchOne();

$t->is(count($sggroup_admin->getPermissions()), 5, 'admin group has admin permission and the other four new permissions');