text:
/*
 * frame_preprocessor.h
 */
#ifndef VPM_FRAME_PREPROCESSOR_H
#define VPM_FRAME_PREPROCESSOR_H

#include "typedefs.h"
#include "video_processing.h"
#include "content_analysis.h"
#include "spatial_resampler.h"
#include "video_decimator.h"

namespace webrtc {

class VPMFramePreprocessor
{
public:

    VPMFramePreprocessor();
    ~VPMFramePreprocessor();

    WebRtc_Word32 ChangeUniqueId(const WebRtc_Word32 id);

    void Reset();

    // Enable temporal decimation
    void EnableTemporalDecimation(bool enable);

    void SetInputFrameResampleMode(VideoFrameResampling resamplingMode);

    //Enable content analysis
    void EnableContentAnalysis(bool enable);

    //Set max frame rate
    WebRtc_Word32 SetMaxFrameRate(WebRtc_UWord32 maxFrameRate);

    //Set target resolution: frame rate and dimension
    WebRtc_Word32 SetTargetResolution(WebRtc_UWord32 width,
                                      WebRtc_UWord32 height,
                                      WebRtc_UWord32 frameRate);

    //Update incoming frame rate/dimension
    void UpdateIncomingFrameRate();

    WebRtc_Word32 updateIncomingFrameSize(WebRtc_UWord32 width,
                                          WebRtc_UWord32 height);

    //Set decimated values: frame rate/dimension
    WebRtc_UWord32 DecimatedFrameRate();
    WebRtc_UWord32 DecimatedWidth() const;
    WebRtc_UWord32 DecimatedHeight() const;

    //Preprocess output:
    WebRtc_Word32 PreprocessFrame(const I420VideoFrame& frame,
                                  I420VideoFrame** processedFrame);
    VideoContentMetrics* ContentMetrics() const;

private:
    // The content does not change so much every frame, so to reduce complexity
    // we can compute new content metrics every |kSkipFrameCA| frames.
    enum { kSkipFrameCA = 2 };

    WebRtc_Word32              _id;
    VideoContentMetrics*      _contentMetrics;
    WebRtc_UWord32             _maxFrameRate;
    I420VideoFrame           _resampledFrame;
    VPMSpatialResampler*     _spatialResampler;
    VPMContentAnalysis*      _ca;
    VPMVideoDecimator*       _vd;
    bool                     _enableCA;
    int                      _frameCnt;

}; // end of VPMFramePreprocessor class definition

} //namespace

#endif // VPM_FRAME_PREPROCESS_H


text:
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

require('source-map-support').install();

import 'babel/polyfill';
import _ from 'lodash';
import fs from 'fs';
import path from 'path';
import express from 'express';

const server = express();

server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname)));

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------

// The top-level React component + HTML template for it
const templateFile = path.join(__dirname, 'templates/index.html');
const template = _.template(fs.readFileSync(templateFile, 'utf8'));

server.get('*', async (req, res, next) => {
  try {
    let notFound = false;
    let css = [];
    let data = {description: ''};

    data.title = 'Starter Kit';
    data.css = css.join('');
    data.body = '';
    let html = template(data);
    if (notFound) {
      res.status(404);
    }
    res.send(html);
  } catch (err) {
    next(err);
  }
});

//
// Launch the server
// -----------------------------------------------------------------------------

server.listen(server.get('port'), () => {
  if (process.send) {
    process.send('online');
  } else {
    console.log('The server is running at http://localhost:' + server.get('port'));
  }
});

redpajama_set_name: RedPajamaGithub


text:
package android.lib.pen.demo;

import android.content.ClipData;
import android.graphics.Point;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;

final class DragDropUtils {
    private static final CharSequence EMPTY = ""; //$NON-NLS-1$

    private DragDropUtils() {
    }

    /**
     * Standard drag & drop implementation.
     */
    public static void addDragDropSupport(final View dragHandle, final View dragView, final View dropTarget) {
        dragHandle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(final View view, final MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    dragView.startDrag(ClipData.newPlainText(DragDropUtils.EMPTY, DragDropUtils.EMPTY), new View.DragShadowBuilder(dragView) {
                        @Override
                        public void onProvideShadowMetrics(final Point shadowSize, final Point shadowTouchPoint) {
                            shadowSize.set(this.getView().getWidth(), this.getView().getHeight());
                            shadowTouchPoint.set(30, 30);
                        }
                    }, dragView, 0);

                    dragView.setVisibility(View.INVISIBLE);

                    return true;
                }

                return false;
            }
        });

        MultiDragListener listener = (MultiDragListener)dropTarget.getTag();

        if (listener == null) {
            listener = new MultiDragListener();
        }

        listener.addListener(dragView, new View.OnDragListener() {
            @Override
            public boolean onDrag(final View view, final DragEvent event) {
                switch (event.getAction()) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        return true;

                    case DragEvent.ACTION_DROP:
                        if (dragView.getVisibility() == View.INVISIBLE) {
                            dragView.setX(event.getX() - 30);
                            dragView.setY(event.getY() - 30);

                            dragView.setVisibility(View.VISIBLE);

                            return true;
                        }

                        break;

                    case DragEvent.ACTION_DRAG_ENDED:
                        if (dragView.getVisibility() == View.INVISIBLE) {
                            dragView.setVisibility(View.VISIBLE);

                            return true;
                        }

                        break;
                }

                return false;
            }
        });

        dropTarget.setOnDragListener(listener);
        dropTarget.setTag(listener);
    }
}


text:
There a lot of situations that we might use multiple directives in a web page,
and they have some relations among them.
In this example, I created two directives and CONNECTED them.

![](assets/001.gif)

The key point is passing `ngModel` with **two-way binding** between these directives.

## Implement

Refer to the following picture, I have 2 drop-down-lists and 1 display label.

1. Regions
2. Cities
3. What companies in the selected city

![](assets/002.png)

![](assets/003.png)

### Regions

* HTML

```
<select ng-model="Region" ng-change="ChangeChargeId()" ng-options="option.Name for option in RegionOptions track by option.Id" />
```

* JS

```
var app = angular.module('app', [])
  .controller('AppCtrl', function ($scope) {
      $scope.RegionOptions = [{
          'Id': 1,
          'Name': 'North Taiwan'
      }, {
          'Id': 2,
          'Name': 'South Taiwan'
      }];
  })
```

### Cities

Create a directive for "Cities". However, the cities drop-down-list would be changed after the "Region" changes.
So we pass the `$scope.Region` to the isolated scope of the directive for two-way binding.

* HTML

```
<my-city ng-model="Region" selectcity="MyCity" />
```

* JS

```
app.directive('myCity', function ($filter) {
        return {
            //restrict: "A",
            scope: {
                Region: "=ngModel",
                selectcity: "="
            },
            template: "<select ng-model='City' ng-change='ChangeCity()' ng-options='option.Name for option in CityOptions track by option.Id' />",
            link: function ($scope, $element) {

                $scope.filterCities = function (regionId) {
                    var cityOpts = $filter('filter')($scope.AllCityOptions, {
                        RegionId: regionId
                    }, true);
                    $scope.CityOptions = cityOpts;
                }

                $scope.AllCityOptions = [
                    { 'Id': 1, 'Name': 'Taipei', 'RegionId': 1 },
                    { 'Id': 2, 'Name': 'Linkou', 'RegionId': 1 },
                    { 'Id': 3, 'Name': 'Tainan', 'RegionId': 2 },
                    {'Id': 4,'Name': 'Kaohsiung','RegionId': 2}];

                $scope.$watch("Region", function (newValue, oldValue) {
                    if (newValue != null && newValue != {}) {
                        $scope.filterCities($scope.Region.Id);
                    }
                });

                $scope.ChangeCity = function () {
                    $scope.selectcity = $scope.City;
                };

            }
        }
    })
```

> Tips,
>
> 1. `$watch` `scope.Region` which is two-way-binding from the "Region" drop-down-list.
> 2. Set the value of `$scope.MyCity`, which is two-way binding as well. We will use this `ngModel` in the next directive.

### Companies

* HTML

```
<my-company selectcity="MyCity">
```

* JS

```
app.directive('myCompany', function () {
        return {
            //restrict: "A",
            scope: {
                selectcity: "="
            },
            template: "<span>{{companies}}</span>",
            link: function ($scope, $element) {
                $scope.$watch("selectcity", function (newValue, oldValue) {
                    if (newValue != null && newValue != {}) {
                        var companies = "";
                        switch ($scope.selectcity.Name) {
                            case "Taipei":
                                companies = "China-trust bank, SYSTEX, Wahlee ...";
                                break;
                            case "Linkou":
                                companies = "Inotera memories ...";
                                break;
                            case "Tainan":
                                companies = "TSMC, Chimei ...";
                                break;
                            case "Kaohsiung":
                                companies = "Foxconn ...";
                                break;
                        }

                        $scope.companies = companies;
                    }
                });
            }
        }
    })
```

([See sample codes on CodePen](http://codepen.io/KarateJB/pen/jrEZaB))


text:
export declare const MouseEvent: MouseEvent;
export declare const KeyboardEvent: KeyboardEvent;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RunChallenge.Models
{
    public class Workout
    {
        public int Id { get; set; }

        public string UserId { get; set; }

        public virtual User User { get; set; }

        public float Distance { get; set; }

        public TimeSpan Time { get; set; }

        public string Location { get; set; }

        public DateTime Date { get; set; }

        public string Pace { get; set; }

        public string KmHour { get; set; }

        public int TimeInSeconds { get; set; }

        public string Comment { get; set; }
    }
}


text:
import {h} from 'react-markup'
import React, {PropTypes} from 'react'
const {string, bool, arrayOf, shape, func} = PropTypes
import prefixer from 'bem-prefixer'

import QuestionTitle from './elements/question-title'

const bem = prefixer('questionnaire-radio')

class Radio extends React.Component {
    handleChange = (value) => {
        this.props.onChange(value)
    }

    render() {
        const {name, value, title, options, mandatory} = this.props
        return h(bem('div'),
            h(QuestionTitle, {mandatory}, title),
            h(bem('div#options'),
                options.map((option) => (
                    h(bem('button', 'input', option.value === value ? ['is-checked'] : []), {
                        key: option.value,
                        name, // todo: need to guarantee, that name is globaly unique, need to build full name including page name, or generate random name
                        value: option.value,
                        checked: option.value === value,
                        onClick: this.handleChange.bind(this, option.value),
                    }, option.title)
                ))
            )
        )
    }
}

Radio.propTypes = {
    name: string.isRequired,
    title: string.isRequired,
    value: string.isRequired,
    options: arrayOf(shape({
        title: string.isRequired,
        value: string.isRequired,
    }).isRequired),
    onChange: func.isRequired,
    mandatory: bool,
}

Radio.defaultProps = {
    mandatory: false,
}

export default Radio


text:
package javax.batch.api;

import javax.batch.runtime.StepExecution;

public interface Decider {
    String decide(StepExecution[] executions) throws Exception;
}


text:
import time

from twisted.internet import defer, task, reactor
from twisted.web import server
from twisted.web.resource import Resource

import amfast
from amfast.class_def.as_types import AsNoProxy
from channel import ChannelSet, HttpChannel
from endpoint import AmfEndpoint
import flex_messages as messaging
import connection_manager as cm

class TwistedChannelSet(ChannelSet):
    """A ChannelSet optimized for use with Twisted."""

    def render_POST(self, request):
        channel_name = request.path[1:]
        channel = self.getChannel(channel_name)
        return channel.render_POST(request)

    def scheduleClean(self):
        cleaner = task.LoopingCall(self.clean)
        cleaner.start(self.clean_freq, False)

    def notifyConnections(self, topic, sub_topic):
        reactor.callLater(0, self._notifyConnections, topic, sub_topic)

    def _notifyConnections(self, topic, sub_topic):
        iter = self.subscription_manager.iterSubscribers(topic, sub_topic)
        def _notify():
            try:
                connection_id = iter.next()
                try:
                    connection = self.connection_manager.getConnection(connection_id, False)
                except cm.NotConnectedError:
                    pass
                else:
                    if connection.notify_func is not None:
                        reactor.callLater(0, connection.notify_func)
                reactor.callLater(0, _notify)
            except StopIteration:
                pass
        reactor.callLater(0, _notify)

    def clean(self):
        if amfast.log_debug is True:
            amfast.logger.debug("Cleaning channel.")

        current_time = time.time()
        iter = self.connection_manager.iterConnectionIds()

        def _clean():
            try:
                connection_id = iter.next()
                reactor.callLater(0, self.cleanConnection, connection_id, current_time)
                reactor.callLater(0, _clean)
            except StopIteration:
                pass
        reactor.callLater(0, _clean)

class TwistedChannel(Resource, HttpChannel):
    """An AMF messaging channel that can be used with Twisted Web."""

    # This attribute is added to packets
    # that are waiting for a long-poll
    # to receive a message.
    MSG_NOT_COMPLETE = '_msg_not_complete'

    # This attribute is added to store
    # Twisted's request var on the packet,
    # so that it can be available to targets.
    TWISTED_REQUEST = '_twisted_request'

    def __init__(self, *args, **kwargs):

        Resource.__init__(self)
        HttpChannel.__init__(self, *args, **kwargs)

    def render_POST(self, request):
        """Process an incoming AMF packet."""
        if request.content:
            d = defer.Deferred()
            d.addCallbacks(request.content.read, self.fail, errbackArgs=(request,))
            d.addCallbacks(self.decode, self.fail, callbackArgs=(request,), errbackArgs=(request,))
            d.addCallbacks(self.invoke, self.fail, errbackArgs=(request,))
            d.addCallbacks(self.checkComplete, self.fail, callbackArgs=(request,), errbackArgs=(request,))
            d.callback(int(request.getHeader('Content-Length')))

            return server.NOT_DONE_YET

    def decode(self, raw_request, request):
        """Overridden to add Twisted's request object onto the packet."""
        decoded = HttpChannel.decode(self, raw_request)
        setattr(decoded, self.TWISTED_REQUEST, request)
        return decoded

    def getDeferred(self, msg):
        """Returns a Deferred object if a message contains a Deferred in its body,
        or False if message is not deferred.
        """
        if msg.is_flex_msg:
            body = msg.body.body
            if isinstance(body, defer.Deferred):
                return body
        else:
            body = msg.body
            if isinstance(body, defer.Deferred):
                return body
        return False

    def completeDeferreds(self, results, response, request, deferred_msgs):
        """A response's deferred methods have completed."""
        for i, result in enumerate(results):
            msg = deferred_msgs[i]

            if result[0] is False:
                # Invokation failed
                msg.convertFail(result[1].value)
            else:
                if msg.is_flex_msg:
                    msg.body.body = result[1]
                else:
                    msg.body = result[1]

        d = defer.Deferred()
        d.addCallbacks(self.encode, self.fail, errbackArgs=(request,))
        d.addCallbacks(self.finish, self.fail, callbackArgs=(request,),
            errbackArgs=(request,))
        d.callback(response)

    def checkComplete(self, response, request):
        """Checks to determine if the response message is ready
        to be returned to the client, and defers the response if
        ready.
        """

        if hasattr(response, self.MSG_NOT_COMPLETE):
            # long-poll operation.
            # response is waiting for a message to be published.
            return

        # Check for deferred messages
        deferreds = []
        deferred_msgs = []
        for msg in response.messages:
            deferred = self.getDeferred(msg)
            if deferred is not False:
                deferreds.append(deferred)
                deferred_msgs.append(msg)

        if len(deferreds) > 0:
            dl = defer.DeferredList(deferreds)
            dl.addCallbacks(self.completeDeferreds, self.fail,
                callbackArgs=(response, request, deferred_msgs), errbackArgs=(request,))
            return

        # Message is complete, encode and return
        d = defer.Deferred()
        d.addCallbacks(self.encode, self.fail, errbackArgs=(request,))
        d.addCallbacks(self.finish, self.fail, callbackArgs=(request,), errbackArgs=(request,))
        d.callback(response)

    def finish(self, raw_response, request):
        """Send response to client when message is complete."""
        request.setHeader('Content-Type', self.CONTENT_TYPE)
        request.write(raw_response)
        request.finish()

    def fail(self, failure, request, code=500, message='Internal Server Error'):
        request.setResponseCode(500, message)
        self.finish(message, request)

    def setupPollRequest(self, packet, connection):
        """Setup a request for a long-poll operation."""

        # Set flag so self.finish
        # does not get called when
        # response packet is returned
        # from self.invoke.
        setattr(packet.response, self.MSG_NOT_COMPLETE, True)

        request = getattr(packet, self.TWISTED_REQUEST)

        return request

    def finishPoll(self, request, packet, message, messages):
        """Finish a request that has been waiting for messages."""

        if request.finished:
            # Someone else has already called this function,
            # or twisted has finished the request for some other reason.
            return

        if isinstance(self.endpoint, AmfEndpoint):
            # Make sure messages are not encoded as an ArrayCollection
            messages = AsNoProxy(messages)
        message.response_msg.body.body = messages

        delattr(packet.response, self.MSG_NOT_COMPLETE)
        self.checkComplete(packet.response, request)

    def _waitForMessage(self, packet, message, connection):
        """Overridden to be non-blocking."""

        request = self.setupPollRequest(packet, connection)

        timeout_call = None
        def _notify():
            # This function gets called when a message is published,
            # or wait_interval is reached.
            if timeout_call is not None and timeout_call.active():
                # Disable time out callback
                timeout_call.cancel()

            # Disable notify function.
            connection.unSetNotifyFunc()

            # Get messages and add them
            # to the response message
            messages = self.channel_set.subscription_manager.pollConnection(connection)
            self.finishPoll(request, packet, message, messages)
        connection.setNotifyFunc(_notify)

        # Notify when wait_interval is reached
        if self.wait_interval > -1:
            timeout_call = reactor.callLater(float(self.wait_interval) / 1000, _notify)

        # Cleanup if client drops connection.
        _connectionLost = request.connectionLost
        def _connection_lost(reason):
            _connectionLost(reason)
            _notify()
        request.connectionLost = _connection_lost

        return ()

    def _pollForMessage(self, packet, message, connection):
        """Overridden to be non-blocking."""

        request = self.setupPollRequest(packet, connection)

        poller = task.LoopingCall(None)

        def _timeout():
            poller.stop()
            messages = self.channel_set.subscription_manager.pollConnection(connection)
            self.finishPoll(request, packet, message, messages)

        # Cleanup if client drops connection.
        _connectionLost = request.connectionLost
        def _connection_lost(reason):
            _connectionLost(reason)
            _timeout()
        request.connectionLost = _connection_lost

        if self.wait_interval > -1:
            timeout_call = reactor.callLater(float(self.wait_interval) / 1000, _timeout)
        else:
            timeout_call = None

        def _poll():
            messages = self.channel_set.subscription_manager.pollConnection(connection)
            if len(messages) > 0:
                poller.stop()
                if timeout_call is not None and timeout_call.active():
                    # Disable time out callback
                    timeout_call.cancel()

                self.finishPoll(request, packet, message, messages)
            elif connection.connected is False:
                _timeout()

        poller.f = _poll
        poller.start(float(self.poll_interval) / 1000)

        return ()

class StreamingTwistedChannel(TwistedChannel):
    """Handles streaming http connections."""

    def __init__(self, name, max_connections=-1, endpoint=None,
        timeout=1200, wait_interval=0, heart_interval=30000):
        TwistedChannel.__init__(self, name, max_connections, endpoint,
            timeout, wait_interval)

        self.heart_interval = heart_interval

    def render_POST(self, request):
        """Process an incoming AMF packet."""

        if request.getHeader('Content-Type') == self.CONTENT_TYPE:
            # Regular AMF message
            return TwistedChannel.render_POST(self, request)

        request.setHeader('Content-Type', self.CONTENT_TYPE)

        # Create streaming message command
        msg = messaging.StreamingMessage()
        msg.parseArgs(request.args)

        d = defer.Deferred()
        if msg.operation == msg.OPEN_COMMAND:
            d.addCallbacks(self.startStream, self.fail, callbackArgs=(request,), errbackArgs=(request,))
            d.callback(msg)
            return server.NOT_DONE_YET
        if msg.operation == msg.CLOSE_COMMAND:
            d.addCallbacks(self.stopStream, self.fail, callbackArgs=(request,), errbackArgs=(request,))
            d.callback(msg)
            return server.NOT_DONE_YET

    def startStream(self, msg, request):
        """Get this stream rolling!"""

        connection = self.channel_set.connection_manager.getConnection(msg.headers.get(msg.FLEX_CLIENT_ID_HEADER))

        if self.channel_set.notify_connections is True:
            poller = None
        else:
            # Repeatedly poll for messages.
            poller = task.LoopingCall(None)

        # Remove notify function if client drops connection.
        _connectionLost = request.connectionLost
        def _connection_lost(reason):
            self.channel_set.disconnect(connection)
            connection.unSetNotifyFunc()
            _connectionLost(reason)
        request.connectionLost = _connection_lost

        # This function gets called when a message is published.
        def _notify():
            if connection.connected is False:
                if poller is not None:
                    poller.stop()

                connection.unSetNotifyFunc()
                msg = messaging.StreamingMessage.getDisconnectMsg()
                request.write(messaging.StreamingMessage.prepareMsg(msg, self.endpoint))
                request.finish()
                return

            msgs = self.channel_set.subscription_manager.pollConnection(connection)
            for msg in msgs:
                request.write(messaging.StreamingMessage.prepareMsg(msg, self.endpoint))
        connection.setNotifyFunc(_notify)

        if poller is not None:
            poller.f = _notify
            poller.start(float(self.poll_interval) / 1000, False)

        # Acknowledge connection
        response = msg.acknowledge()
        response.body = connection.id
        self.sendMsg(request, response)

        # Prime request with bytes so
        # client will start responding.
        request.write(chr(messaging.StreamingMessage.NULL_BYTE) * self.KICKSTART_BYTES)

        self.startBeat(connection, request)

    def sendMsg(self, request, msg):
        """Send a message to the client."""

        request.write(messaging.StreamingMessage.prepareMsg(msg, self.endpoint))

    def stopStream(self, msg, request):
        connection = self.channel_set.connection_manager.getConnection(msg.headers.get(msg.FLEX_CLIENT_ID_HEADER))
        self.channel_set.disconnect(connection)

    def startBeat(self, connection, request):
        # Send out heart beat.
        looper = task.LoopingCall(None)
        def _beat():
            """Keep calling this method as long as the connection is alive."""
            if connection.connected is False:
                looper.stop()
                return

            request.write(chr(messaging.StreamingMessage.NULL_BYTE))

        looper.f = _beat
        looper.start(float(self.heart_interval) / 1000, False)


text:
\input{preamble.tex}

\input{chapters/02usecase.tex}

\input{finish.tex}


text:
/*
 * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
 * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
 *
 * 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 including the dates of first publication and
 * either this permission notice or a reference to
 * http://oss.sgi.com/projects/FreeB/
 * 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
 * SILICON GRAPHICS, INC. 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.
 *
 * Except as contained in this notice, the name of Silicon Graphics, Inc.
 * shall not be used in advertising or otherwise to promote the sale, use or
 * other dealings in this Software without prior written authorization from
 * Silicon Graphics, Inc.
 */
/*
*/

#ifndef _DIRECTEDLINE_H
#define _DIRECTEDLINE_H

#include "definitions.h"
#include "sampledLine.h"

enum {INCREASING, DECREASING};

class directedLine {
  short direction; /*INCREASING or DECREASING*/
  sampledLine* sline;
  directedLine* next; /*double linked list*/
  directedLine* prev; /*double linked list*/

  /*in case we need a list of polygons each
   *consisting of a double linked list
   */
  directedLine* nextPolygon;

  /*optimization make cutoff polygon faster*/
/*  directedLine* prevPolygon;*/

  Int rootBit; /*1 if this is a root of the polygon, set by setRootBit*/
               /*and reset by resetRootBit()*/

  directedLine* rootLink; /*fast root-finding*/

public:
  directedLine(short dir, sampledLine* sl);
  directedLine();
  ~directedLine();

  void init(short dir, sampledLine* sl);

  Real* head(); /*points[0] if INCREASING, points[n-1] otherwise*/
  Real* tail(); /*points[n-1] if INCREASING, points[0] otherwise*/
  Real* getVertex(Int i); /*points[i] if INCREASING, points[n-1-i] otherwise*/
  Int get_npoints() {return sline->get_npoints();}
  directedLine* getPrev() {return prev;}
  directedLine* getNext() {return next;}
  directedLine* getNextPolygon()  {return nextPolygon;}
  sampledLine*  getSampledLine()  {return sline;}

  short getDirection(){return direction;}
  void putDirection(short dir) {direction = dir;}
  void putPrev(directedLine *p) {prev = p;}
  void putNext(directedLine *p) {next = p;}

  /*insert a new line between prev and this*/
  void insert(directedLine* nl);

  /*delete all the polygons following the link: nextPolygon.
   *notice that sampledLine is not deleted. The caller is
   *responsible for that
   */
  void  deletePolygonList();
  void  deleteSinglePolygon();

  void  deleteSinglePolygonWithSline(); //also delete sanmpled line
  void  deletePolygonListWithSline(); //also delete sanmpled line

  void deleteSingleLine(directedLine* dline);
  directedLine* deleteDegenerateLines();
  directedLine* deleteDegenerateLinesAllPolygons();
  directedLine* cutIntersectionAllPoly(int& cutOccur);

  /*check to see if the list forms a closed polygon
   *return 1 if yes
   */
  short isPolygon();

  Int compInY(directedLine* nl);
  Int compInX(directedLine* nl);

  /*return an array of pointers.
   *the
   */
  directedLine** sortAllPolygons();

  Int numEdges();
  Int numEdgesAllPolygons();
  Int numPolygons();

  /*check if the head of this edge is connected to
   *the tail of the prev
   */
  short isConnected();

  Real polyArea();

  void printSingle();
  void printList();
  void printAllPolygons();
  void writeAllPolygons(char* filename);

  /*insert a polygon: using nextPolygon*/
  directedLine* insertPolygon(directedLine* newpolygon);
  directedLine* cutoffPolygon(directedLine *p);

  Int toArraySinglePolygon(directedLine** array, Int index);
  directedLine** toArrayAllPolygons(Int& total_num_edges);

  void connectDiagonal(directedLine* v1, directedLine* v2,
			   directedLine** ret_p1,
			   directedLine** ret_p2,
			   sampledLine** generatedLine, directedLine* list);

  /*generate two slines
   */
  void connectDiagonal_2slines(directedLine* v1, directedLine* v2,
			   directedLine** ret_p1,
			   directedLine** ret_p2,
			   directedLine* list);

  Int samePolygon(directedLine* v1, directedLine* v2);
  void setRootBit() {rootBit = 1;}
  void resetRootBit() {rootBit = 0;}
  directedLine* findRoot();

  void rootLinkSet(directedLine* r) {rootLink = r;}
  directedLine* rootLinkFindRoot();

  //the chain from begin to end is deleted (the space is deallocated)
  //and a new edge(which connectes the head of begin and the tail of end)
  // is inserted. The new polygon is returned.
  //notice that "this" is arbitrary
  directedLine* deleteChain(directedLine* begin, directedLine* end);
};

directedLine*  readAllPolygons(char* filename);

extern Int compV2InY(Real A[2], Real B[2]);
extern Int compV2InX(Real A[2], Real B[2]);

#endif


text:
package org.jkiss.dbeaver.ui.editors;

import org.eclipse.ui.IEditorPart;
import org.jkiss.dbeaver.model.struct.DBSObject;

/**
 * IDatabaseModellerEditor - editor which supports database object modelling
 */
public interface IDatabaseModellerEditor extends IEditorPart
{
    boolean isModelEditEnabled();

    boolean containsModelObject(DBSObject object);

}


text:
var InsightRestClient = require('..').RestClient;
var cli = new InsightRestClient();
cli.lastBlock().then(console.log)


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class EmpleadoController extends CI_Controller {

    private $styles = array();
    private $scripts = array();

    public function __construct() {
        parent::__construct();
        $this->load->model(array("mod_empleado"));
        $this->load->helper('cookie');
    }

    public function index() {
        if ($this->session->userdata("usuario") && check_permission(BUSCAR_EMPLEADO)) {
            $this->styles[] = '<link href="'.asset_url().'css/empleado.css" rel="stylesheet">';

            $this->scripts[] = '';
            $this->scripts[] = '';
            $this->scripts[] = '';
            $this->scripts[] = '';
            $this->scripts[] = '';
            $this->scripts[] = '';

            // Imprimir vista con datos
            $data["styles"] = $this->styles;
            $data["scripts"] = $this->scripts;
            $component["content"] = $this->load->view("empleado/search", $data, true);
            $this->load->view("template/body_main", $component);
        } else {
            header("Location: " . base_url());
        }
    }

    public function paginate() {
        if ($this->session->userdata("usuario") && check_permission(BUSCAR_EMPLEADO)) {
            $nTotal = $this->mod_empleado->count_all($_POST['sSearch']);

            $data = $this->mod_empleado->get_paginate($_POST['iDisplayLength'], $_POST['iDisplayStart'], $_POST['sSearch']);

            $aaData = array();

            foreach ($data as $row) {

                $estado = "";
                $opciones = "";
                if ($this->session->userdata("usuario") && check_permission(MODIFICAR_EMPLEADO)) {
                    $opciones .= '<button type="button" class="btn btn-primary btn-modificar" data-toggle="tooltip" data-placement="top" title="Actualizar"></button> ';
                }
                if ($row->esta_emp == "1") {
                    $estado = 'Habilitado';
                    if ($this->session->userdata("usuario") && check_permission(DESHABILITAR_EMPLEADO)) {
                        $opciones.= '<form method="post" class="deshabilitar_emp" action="'.base_url('empleado/deshabilitar').'" style="display: inline-block;"><input type="hidden" name="codi_emp" value="'.$row->codi_emp.'"><button type="submit" class="btn btn-warning btn-deshabilitar" data-toggle="tooltip" data-placement="top" title="Deshabilitar"></button></form> ';
                    }
                } else if ($row->esta_emp == "0") {
                    $estado = 'Deshabilitado';
                    if ($this->session->userdata("usuario") && check_permission(HABILITAR_EMPLEADO)) {
                        $opciones.= '<form method="post" class="habilitar_emp" action="'.base_url('empleado/habilitar').'" style="display: inline-block;"><input type="hidden" name="codi_emp" value="'.$row->codi_emp.'"><button type="submit" class="btn btn-success" data-toggle="tooltip" data-placement="top" title="Habilitar"></button></form> ';
                    }
                }
                if ($this->session->userdata("usuario") && check_permission(ELIMINAR_EMPLEADO)) {
                        $opciones.= '<form method="post" class="eliminar_emp" action="'.base_url('empleado/eliminar').'" style="display: inline-block;"><input type="hidden" name="codi_emp" value="'.$row->codi_emp.'"><button type="submit" class="btn btn-danger" data-toggle="tooltip" data-placement="top" title="Eliminar"></button></form>';
                }
                $opciones .= "";

                $aaData[] = array(
                    "codi_emp" => $row->codi_emp,
                    "full_emp" => $row->apel_emp . (($row->apel_emp != "") ? ', ' : "") . $row->nomb_emp,
                    "apel_emp" => $row->apel_emp,
                    "nomb_emp" => $row->nomb_emp,
                    "carg_emp" => $row->carg_emp,
                    "docu_emp" => $row->docu_emp,
                    "ofic_emp" => $row->ofic_emp,
                    "tipo_emp" => $row->tipo_emp,
                    "obsv_emp" => $row->obsv_emp,
                    "estado" => $estado,
                    "opciones" => $opciones
                );
            }

            $aa = array(
                'sEcho' => $_POST['sEcho'],
                'iTotalRecords' => $nTotal,
                'iTotalDisplayRecords' => $nTotal,
                'aaData' => $aaData);

            print_r(json_encode($aa));
        } else {
            header("Location: " . base_url());
        }
    }

    public function check_full_emp() {
        echo $this->mod_empleado->check_full_emp($this->input->post('full_emp'));
    }

    public function check_full_emp_actualizar() {
        echo $this->mod_empleado->check_full_emp_actualizar($this->input->post('codi_emp'), $this->input->post('full_emp'));
    }

    public function save() {

        $apel_emp = $this->input->post('apel_emp');
        $nomb_emp = $this->input->post('nomb_emp');
        $carg_emp = $this->input->post('carg_emp');
        $docu_emp = $this->input->post('docu_emp');
        $ofic_emp = $this->input->post('ofic_emp');
        $tipo_emp = $this->input->post('tipo_emp');
        $obsv_emp = $this->input->post('obsv_emp');

        if ($this->mod_empleado->check_full_emp($apel_emp.', '.$nomb_emp) == "true") {
            $data = array(
                'apel_emp' => $apel_emp,
                'nomb_emp' => $nomb_emp,
                'carg_emp' => $carg_emp,
                'docu_emp' => $docu_emp,
                'ofic_emp' => $ofic_emp,
                'tipo_emp' => $tipo_emp,
                'obsv_emp' => $obsv_emp,
                'esta_emp' => '1'
            );
            $codi_emp = $this->mod_empleado->save($data);

            $type_system = "success";
            $message_system = "El empleado ha sido registrado con éxito";
        } else {
            $type_system = "error";
            $message_system = "El empleado ya existe";
        }
        set_message_system($type_system, $message_system);

        header('Location: ' . base_url('empleado'));
    }

    public function update() {

        $codi_emp = $this->input->post('codi_emp');
        $apel_emp = $this->input->post('apel_emp');
        $nomb_emp = $this->input->post('nomb_emp');
        $carg_emp = $this->input->post('carg_emp');
        $docu_emp = $this->input->post('docu_emp');
        $ofic_emp = $this->input->post('ofic_emp');
        $tipo_emp = $this->input->post('tipo_emp');
        $obsv_emp = $this->input->post('obsv_emp');

        if ($this->mod_empleado->check_full_emp_actualizar($codi_emp, $apel_emp.', '.$nomb_emp) == "true") {
            $data = array(
                'apel_emp' => $apel_emp,
                'nomb_emp' => $nomb_emp,
                'carg_emp' => $carg_emp,
                'docu_emp' => $docu_emp,
                'ofic_emp' => $ofic_emp,
                'obsv_emp' => $obsv_emp,
                'tipo_emp' => $tipo_emp
            );

            $type_system = "success";
            $message_system = "El empleado ha sido actualizado con éxito";

            $this->mod_empleado->update($codi_emp, $data);

        } else {
            $type_system = "error";
            $message_system = "El empleado ya existe";
        }

        set_message_system($type_system, $message_system);

        header('Location: ' . base_url('empleado'));
    }

    public function habilitar() {
        $codi_emp = $this->input->post('codi_emp');
        $data = array(
            'esta_emp' => '1'
        );
        $this->mod_empleado->update($codi_emp, $data);

        $type_system = "success";
        $message_system = "El empleado ha sido habilitado con éxito";

        set_message_system($type_system, $message_system);

        header('Location: ' . base_url('empleado'));
    }

    public function deshabilitar() {
        $codi_emp = $this->input->post('codi_emp');
        $data = array(
            'esta_emp' => '0'
        );
        $this->mod_empleado->update($codi_emp, $data);

        $type_system = "success";
        $message_system = "El empleado ha sido deshabilitado con éxito";

        set_message_system($type_system, $message_system);

        header('Location: ' . base_url('empleado'));
    }

    public function eliminar() {
        $codi_emp = $this->input->post('codi_emp');
        $data = array(
            'esta_emp' => '-1'
        );
        $this->mod_empleado->update($codi_emp, $data);

        $type_system = "success";
        $message_system = "El empleado ha sido eliminado con éxito";

        set_message_system($type_system, $message_system);

        header('Location: ' . base_url('empleado'));
    }

}


text:
class CreateFriends < ActiveRecord::Migration
  def self.up
    create_table :friends do |t|
      t.integer :from
      t.integer :to
      t.timestamps
    end
  end

  def self.down
    drop_table :friends
  end
end


text:
class Calendar < ActiveRecord::Base
  has_many :meals
  has_many :components, through: :meals
  after_save :clean_components

  def component_list
    components.map(&:name)
  end

  def component_list=(names_string)
    components.delete_all
    names_string.split(',').map!(&:strip).each do |name|
      unless components.where(name: name).exists?
        component = Component.find_or_initialize_by(name: name)
        components << component
      end
    end
  end

  def clean_components
    Component.clean_unreferenced
  end
end


text:
jQuery(document).ready( function($){
	jQuery(".footer_container").click(function(){
		SetCookie( 'hide_popup', '1', 14);
		window.location = $('#target_url').val();
	});

	// Magnific Popup
	$('.spp-ddl-popup').magnificPopup({
		type: 'iframe',
		iframe: {
			patterns: {
				sppddl: {
					index: '',
					src: '%id%'
				}
			}
		}
	});

}) // global end

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString()+"; path=/";;
}

function readCookie(cookieName) {
 var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
 var sMatch = (' '+document.cookie).match(re);
 if (cookieName && sMatch) return unescape(sMatch[1]);
 return '';
}


text:
<?php

namespace App\Containers\AppSection\Authorization\Tasks;

use App\Containers\AppSection\Authorization\Models\Role;
use App\Containers\AppSection\User\Models\User;
use App\Ship\Parents\Tasks\Task as ParentTask;
use Illuminate\Contracts\Auth\Authenticatable;

class AssignRolesToUserTask extends ParentTask
{
    /**
     * @param User $user
     * @param array|int|string|Role $roles
     * @return Authenticatable
     */
    public function run(User $user, Role|array|int|string $roles): Authenticatable
    {
        return $user->assignRole($roles);
    }
}


text:
@interface ASPTableViewController ()
@property (nonatomic, strong) NSMutableDictionary *rowClasses;
@end

@implementation ASPTableViewController

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.rowClasses = [NSMutableDictionary dictionary];
}

-(void)setJsonDefinitionURL:(NSURL *)url
{
    _jsonDefinitionURL = url;

    if (url) {

        NSError *error = nil;
        NSInputStream *stream = [[NSInputStream alloc] initWithURL:url];
        [stream open];
        self.sections = [NSJSONSerialization JSONObjectWithStream:stream
                                                          options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
                                                            error:&error];

        if (error) {
            NSLog(@"Failed to read table definition %@", url);
        }
    }
    else {
        self.sections = [NSMutableArray array];
    }
}

-(NSMutableDictionary*)cellInfoFromIndexPath:(NSIndexPath*)indexPath
{
    NSMutableDictionary *section = self.sections[indexPath.section];
    NSMutableArray *cells = section[@"rows"];
    NSMutableDictionary *cellInfo = cells[indexPath.row];

    return cellInfo;
}

-(NSIndexPath*) indexPathForRowWithKey:(NSString*)key andValue:(NSString*)value {
    NSInteger sectionIndex = 0;
    for (NSMutableDictionary *section in self.sections) {
        NSMutableArray *cells = section[@"rows"];
        NSInteger row = 0;
        for (NSMutableDictionary *cellInfo in cells) {
            if ([cellInfo[key] isEqualToString:value]) {
                return [NSIndexPath indexPathForRow:row inSection:sectionIndex];
            }
            row++;
        }
        sectionIndex++;
    }
    return nil;
}

#pragma mark - Table view delegate

-(void)performActionForCell:(NSMutableDictionary*)cellInfo
{
    // Built in actions; we invoke one of these:
    // 1. Perform a selector
    // 2. Push a storyboard's view controller
    // 3. Perform a segue
    NSString *selector = cellInfo[@"action"];
    NSString *segue = cellInfo[@"segue"];
    NSString *storyboardName = cellInfo[@"storyboard"];
    NSString *viewControllerId = cellInfo[@"viewControllerId"];

    if (selector) {
        // We're going to be passing a parameter, ensure the action selector ends with a colon.
        NSString *selectorWithParam;
        if (! [selector hasSuffix:@":"]) {
            selectorWithParam = [selector stringByAppendingString:@":"];
        }

        // Try version with a parameter first.
        SEL selWithParam;
        selWithParam = NSSelectorFromString(selectorWithParam);
        if (selWithParam && [self respondsToSelector:selWithParam]) {
            // Call selector with a param
            IMP imp = [self methodForSelector:selWithParam];
            void (*func)(id, SEL, NSMutableDictionary*) = (void *)imp;
            func(self, selWithParam, cellInfo);
        }
        else {
            // Call selector without a param
            SEL sel = NSSelectorFromString(selector);
            IMP imp = [self methodForSelector:sel];
            void (*func)(id, SEL) = (void *)imp;
            func(self, sel);
        }
    }
    else if (storyboardName) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
        UIViewController *vc;
        if (viewControllerId) {
            vc = [storyboard instantiateViewControllerWithIdentifier:viewControllerId];
        }
        else {
            vc = [storyboard instantiateInitialViewController];
        }

        [self prepareForStoryboard:storyboardName viewControllerId:viewControllerId fromCell:cellInfo destination:vc];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (segue) {
        [self performSegueWithIdentifier:segue sender:self];
    }
}

-(void)prepareForStoryboard:(NSString *)storyboardName
           viewControllerId:(NSString*)viewControllerId
                   fromCell:(NSDictionary*)cellInfo
                destination:(UIViewController*)viewController
{
    // Can be overridden to prepare a destination viewController, cf prepareForSegue.
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *cellInfo = [self cellInfoFromIndexPath:indexPath];

    [self performActionForCell:cellInfo];
}

#pragma mark - Table View data source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *sectionDefinition = self.sections[section];
    NSArray *rows = sectionDefinition[@"rows"];
    return rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *rowDefinition = [self cellInfoFromIndexPath:indexPath];
    NSString *cellId = rowDefinition[@"type"];

    ASPTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    if ( ! [cell isKindOfClass:[ASPTableViewCell class]]) {
        NSLog(@"Cell must be a subclass of ASPTableViewCell!");
    }

    [cell configureInViewController:self fromRowDefinition:rowDefinition ];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *rowDefinition = [self cellInfoFromIndexPath:indexPath];

    CGFloat height = 44;
    Class class = self.rowClasses[rowDefinition[@"type"]];

    // Ask the cell's class how tall a row needs to be
    // to display the given row definition.
    // We have to ask the class, as the table view might
    // not yet have instantiated any actual cells for us to ask.
    SEL heightSelector = NSSelectorFromString(@"heightForRowDefinition:inViewController:");

    if (class && [class respondsToSelector:heightSelector]) {

        IMP imp = [class methodForSelector:heightSelector];
        CGFloat (*func)(id, SEL, NSMutableDictionary*, UIViewController*) = (void *)imp;
        height = func(class, heightSelector, rowDefinition, self);
    }

    return height;
}

#pragma mark - Cell class registration

// Rows must register their classes with us independently from the table view's
// registration, as we need to call class methods on them before the table view
// instatiates them.
-(void)registerClass:(Class)cellClass forCellType:(NSString *)identifier
{
    self.rowClasses[identifier] = cellClass;
    [self.tableView registerClass:cellClass forCellReuseIdentifier:identifier];
}

// Rows must register their classes with us independently from the table view's
// registration, as we need to call class methods on them before the table view
// instatiates them.
-(void)registerNib:(UINib*)nib forCellType:(NSString *)identifier ofClass:(Class)cellClass
{
    self.rowClasses[identifier] = cellClass;
    [self.tableView registerNib:nib forCellReuseIdentifier:identifier];
}

@end


text:
<?php

$input = file_get_contents('php://input');

if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $input)) {
	exit('fail');
}
libxml_disable_entity_loader(true);
$obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
if($obj instanceof SimpleXMLElement && !empty($obj->FeedBackId)) {
	$data = array(
		'openid' => trim($obj->OpenId),
		'appid' => trim($obj->AppId),
		'timestamp' => trim($obj->TimeStamp),
		'msgtype' => trim($obj->MsgType),
		'feedbackid' => trim($obj->FeedBackId),
		'transid' => trim($obj->TransId),
		'reason' => trim($obj->Reason),
		'solution' => trim($obj->Solution),
		'extinfo' => trim($obj->ExtInfo),
		'appsignature' => trim($obj->AppSignature),
		'signmethod' => trim($obj->SignMethod),
	);
	if (!empty($obj->PicInfo) && !empty($obj->PicInfo->item)) {
		foreach ($obj->PicInfo->item as $item) {
			$data['picinfo'][] = trim($item->PicUrl);
		}
	}
	require '../../framework/bootstrap.inc.php';
	WeUtility::logging('pay-rights', $input);
	$_W['uniacid'] = pdo_fetchcolumn("SELECT uniacid FROM ".tablename('account_wechats')." WHERE `key` = :key", array(':key' => $data['appid']));
	$setting = uni_setting($_W['uniacid'], array('payment'));
	$_W['weid'] = $_W['uniacid'];

	if (empty($setting['payment'])) {
		exit('failed');
	}
	$data['appkey'] = $setting['payment']['wechat']['signkey'];
	if (!checkSign($data)) {
		exit('failed');
	}
	if ($data['msgtype'] == 'request') {
		$insert = array(
			'weid' => $_W['weid'],
			'openid' => $data['openid'],
			'feedbackid' => $data['feedbackid'],
			'transid' => $data['transid'],
			'reason' => $data['reason'],
			'solution' => $data['solution'],
			'remark' => $data['extinfo'],
			'createtime' => $data['timestamp'],
			'status' => 0,
		);
		pdo_insert('shopping_feedback', $insert);
		exit('success');
	} elseif ($data['msgtype'] == 'confirm') {
		pdo_update('shopping_feedback', array('status' => 1), array('feedbackid' => $data['feedbackid']));
		exit('success');
	} elseif ($data['msgtype'] == 'reject') {
		pdo_update('shopping_feedback', array('status' => 2), array('feedbackid' => $data['feedbackid']));
		exit('success');
	} else {
		exit('failed');
	}
}
exit('failed');

function checkSign($data) {
	$string = '';
	$keys = array('appid', 'timestamp', 'openid', 'appkey');
	sort($keys);
	foreach($keys as $key) {
		$v = $data[$key];
		$key = strtolower($key);
		$string .= "{$key}={$v}&";
	}
	$string = sha1(rtrim($string, '&'));
	if ($data['appsignature'] == $string) {
		return true;
	} else {
		return false;
	}
}


text:
<?php

namespace MwBundle\Repository;

use AppBundle\Repository\DoelstellingRepositoryInterface;
use AppBundle\Repository\DoelstellingRepositoryTrait;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Metadata\ClassMetadata;
use MwBundle\Entity\Info;
use MwBundle\Entity\Verslag;

class KlantRepository extends EntityRepository implements DoelstellingRepositoryInterface
{
    use DoelstellingRepositoryTrait;

    public $economischDaklozenLocaties;

    public function setEconomischDaklozenLocaties($locaties)
    {
        $this->economischDaklozenLocaties = $locaties;
    }

    public function getCategory(): string
    {
        return DoelstellingRepositoryInterface::CAT_HULPVERLENING;
    }

    public function initDoelstellingcijfers(): void
    {
        $economischDaklozenLocatiesStr = implode(", ",$this->economischDaklozenLocaties);
        $this->addDoelstellingcijfer(
            "Aantal clienten dat een verslag heeft dat is vastgelegd in de periode, vanaf de locatie 'zonder zorg'.",
            "4155",
            "Zonder zorg",
            function($doelstelling,$startdatum,$einddatum){
                $r = $this->getAantalClientenLocatie($startdatum,$einddatum,["Zonder Zorg"]);
                return $r;
            }
        );

        $this->addDoelstellingcijfer(
            "Aantal clienten dat een verslag heeft dat is vastgelegd in de periode, vanaf de locaties '$economischDaklozenLocatiesStr'.",
            "4152",
            "Economisch daklozen",
            function($doelstelling,$startdatum,$einddatum){
                $r = $this->getAantalClientenLocatie($startdatum,$einddatum,$this->economischDaklozenLocaties);
                return $r;
            }
        );
        $losseLocaties = [
            "6550"=>'De Meeuw',
            "6551"=>'Claverhuis',
        ];

        foreach ($losseLocaties as $kpl=>$locatie) {
            $locatieArr = [$locatie];
            $this->addDoelstellingcijfer(
                "Aantal klanten op locatie $locatie dat in afgelopen periode een (nieuwe) waarvan de laatste intake datum binnen periode valt.",
                $kpl,
                $locatie,
                function($doelstelling,$startdatum,$einddatum) use ($locatieArr) {
                    $r = $this->getAantalClientenMetNieuweIntakeVoorLocaties($startdatum,$einddatum,$locatieArr);
                    return $r;
                }
            );
        }

    }
    private function getAantalClientenMetNieuweIntakeVoorLocaties($startdatum,$einddatum,$locaties)
    {
        $builder = $this->createQueryBuilder("klant");
        $builder->select("COUNT(DISTINCT klant.id) AS aantalKlanten")
//            ->innerJoin("klant.verslagen","verslag")
            ->innerJoin("klant.laatsteIntake","laatsteIntake")
            ->innerJoin("laatsteIntake.intakelocatie","locatie")
//            ->andWhere("verslag.type = :mw_verslagType")
            ->andWhere("DATE(laatsteIntake.intakedatum) BETWEEN :startdatum AND :einddatum")
            ->andWhere("locatie.naam IN (:locatieNamen)")
//            ->setParameter("mw_verslagType",Verslag::TYPE_MW)
            ->setParameter("startdatum",$startdatum)
            ->setParameter("einddatum",$einddatum)
            ->setParameter("locatieNamen",$locaties)
        ;

        $query = $builder->getQuery();
        $sql = $query->getSQL();
        $parameters = $query->getParameters();
        $result = $query->getSingleScalarResult();
        return $result;
    }

    private function getAantalClientenLocatie($startdatum,$einddatum,$locaties)
    {
        $builder = $this->createQueryBuilder("klant");
        $builder->select("COUNT(DISTINCT klant.id) AS aantalKlanten")
            ->innerJoin("klant.verslagen","verslag")
            ->innerJoin("verslag.locatie","locatie")
            ->andWhere("verslag.type = :mw_verslagType")
            ->andWhere("DATE(verslag.datum) BETWEEN :startdatum AND :einddatum")
            ->andWhere("locatie.naam IN (:locatieNamen)")
            ->setParameter("mw_verslagType",Verslag::TYPE_MW)
            ->setParameter("startdatum",$startdatum)
            ->setParameter("einddatum",$einddatum)
            ->setParameter("locatieNamen",$locaties)
        ;

        $query = $builder->getQuery();
        $sql = $query->getSQL();
        $parameters = $query->getParameters();
        $result = $query->getSingleScalarResult();
        return $result;
    }

}


text:
package com.amazonaws.services.cloudsearchv2.model;

/**
 * Option State
 */
public enum OptionState {

    RequiresIndexDocuments("RequiresIndexDocuments"),
    Processing("Processing"),
    Active("Active"),
    FailedToValidate("FailedToValidate");

    private String value;

    private OptionState(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *            real value
     * @return OptionState corresponding to the value
     */
    public static OptionState fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");

        } else if ("RequiresIndexDocuments".equals(value)) {
            return OptionState.RequiresIndexDocuments;
        } else if ("Processing".equals(value)) {
            return OptionState.Processing;
        } else if ("Active".equals(value)) {
            return OptionState.Active;
        } else if ("FailedToValidate".equals(value)) {
            return OptionState.FailedToValidate;
        } else {
            throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
        }
    }
}


text:
package ax25

import (
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"syscall"
	"time"

	"github.com/la5nta/wl2k-go/fbb"
	"github.com/tarm/goserial"
)

// KenwoodConn implements net.Conn using a
// Kenwood (or similar) TNC in connected transparent mode.
//
// Tested with Kenwood TH-D72 and TM-D710 in "packet-mode".
//
// TODO: github.com/term/goserial does not support setting the
// line flow control. Thus, KenwoodConn is not suitable for
// sending messages > the TNC's internal buffer size.
//
// We should probably be using software flow control (XFLOW),
// as hardware flow is not supported by many USB->RS232 adapters
// including the adapter build into TH-D72 (at least, not using the
// current linux kernel module.
type KenwoodConn struct{ Conn }

// Dial a packet node using a Kenwood (or similar) radio over serial
func DialKenwood(dev, mycall, targetcall string, config Config, logger *log.Logger) (*KenwoodConn, error) {
	if logger == nil {
		logger = log.New(os.Stderr, "", log.LstdFlags)
	}

	localAddr, remoteAddr := tncAddrFromString(mycall), tncAddrFromString(targetcall)
	conn := &KenwoodConn{Conn{
		localAddr:  AX25Addr{localAddr},
		remoteAddr: AX25Addr{remoteAddr},
	}}

	if dev == "socket" {
		c, err := net.Dial("tcp", "127.0.0.1:8081")
		if err != nil {
			panic(err)
		}
		conn.Conn.ReadWriteCloser = c
	} else {
		c := &serial.Config{Name: dev, Baud: int(B9600)}
		s, err := serial.OpenPort(c)
		if err != nil {
			return conn, err
		} else {
			conn.Conn.ReadWriteCloser = s
		}
	}

	conn.Write([]byte{3, 3, 3}) // ETX
	fmt.Fprint(conn, "\r\nrestart\r\n")
	for {
		line, _ := fbb.ReadLine(conn)

		if strings.HasPrefix(line, "cmd:") {
			fmt.Fprint(conn, "ECHO OFF\r") // Don't echo commands
			fmt.Fprint(conn, "FLOW OFF\r")
			fmt.Fprint(conn, "XFLOW ON\r")    // Enable software flow control
			fmt.Fprint(conn, "LFIGNORE ON\r") // Ignore linefeed (\n)
			fmt.Fprint(conn, "AUTOLF OFF\r")  // Don't auto-insert linefeed
			fmt.Fprint(conn, "CR ON\r")
			fmt.Fprint(conn, "8BITCONV ON\r") // Use 8-bit characters

			// Return to command mode if station of current I/O stream disconnects.
			fmt.Fprint(conn, "NEWMODE ON\r")

			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "MYCALL %s\r", mycall)
			fmt.Fprintf(conn, "HBAUD %d\r", config.HBaud)
			fmt.Fprintf(conn, "PACLEN %d\r", config.PacketLength)
			fmt.Fprintf(conn, "TXDELAY %d\r", config.TXDelay/_CONFIG_TXDELAY_UNIT)
			fmt.Fprintf(conn, "PERSIST %d\r", config.Persist)
			time.Sleep(500 * time.Millisecond)

			fmt.Fprintf(conn, "SLOTTIME %d\r", config.SlotTime/_CONFIG_SLOT_TIME_UNIT)
			fmt.Fprint(conn, "FULLDUP OFF\r")
			fmt.Fprintf(conn, "MAXFRAME %d\r", config.MaxFrame)
			fmt.Fprintf(conn, "FRACK %d\r", config.FRACK/_CONFIG_FRACK_UNIT)
			fmt.Fprintf(conn, "RESPTIME %d\r", config.ResponseTime/_CONFIG_RESPONSE_TIME_UNIT)
			fmt.Fprintf(conn, "NOMODE ON\r")

			break
		}
	}
	time.Sleep(2 * time.Second)

	fmt.Fprintf(conn, "\rc %s\r", targetcall)
	for {
		line, _ := fbb.ReadLine(conn)
		logger.Println(line)
		line = strings.TrimSpace(line)

		if strings.Contains(line, "*** CONNECTED to") {
			fmt.Fprint(conn, "TRANS\r\n")
			return conn, nil
		} else if strings.Contains(line, "*** DISCONNECTED") {
			logger.Fatal("got disconnect ", int(line[len(line)-1]))
		}
	}
}

func (c *KenwoodConn) Close() error {
	if !c.ok() {
		return syscall.EINVAL
	}

	// Exit TRANS mode
	time.Sleep(1 * time.Second)
	for i := 0; i < 3; i++ {
		c.Write([]byte{3}) // ETX
		time.Sleep(200 * time.Millisecond)
	}

	// Wait for prompt
	time.Sleep(1 * time.Second)

	// Disconnect
	fmt.Fprint(c, "\r\nD\r\n")
	for {
		line, _ := fbb.ReadLine(c)
		if strings.Contains(line, `DISCONN`) {
			log.Println(`Disconnected`)
			break
		}
	}
	return c.Conn.Close()
}


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Slide from '../Animation/Slide';
import Modal from '../Modal/Modal';

import { prefix, defaultProps } from '../utils';
import { DrawerProps } from './Drawer.d';

class Drawer extends React.Component<DrawerProps> {
  static propTypes = {
    classPrefix: PropTypes.string,
    placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
    show: PropTypes.bool,
    full: PropTypes.bool,
    children: PropTypes.node,
    className: PropTypes.string
  };
  static defaultProps = {
    placement: 'right'
  };

  render() {
    const { show, full, className, placement, classPrefix, ...props } = this.props;
    const addPrefix: Function = prefix(classPrefix);
    const classes = classNames(addPrefix(placement), className, {
      [addPrefix('full')]: full
    });

    const animationProps = {
      placement
    };

    return (
      <Modal
        {...props}
        drawer
        classPrefix={classPrefix}
        className={classes}
        show={show}
        animation={Slide}
        animationProps={animationProps}
      />
    );
  }
}

const EnhancedDrawer = defaultProps<DrawerProps>({
  classPrefix: 'drawer'
})(Drawer);

export default EnhancedDrawer;


text:
An ember addon that lets you generate ember models from an external schema source

## Installation

* `git clone` this repository
* `npm install`
* `bower install`

## Running

* `ember server`
* Visit your app at http://localhost:4200.

## Running Tests

* `ember test`
* `ember test --server`

## Building

* `ember build`

For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).


text:
namespace OmniSharp.Services
{
    public enum TransportType
    {
        Http,
        Stdio
    }
}


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

<title>TiuNoteHeader</title>
<meta name="date" content="2014-08-13">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

gov.va.med.lom.javaBroker.rpc.patient.models

Class TiuNoteHeader

java.lang.Object

gov.va.med.lom.javaBroker.rpc.BaseBean

gov.va.med.lom.javaBroker.rpc.patient.models.TiuNoteHeader

All Implemented Interfaces:

java.io.Serializable

public class TiuNoteHeader
extends BaseBean
implements java.io.Serializable

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

TiuNoteHeader()

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getAuthorDuz()

java.lang.String
getAuthorName()

java.util.Date
getDischargeDatetime()

java.lang.String
getDischargeDatetimeStr()

java.lang.String
getDocumentClass()

java.lang.String
getDocumentClassIen()

java.lang.String
getExpectedSignerDuz()

boolean
getHasChildren()

java.lang.String
getHospitalLocation()

int
getNumAssociatedImages()

java.lang.String
getParentIen()

java.lang.String
getPatientName()

java.util.Date
getReferenceDatetime()

java.lang.String
getReferenceDatetimeStr()

java.lang.String
getRequestIen()

java.lang.String
getSignatureStatus()

java.lang.String
getSubject()

java.lang.String
getTitle()

java.util.Date
getVisitDatetime()

java.lang.String
getVisitDatetimeStr()

void
setAuthorDuz(java.lang.String authorDuz)

void
setAuthorName(java.lang.String authorName)

void
setDischargeDatetime(java.util.Date dischargeDatetime)

void
setDischargeDatetimeStr(java.lang.String dischargeDateTime)

void
setDocumentClass(java.lang.String documentClass)

void
setDocumentClassIen(java.lang.String documentClassIen)

void
setExpectedSignerDuz(java.lang.String expectedSignerDuz)

void
setHasChildren(boolean hasChildren)

void
setHospitalLocation(java.lang.String hospitalLocation)

void
setNumAssociatedImages(int numAssociatedImages)

void
setParentIen(java.lang.String parentIen)

void
setPatientName(java.lang.String patientName)

void
setReferenceDatetime(java.util.Date referenceDatetime)

void
setReferenceDatetimeStr(java.lang.String referenceDateTime)

void
setRequestIen(java.lang.String requestIen)

void
setSignatureStatus(java.lang.String signatureStatus)

void
setSubject(java.lang.String subject)

void
setTitle(java.lang.String title)

void
setVisitDatetime(java.util.Date visitDatetime)

void
setVisitDatetimeStr(java.lang.String visitDateTime)

Methods inherited from class gov.va.med.lom.javaBroker.rpc.BaseBean

getDfn, getDuz, getIen, getRpcResult, setDfn, setDuz, setIen, setRpcResult

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TiuNoteHeader

public TiuNoteHeader()

Method Detail

getAuthorDuz

public java.lang.String getAuthorDuz()

setAuthorDuz

public void setAuthorDuz(java.lang.String authorDuz)

getAuthorName

public java.lang.String getAuthorName()

setAuthorName

public void setAuthorName(java.lang.String authorName)

getDischargeDatetimeStr

public java.lang.String getDischargeDatetimeStr()

setDischargeDatetimeStr

public void setDischargeDatetimeStr(java.lang.String dischargeDateTime)

getHasChildren

public boolean getHasChildren()

setHasChildren

public void setHasChildren(boolean hasChildren)

getHospitalLocation

public java.lang.String getHospitalLocation()

setHospitalLocation

public void setHospitalLocation(java.lang.String hospitalLocation)

getNumAssociatedImages

public int getNumAssociatedImages()

setNumAssociatedImages

public void setNumAssociatedImages(int numAssociatedImages)

getParentIen

public java.lang.String getParentIen()

setParentIen

public void setParentIen(java.lang.String parentIen)

getPatientName

public java.lang.String getPatientName()

setPatientName

public void setPatientName(java.lang.String patientName)

getReferenceDatetimeStr

public java.lang.String getReferenceDatetimeStr()

setReferenceDatetimeStr

public void setReferenceDatetimeStr(java.lang.String referenceDateTime)

getRequestIen

public java.lang.String getRequestIen()

setRequestIen

public void setRequestIen(java.lang.String requestIen)

getSignatureStatus

public java.lang.String getSignatureStatus()

setSignatureStatus

public void setSignatureStatus(java.lang.String signatureStatus)

getSubject

public java.lang.String getSubject()

setSubject

public void setSubject(java.lang.String subject)

getTitle

public java.lang.String getTitle()

setTitle

public void setTitle(java.lang.String title)

getVisitDatetimeStr

public java.lang.String getVisitDatetimeStr()

setVisitDatetimeStr

public void setVisitDatetimeStr(java.lang.String visitDateTime)

getDischargeDatetime

public java.util.Date getDischargeDatetime()

setDischargeDatetime

public void setDischargeDatetime(java.util.Date dischargeDatetime)

getReferenceDatetime

public java.util.Date getReferenceDatetime()

setReferenceDatetime

public void setReferenceDatetime(java.util.Date referenceDatetime)

getVisitDatetime

public java.util.Date getVisitDatetime()

setVisitDatetime

public void setVisitDatetime(java.util.Date visitDatetime)

getDocumentClassIen

public java.lang.String getDocumentClassIen()

setDocumentClassIen

public void setDocumentClassIen(java.lang.String documentClassIen)

getDocumentClass

public java.lang.String getDocumentClass()

setDocumentClass

public void setDocumentClass(java.lang.String documentClass)

getExpectedSignerDuz

public java.lang.String getExpectedSignerDuz()

setExpectedSignerDuz

public void setExpectedSignerDuz(java.lang.String expectedSignerDuz)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method