text:
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include "drill/drillc.hpp"
#include "drill/drillError.hpp"
#include "clientlib/channel.hpp"
#include "clientlib/drillClientImpl.hpp"
#include "clientlib/errmsgs.hpp"
#include "clientlib/logger.hpp"
#include "clientlib/rpcMessage.hpp"
#include "clientlib/utils.hpp"
#include "protobuf/GeneralRPC.pb.h"
#include "protobuf/UserBitShared.pb.h"

namespace Drill {

class DrillTestClient {

    public:

    DrillTestClient(Channel* pChannel):
    m_handshakeStatus(exec::user::SUCCESS),
    m_wbuf(MAX_SOCK_RD_BUFSIZE),
    m_rbuf(0){
            m_pChannel=pChannel;
            m_pError=NULL;
            m_coordinationId=Utils::s_randomNumber()%1729+1;
        }

        connectionStatus_t recvHandshake(){
            if(m_rbuf==NULL){
                m_rbuf = Utils::allocateBuffer(MAX_SOCK_RD_BUFSIZE);
            }

            m_pChannel->getIOService().reset();

            m_pChannel->getSocketStream().asyncRead(
                    boost::asio::buffer(m_rbuf, LEN_PREFIX_BUFLEN),
                    boost::bind(
                        &DrillTestClient::handleHandshake,
                        this,
                        m_rbuf,
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred)
                    );
            DRILL_MT_LOG(DRILL_LOG(LOG_DEBUG) << "DrillClientImpl::recvHandshake: async read waiting for server handshake response.\n";)
            m_pChannel->getIOService().run();
            if(m_rbuf!=NULL){
                Utils::freeBuffer(m_rbuf, MAX_SOCK_RD_BUFSIZE); m_rbuf=NULL;
            }

            if (m_pError != NULL) {
                DRILL_MT_LOG(DRILL_LOG(LOG_ERROR) << "DrillClientImpl::recvHandshake: failed to complete handshake with server."
                        << m_pError->msg << "\n";)
                    return static_cast<connectionStatus_t>(m_pError->status);
            }

            return CONN_SUCCESS;
        }

        void doReadFromSocket(ByteBuf_t inBuf, size_t bytesToRead, boost::system::error_code& errorCode) {
            // Check if bytesToRead is zero
            if(0 == bytesToRead) {
                return;
            }

            // Read all the bytes. In case when all the bytes were not read the proper
            // errorCode will be set.
            while(1){
                size_t dataBytesRead = m_pChannel->getSocketStream().readSome(boost::asio::buffer(inBuf, bytesToRead), errorCode);
                // Update the state
                bytesToRead -= dataBytesRead;
                inBuf += dataBytesRead;

                // Check if errorCode is EINTR then just retry otherwise break from loop
                if(EINTR != errorCode.value()) break;

                // Check if all the data is read then break from loop
                if(0 == bytesToRead) break;
            }
        }

        void handleHandshake(ByteBuf_t inBuf,
                const boost::system::error_code& err,
                size_t bytes_transferred) {
            boost::system::error_code error=err;
            DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Deadline timer cancelled." << std::endl;)
                if(!error){
                    rpc::InBoundRpcMessage msg;
                    uint32_t length = 0;
                    std::size_t bytes_read = rpc::lengthDecode(m_rbuf, length);
                    if(length>0){
                        const size_t leftover = LEN_PREFIX_BUFLEN - bytes_read;
                        const ByteBuf_t b = m_rbuf + LEN_PREFIX_BUFLEN;
                        const size_t bytesToRead=length - leftover;
                        doReadFromSocket(b, bytesToRead, error);

                        // Check if any error happen while reading the message bytes. If yes then return before decoding the Msg
                        if(error) {
                            DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "DrillClientImpl::handleHandshake: ERR_CONN_RDFAIL. "
                                    << " Failed to read entire handshake message. with error: "
                                    << error.message().c_str() << "\n";)
                                handleConnError(CONN_FAILURE, getMessage(ERR_CONN_RDFAIL, "Failed to read entire handshake message"));
                            return;
                        }

                        // Decode the bytes into a valid RPC Message
                        if (!decode(m_rbuf+bytes_read, length, msg)) {
                            DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "DrillClientImpl::handleHandshake: ERR_CONN_RDFAIL. Cannot decode handshake.\n";)
                                handleConnError(CONN_FAILURE, getMessage(ERR_CONN_RDFAIL, "Cannot decode handshake"));
                            return;
                        }
                    }else{
                        DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "DrillClientImpl::handleHandshake: ERR_CONN_RDFAIL. No handshake.\n";)
                            handleConnError(CONN_FAILURE, getMessage(ERR_CONN_RDFAIL, "No handshake"));
                        return;
                    }
                    exec::user::BitToUserHandshake b2u;
                    b2u.ParseFromArray(msg.m_pbody.data(), msg.m_pbody.size());
                    this->m_handshakeErrorId=b2u.errorid();
                    this->m_handshakeErrorMsg=b2u.errormessage();
                }else{
                    // boost error
                    if(error==boost::asio::error::eof){ // Server broke off the connection
                        handleConnError(CONN_HANDSHAKE_FAILED, getMessage(ERR_CONN_NOHSHAKE, DRILL_RPC_VERSION));
                    }else{
                        handleConnError(CONN_FAILURE, getMessage(ERR_CONN_RDFAIL, error.message().c_str()));
                    }
                    return;
                }
            return;
        }

        connectionStatus_t handleConnError(connectionStatus_t status, const std::string& msg){
            DrillClientError* pErr = new DrillClientError(status, DrillClientError::CONN_ERROR_START+status, msg);
            if(m_pError!=NULL){ delete m_pError; m_pError=NULL;}
            m_pError=pErr;
            return status;
        }

        connectionStatus_t sendSyncCommon(rpc::OutBoundRpcMessage& msg) {
            encode(m_wbuf, msg);
            boost::system::error_code ec;
            doWriteToSocket(reinterpret_cast<char*>(m_wbuf.data()), m_wbuf.size(), ec);

            if(!ec) {
                return CONN_SUCCESS;
            } else {
                return handleConnError(CONN_FAILURE, getMessage(ERR_CONN_WFAIL, ec.message().c_str()));
            }
        }

        void doWriteToSocket(const char* dataPtr, size_t bytesToWrite,
                boost::system::error_code& errorCode) {
            if(0 == bytesToWrite) {
                return;
            }

            // Write all the bytes to socket. In case of error when all bytes are not successfully written
            // proper errorCode will be set.
            while(1) {
                size_t bytesWritten = m_pChannel->getSocketStream().writeSome(boost::asio::buffer(dataPtr, bytesToWrite), errorCode);
                // Update the state
                bytesToWrite -= bytesWritten;
                dataPtr += bytesWritten;

                if(EINTR != errorCode.value()) break;

                // Check if all the data is written then break from loop
                if(0 == bytesToWrite) break;
            }
        }

        connectionStatus_t validateHandshake(DrillUserProperties* properties){

            DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "validateHandShake\n";)

                exec::user::UserToBitHandshake u2b;
            u2b.set_channel(exec::shared::USER);
            u2b.set_rpc_version(DRILL_RPC_VERSION);
            u2b.set_support_listening(true);
            u2b.set_support_timeout(DrillClientConfig::getHeartbeatFrequency() > 0);
            u2b.set_sasl_support(exec::user::SASL_PRIVACY);

            // Adding version info
            exec::user::RpcEndpointInfos* infos = u2b.mutable_client_infos();
            infos->set_name(DrillClientConfig::getClientName());
            infos->set_application(DrillClientConfig::getApplicationName());
            infos->set_version(DRILL_VERSION_STRING);
            infos->set_majorversion(DRILL_VERSION_MAJOR);
            infos->set_minorversion(DRILL_VERSION_MINOR);
            infos->set_patchversion(DRILL_VERSION_PATCH);

            if(properties != NULL && properties->size()>0){
                std::string username;
                std::string err;
                if(!properties->validate(err)){
                    DRILL_MT_LOG(DRILL_LOG(LOG_INFO) << "Invalid user input:" << err << std::endl;)
                }
                exec::user::UserProperties* userProperties = u2b.mutable_properties();

                std::map<char,int>::iterator it;
                for (std::map<std::string,std::string>::const_iterator propIter=properties->begin(); propIter!=properties->end(); ++propIter){
                    std::string currKey=propIter->first;
                    std::string currVal=propIter->second;
                    std::map<std::string,uint32_t>::const_iterator it=DrillUserProperties::USER_PROPERTIES.find(currKey);
                    if(it==DrillUserProperties::USER_PROPERTIES.end()){
                        DRILL_MT_LOG(DRILL_LOG(LOG_INFO) << "Connection property ("<< currKey
                                << ") is unknown" << std::endl;)
                            exec::user::Property* connProp = userProperties->add_properties();
                        connProp->set_key(currKey);
                        connProp->set_value(currVal);
                        continue;
                    }
                    if(IS_BITSET((*it).second,USERPROP_FLAGS_SERVERPROP)){
                        exec::user::Property* connProp = userProperties->add_properties();
                        connProp->set_key(currKey);
                        connProp->set_value(currVal);
                        //Username(but not the password) also needs to be set in UserCredentials
                        if(IS_BITSET((*it).second,USERPROP_FLAGS_USERNAME)){
                            exec::shared::UserCredentials* creds = u2b.mutable_credentials();
                            username=currVal;
                            creds->set_user_name(username);
                            //u2b.set_credentials(&creds);
                        }
                        if(IS_BITSET((*it).second,USERPROP_FLAGS_PASSWORD)){
                            DRILL_MT_LOG(DRILL_LOG(LOG_INFO) <<  currKey << ": ********** " << std::endl;)
                        }else{
                            DRILL_MT_LOG(DRILL_LOG(LOG_INFO) << currKey << ":" << currVal << std::endl;)
                        }
                    }// Server properties
                }
            }

            {
                boost::lock_guard<boost::mutex> lock(this->m_dcMutex);
                uint64_t coordId = ++m_coordinationId;

                rpc::OutBoundRpcMessage out_msg(exec::rpc::REQUEST, exec::user::HANDSHAKE, coordId, &u2b);
                sendSyncCommon(out_msg);
                DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Sent handshake request message. Coordination id: " << coordId << "\n";)
            }

            connectionStatus_t ret = recvHandshake();
            if(ret!=CONN_SUCCESS){
                return ret;
            }

            switch(this->m_handshakeStatus) {
                case exec::user::SUCCESS:
                    // reset io_service after handshake is validated before running queries
                    m_pChannel->getIOService().reset();
                    return CONN_SUCCESS;
                case exec::user::RPC_VERSION_MISMATCH:
                    DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Invalid rpc version.  Expected "
                            << DRILL_RPC_VERSION << ", actual "<< 0 << "." << std::endl;)
                        return handleConnError(CONN_BAD_RPC_VER, getMessage(ERR_CONN_BAD_RPC_VER, DRILL_RPC_VERSION,
                                    0,
                                    this->m_handshakeErrorId.c_str(),
                                    this->m_handshakeErrorMsg.c_str()));
                case exec::user::AUTH_FAILED:
                    DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Authentication failed." << std::endl;)
                        return handleConnError(CONN_AUTH_FAILED, getMessage(ERR_CONN_AUTHFAIL,
                                    this->m_handshakeErrorId.c_str(),
                                    this->m_handshakeErrorMsg.c_str()));
                case exec::user::UNKNOWN_FAILURE:
                    DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Unknown error during handshake." << std::endl;)
                        return handleConnError(CONN_HANDSHAKE_FAILED, getMessage(ERR_CONN_UNKNOWN_ERR,
                                    this->m_handshakeErrorId.c_str(),
                                    this->m_handshakeErrorMsg.c_str()));
                case exec::user::AUTH_REQUIRED:
                    DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Server requires SASL authentication." << std::endl;)
                    return handleConnError(CONN_HANDSHAKE_FAILED, getMessage(ERR_CONN_UNKNOWN_ERR,
                                                                             this->m_handshakeErrorId.c_str(),
                                                                             this->m_handshakeErrorMsg.c_str()));
                default:
                    DRILL_MT_LOG(DRILL_LOG(LOG_TRACE) << "Unknown return status." << std::endl;)
                        return handleConnError(CONN_HANDSHAKE_FAILED, getMessage(ERR_CONN_UNKNOWN_ERR,
                                    this->m_handshakeErrorId.c_str(),
                                    this->m_handshakeErrorMsg.c_str()));
            }
        }

        DrillClientError* m_pError;
    private:
        Channel* m_pChannel;
        int32_t m_coordinationId;
        std::string m_handshakeErrorId;
        std::string m_handshakeErrorMsg;
        exec::user::HandshakeStatus m_handshakeStatus;
        DataBuf m_wbuf;
        ByteBuf_t m_rbuf;
        boost::mutex m_dcMutex;

};

} // namespace Drill

using namespace Drill;

int main(int argc, char* argv[]){
    Channel *pChannel = NULL;
    ChannelContext *pChannelContext = NULL;
    std::string connectStr = "zk=localhost:2181/drill/drillbits1";
    //std::string connectStr = "drillbit=localhost:31090";
    channelType_t type;
    boost::asio::io_service ioService;

    bool isSSL = argc==2 && !(strcmp(argv[1], "ssl"));
    type = CHANNEL_TYPE_SOCKET;
    if(isSSL){
        type = CHANNEL_TYPE_SSLSTREAM;
    }
    Drill::DrillUserProperties props;
    props.setProperty(USERPROP_USERNAME, "admin");
    props.setProperty(USERPROP_PASSWORD, "admin");
    props.setProperty(USERPROP_CERTFILEPATH, "../../../test/ssl/drillTestCert.pem");

    pChannel = ChannelFactory::getChannel(type, ioService, connectStr.c_str(), &props);
    if(pChannel != NULL){
        connectionStatus_t connStat;
        connStat = pChannel->init();
        if(connStat != CONN_SUCCESS){
            std::cout << "Init Failed." << std::endl;
            return -1;
        }
        connStat = pChannel->connect();
        if(connStat != CONN_SUCCESS){
            std::cout << "Connect Failed." << std::endl;
            std::cout << pChannel->getError()->msg << std::endl;
            return -1;
        }
    } else{
        std::cout << "Channel creation failed." << std::endl;
        return -1;
    }
    std::cout << "Connected." << std::endl;
    std::cout << "Starting Drill handshake" << std::endl;

    DrillTestClient client(pChannel);

    connectionStatus_t stat = client.validateHandshake(&props);
    if(stat == CONN_SUCCESS){
        std::cout << "Handshake validated." << std::endl;
    } else{
        if(client.m_pError != NULL){
            std::cout << "Handshake failed: " << client.m_pError->msg << ". " << std::endl;
        } else{
            std::cout << "Handshake failed  with unknown error" << ". " << std::endl;
        }
    }

    return 0;

}


text:
package main

import (
	"compress/gzip"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

var logger = log.New(os.Stderr, "", 0)

func main() {
	if err := run(); err != nil {
		logger.Printf(err.Error())
		flag.Usage()
		os.Exit(1)
	}
}

var (
	address   = flag.String("a", "http://127.0.0.1:9200", "Address")
	index     = flag.String("i", "", "Index Name")
	out       = flag.String("o", "", "Output file")
	batchSize = flag.Int("b", 1000, "Batch Size")
	scroll    = flag.String("s", "1m", "Scroll duration")
)

func run() error {
	flag.Parse()
	if *address == "" {
		return errors.New("Address must be set")
	}
	if *index == "" {
		return errors.New("Index Name must be set")
	}

	if *out == "" {
		return errors.New("Output file must be set")
	}

	f, err := os.Create(*out)
	if err != nil {
		return err
	}
	defer f.Close()
	gz := gzip.NewWriter(f)
	defer gz.Close()

	docs, err := iterateIndex(*address, *index, *batchSize, *scroll)
	if err != nil {
		return err
	}

	c, wg := progress()
	for d := range docs {
		if _, err = io.WriteString(gz, string(d)+"\n"); err != nil {
			return err
		}
		c <- struct{}{}
	}
	close(c)
	wg.Wait()
	return nil
}

func progress() (chan struct{}, *sync.WaitGroup) {
	wg := &sync.WaitGroup{}
	wg.Add(1)
	c := make(chan struct{})
	go func() {
		defer wg.Done()
		t := time.Tick(1 * time.Second)
		started := time.Now()
		cnt := 0

		printStatus := func() {
			diff := time.Since(started).Seconds()
			perSecond := float64(cnt) / diff
			logger.Printf("cnt=%d time=%.01f per_second=%.1f/second", cnt, diff, perSecond)
		}
		for {
			select {
			case _, ok := <-c:
				if !ok {
					printStatus()
					return
				}
				cnt++
			case <-t:
				printStatus()
			}

		}
	}()
	return c, wg
}

func iterateIndex(addr, name string, size int, scroll string) (chan json.RawMessage, error) {
	scrollID, err := openIndex(addr, name, size, scroll)
	if err != nil {
		return nil, err
	}
	c := make(chan json.RawMessage)
	var docs []json.RawMessage
	go func() {
		defer close(c)
		for {
			scrollID, docs, err = loadDocumentsWithScroll(addr, scrollID)
			if err != nil {
				logger.Printf("err=%q", err)
				return
			} else if len(docs) == 0 {
				return
			}
			for _, d := range docs {
				c <- d
			}
		}
	}()
	return c, nil
}

type scrollResponse struct {
	ScrollID string `json:"_scroll_id"`
	Hits     struct {
		Hits []json.RawMessage `json:"hits"`
	} `json:"hits"`
}

func loadDocumentsWithScroll(addr string, id string) (string, []json.RawMessage, error) {
	req, err := http.NewRequest("GET", addr+"/_search/scroll?scroll=1m", strings.NewReader(id))
	if err != nil {
		return "", nil, err
	}
	rsp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", nil, err
	}
	defer rsp.Body.Close()
	switch rsp.StatusCode {
	case 200:
		var rr *scrollResponse
		err = json.NewDecoder(rsp.Body).Decode(&rr)
		if err != nil {
			return "", nil, err
		}
		return rr.ScrollID, rr.Hits.Hits, nil
	default:
		b, _ := ioutil.ReadAll(rsp.Body)
		return "", nil, fmt.Errorf("got status %s but expected 2x. body=%s", rsp.Status, string(b))
	}
}

func openIndex(addr, name string, size int, scroll string) (scrollID string, err error) {
	rsp, err := http.Post(addr+"/"+name+"/_search?search_type=scan&scroll="+scroll,
		"application/json",
		strings.NewReader(`{"query": {"match_all": {} }, "size": `+strconv.Itoa(size)+`}`),
	)
	if err != nil {
		return "", err
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		b, _ := ioutil.ReadAll(rsp.Body)
		return "", fmt.Errorf("expected status 2xx, got %s: %s", rsp.Status, string(b))
	}
	var s *scrollResponse
	err = json.NewDecoder(rsp.Body).Decode(&s)
	if err != nil {
		return "", err
	}
	return s.ScrollID, nil
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.lightcopy.history.event;

import java.util.Map;

import com.google.gson.annotations.SerializedName;

public class SparkListenerExecutorAdded {
  public class ExecutorInfo {
    @SerializedName("Host") public String host;
    @SerializedName("Total Cores") public int totalCores;
    // contains keys "stdout" and "stderr"
    @SerializedName("Log Urls") public Map<String, String> logUrls;
  }

  @SerializedName("Timestamp") public long timestamp;
  @SerializedName("Executor ID") public String executorId;
  @SerializedName("Executor Info") public ExecutorInfo info;
}


text:
package com.eigengo.lift.common

import spray.routing._
import spray.routing.directives.PathDirectives

trait CommonPathDirectives extends PathDirectives {
  val UserIdValue: PathMatcher1[UserId] = JavaUUID.map(UserId.apply)

}


text:
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');

var WordpressappGenerator = module.exports = function WordpressappGenerator(args, options, config) {
	var instance = this;

	// By calling `NamedBase` here, we get the argument to the subgenerator call
	// as `this.name`.
	yeoman.generators.NamedBase.apply(this, arguments);

	// Load options from parent generator
	this.nested = instance.options.nested;
	this.appName = instance.options.appName;
	this.appNS = instance.options.appNS;
	this.jsPath = instance.options.jsPath;
	this.appType = instance.options.appType;
	this.createController = instance.options.createController;
	this.controllerName = instance.options.controllerName;
	this.createExampleClasses = instance.options.createExampleClasses;
};

util.inherits(WordpressappGenerator, yeoman.generators.NamedBase);

WordpressappGenerator.prototype.files = function files() {
	this.mkdir(this.jsPath);

	this.mkdir(this.jsPath + '/' + 'lib');
	this.template('js/lib/hbs.js', this.jsPath + '/' + 'lib/hbs.js');

	this.mkdir(this.jsPath + '/' + this.appNS);
	this.template('js/APP/main.js', this.jsPath + '/' + this.appNS + '/main.js');

	if (this.createController) {
		this.mkdir(this.jsPath + '/' + this.appNS + '/controllers');
		this.template('js/APP/controllers/controller.js', this.jsPath + '/' + this.appNS + '/controllers/' + this.controllerName + '.js');
	}
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 78(3-4): 313 (2004)

#### Original name
Pannaria andina ined.

### Remarks
null


text:
class CreateMailSweeperEmailBlacklists < ActiveRecord::Migration
  def change
    create_table :mail_sweeper_email_blacklists do |t|
      t.string :email, null: false
      t.integer :block_counter, null: false, default: 0
      t.datetime :blocked_until
      t.boolean :permanently_blocked, default: false

      t.timestamps null: false
    end

    add_index :mail_sweeper_email_blacklists, :email, unique: true
  end
end


text:
/** perform math on web mercator grids, http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Mathematics */

/** convert longitude to pixel value */
export function lonToPixel (lon, zoom) {
  // factor of 256 is to get a pixel value not a tile number
  // return int, 32 bit int sufficient for pixels up to zoom 22
  return ((lon + 180) / 360 * Math.pow(2, zoom) * 256) | 0
}

/** convert latitude to pixel value */
export function latToPixel (lat, zoom) {
  let invCos = 1 / Math.cos(radians(lat))
  let tan = Math.tan(radians(lat))
  let ln = Math.log(tan + invCos)
  // return int
  return ((1 - ln / Math.PI) * Math.pow(2, zoom - 1) * 256) | 0
}

/** convert pixel value to longitude */
export function pixelToLon (x, zoom) {
  return x / (Math.pow(2, zoom) * 256) * 360 - 180
}

/** convert pixel value to latitude */
export function pixelToLat (y, zoom) {
  let tile = y / 256
  return degrees(Math.atan(Math.sinh(Math.PI - tile * Math.PI * 2 / Math.pow(2, zoom))))
}

/** convert radians to degrees */
export function degrees (rad) {
  return rad * 180 / Math.PI
}

/** convert degrees to radians */
export function radians (deg) {
  return deg * Math.PI / 180
}


text:
package leap.core.event;

import leap.core.validation.annotations.NotNull;

public class EventListenerRegistration {

	protected String[] 				 categories;
	protected String[] 				 eventNames;
	protected @NotNull EventListener listener;

	public String[] getCategories() {
		return categories;
	}

	public void setCategories(String[] categories) {
		this.categories = categories;
	}

	public String[] getEventNames() {
		return eventNames;
	}

	public void setEventNames(String[] eventNames) {
		this.eventNames = eventNames;
	}

	public EventListener getListener() {
		return listener;
	}

	public void setListener(EventListener listener) {
		this.listener = listener;
	}
}


text:
SGNotificationHelper
===================

**This helper can let you convert 'Remote Push Notification' to 'UILocalNotification', and let you manage the notifications which are already shown on Notification Center.**

***If you want to convert Remote notification and present it as Local Notification, Remote Notifiation must be 'Silent Notification' (otherwise remote notification will be shown on notification center)***

####* Note that all files are ARC only

# Sample Project Screens
**1. Add Notifications**

![alt tag](./README_IMAGES/1_AddNotifications.png)

**2. Check Notifications on Notification Center**

![alt tag](./README_IMAGES/2_CheckAddedNotifications.png)

**3. Select a raw on TableView and confirm to remove notification**

![alt tag](./README_IMAGES/3_ConfirmToDeleteOneNotification.png)

**4. Updated on TableView**

![alt tag](./README_IMAGES/4_RefreshNotificationList.png)

**5. Updated on Notification Center**

![alt tag](./README_IMAGES/5_CheckResultOnNotificationCenter.png)

# INSTALL

## via git submodule

* Add it by git

```
 git submodule add https://github.com/SanggeonPark/SGNotificationHelper submodules/SGNotificationHelper
```
* Add the files you need to your xcode project.

## via Cocoapods

* Add the following line to your podfile (includes default files to your project aka UIKit and Foundation):

```
pod 'SGNotificationHelper'
```

# Publishing

1. Update `SGNotificationHelper.podspec`
2. Run `pod lib lint` to check for errors and
3. Tag the version
4. `pod trunk push`

More infos :
* http://guides.cocoapods.org/making/using-pod-lib-create.html
* http://guides.cocoapods.org/making/getting-setup-with-trunk


text:
<?xml version="1.0"?>
<marionette_info>
  <expected_messages>
    <message type="whole_message">ERROR: Unknown variable: y</message>
  </expected_messages>
</marionette_info>


text:
package org.apache.log.format;

import org.apache.log.LogEvent;
import org.apache.log.Priority;

/**
 * A formatter that serializes in the format originally
 * used by BSD syslog daemon.
 *
 * @author Peter Donald
 */
public class SyslogFormatter
    implements Formatter
{
    public static final int PRIORITY_DEBUG = 7;
    public static final int PRIORITY_INFO = 6;
    public static final int PRIORITY_NOTICE = 5;
    public static final int PRIORITY_WARNING = 4;
    public static final int PRIORITY_ERR = 3;
    public static final int PRIORITY_CRIT = 2;
    public static final int PRIORITY_ALERT = 1;
    public static final int PRIORITY_EMERG = 0;

    /*
     * Constants for facility.
     */
    public static final int FACILITY_KERN = ( 0 << 3 );
    public static final int FACILITY_USER = ( 1 << 3 );
    public static final int FACILITY_MAIL = ( 2 << 3 );
    public static final int FACILITY_DAEMON = ( 3 << 3 );
    public static final int FACILITY_AUTH = ( 4 << 3 );
    public static final int FACILITY_SYSLOG = ( 5 << 3 );
    public static final int FACILITY_LPR = ( 6 << 3 );
    public static final int FACILITY_NEWS = ( 7 << 3 );
    public static final int FACILITY_UUCP = ( 8 << 3 );
    public static final int FACILITY_CRON = ( 9 << 3 );
    public static final int FACILITY_AUTHPRIV = ( 10 << 3 );
    public static final int FACILITY_FTP = ( 11 << 3 );

    public static final int FACILITY_LOCAL0 = ( 16 << 3 );
    public static final int FACILITY_LOCAL1 = ( 17 << 3 );
    public static final int FACILITY_LOCAL2 = ( 18 << 3 );
    public static final int FACILITY_LOCAL3 = ( 19 << 3 );
    public static final int FACILITY_LOCAL4 = ( 20 << 3 );
    public static final int FACILITY_LOCAL5 = ( 21 << 3 );
    public static final int FACILITY_LOCAL6 = ( 22 << 3 );
    public static final int FACILITY_LOCAL7 = ( 23 << 3 );

    ///String descriptions of all the facilities
    protected static final String[] FACILITY_DESCRIPTIONS =
        {
            "kern", "user", "mail", "daemon", "auth", "syslog",
            "lpr", "news", "uucp", "cron", "authpriv", "ftp",
            "", "", "", "", "local0", "local1", "local2", "local3",
            "local4", "local5", "local6", "local7"
        };

    ///Constant for holding facility id
    private int m_facility;

    ///flag to decide whether we write out Facility banner
    private boolean m_showFacilityBanner;

    /**
     * Constructor that assumes FACILITY_USER.
     */
    public SyslogFormatter()
    {
        this( FACILITY_USER );
    }

    /**
     * Constructor so that you can associate facility with formatter.
     *
     * @param facility the facility constant
     */
    public SyslogFormatter( final int facility )
    {
        this( facility, true );
    }

    /**
     * Constructor allowing setting of facility and whether to show banner.
     *
     * @param facility the facility code.
     * @param showFacilityBanner true if facility banner should be shown
     */
    public SyslogFormatter( final int facility, final boolean showFacilityBanner )
    {
        m_facility = facility;
        m_showFacilityBanner = showFacilityBanner;
    }

    /**
     * Format log event into syslog string.
     *
     * @param event the event
     * @return the formatted string
     */
    public String format( final LogEvent event )
    {
        final int priority = getSyslogPriority( event );
        final int facility = getSyslogFacility( event );
        String message = event.getMessage();

        //TODO: Clean and spruce message here (ie remove \t and \n's)

        if( null == message )
        {
            message = "";
        }

        if( m_showFacilityBanner )
        {
            message = getFacilityDescription( facility ) + ": " + message;
        }

        return "<" + ( facility | priority ) + "> " + message;
    }

    /**
     * Retrieve description for facility.
     *
     * @param facility the facility code
     * @return the facility description
     */
    protected String getFacilityDescription( final int facility )
    {
        return FACILITY_DESCRIPTIONS[ facility >> 3 ];
    }

    /**
     * Get facility associated with event.
     * Default implementation returns facility set in constructor.
     *
     * @param event the log event
     * @return the facility code
     */
    protected int getSyslogFacility( final LogEvent event )
    {
        return m_facility;
    }

    /**
     * Get syslog priority code for LogEvent.
     * This is done by translating LogKit priority to syslog priority.
     *
     * @param event the log event
     * @return the priority code
     */
    protected int getSyslogPriority( final LogEvent event )
    {
        if( event.getPriority().isLowerOrEqual( Priority.DEBUG ) )
        {
            return PRIORITY_DEBUG;
        }
        else if( event.getPriority().isLowerOrEqual( Priority.INFO ) )
        {
            return PRIORITY_INFO;
        }
        else if( event.getPriority().isLowerOrEqual( Priority.WARN ) )
        {
            return PRIORITY_WARNING;
        }
        else if( event.getPriority().isLowerOrEqual( Priority.ERROR ) )
        {
            return PRIORITY_ERR;
        }
        else
        {
            return PRIORITY_CRIT;
        }
    }
}


text:
actions :install, :remove, :upgrade

attribute :package, :kind_of => String, :name_attribute => true
attribute :source, :kind_of => String
attribute :version, :kind_of => String
attribute :args, :kind_of => String

def initialize(*args)
	super
	@action = :install
end


text:
void ReplacePadFuncsWithPCControls();
void HandlePCCheats();
char GetAsyncKeyState(int vKey);

void CPad__UpdateHook(struct CPad* pad, int16_t a2);

int16_t EmulateRightStickXWithMouse(struct CPad* pad);
int16_t EmulateRightStickYWithMouse(struct CPad* pad);

int16_t sub_287470(struct CPad* pad);
int16_t sub_287450(struct CPad* pad);
int16_t sub_287430(struct CPad* pad);
int16_t sub_287410(struct CPad* pad);

int16_t sub_287580(struct CPad* pad);
int16_t sub_287530(struct CPad* pad);
int16_t sub_2874E0(struct CPad* pad);
int16_t sub_287490(struct CPad* pad);
int16_t sub_286D28(struct CPad* pad);
int16_t sub_286D78(struct CPad* pad);

float CPad__KBLookAroundLeftRightF(struct CPad* pad);
float CPad__KBLookAroundUpDownF(struct CPad* pad);
float CPad__KBLookAroundLeftRightNoTimeStamp(struct CPad* pad);
float CPad__KBLookAroundUpDownNoTimeStamp(struct CPad* pad);
int16_t CPad__KBGetSteeringLeftRight(struct CPad* pad);
int16_t CPad__KBGetSteeringUpDown(struct CPad* pad);
int16_t CPad__KBGetCarGunUpDown(struct CPad* pad);
int16_t CPad__KBGetCarGunLeftRight(struct CPad* pad);
int16_t CPad__KBGetPedWalkLeftRight(struct CPad* pad);
int16_t CPad__KBGetPedWalkUpDown(struct CPad* pad);
int16_t CPad__KBGetLookLeft(struct CPad* pad);
int16_t CPad__KBGetLookLeftFly(struct CPad* pad);
int16_t CPad__KBGetLookRight(struct CPad* pad);
int16_t CPad__KBGetLookRightFly(struct CPad* pad);
int16_t CPad__KBGetLookBehindForCar(struct CPad* pad);
int16_t CPad__KBGetLookBehindForPed(struct CPad* pad);
int16_t CPad__KBGetHorn(struct CPad* pad);
int16_t CPad__KBHornJustDown(struct CPad* pad);
int16_t CPad__KBGetCarGunFired(struct CPad* pad);
int16_t CPad__KBCarGunJustDown(struct CPad* pad);
int16_t CPad__KBCarGunJustUp(struct CPad* pad);
int16_t CPad__KBGetHandBrake(struct CPad* pad);
int16_t CPad__KBGetBrake(struct CPad* pad);
int16_t CPad__KBJumpJustDown(struct CPad* pad);
int16_t CPad__KBGetExitVehicle(struct CPad* pad);
int16_t CPad__KBExitVehicleJustDown(struct CPad* pad);
int16_t CPad__KBGetWeapon(struct CPad* pad);
int16_t CPad__KBWeaponJustDown(struct CPad* pad);
int16_t CPad__KBGetAccelerate(struct CPad* pad);
int16_t CPad__KBCycleCameraModeUpJustDown(struct CPad* pad);
int16_t CPad__KBChangeStationUpJustDown(struct CPad* pad);
int16_t CPad__KBChangeStationDownJustDown(struct CPad* pad);
int16_t CPad__KBCycleWeaponLeftJustDown(struct CPad* pad);
int16_t CPad__KBCycleWeaponRightJustDown(struct CPad* pad);
int16_t CPad__KBGetTarget(struct CPad* pad);
int16_t CPad__KBTargetJustDown(struct CPad* pad);
int16_t CPad__KBDuckJustDown(struct CPad* pad);
int16_t CPad__KBGetSprint(struct CPad* pad);
int16_t CPad__KBForceCameraBehindPlayer(struct CPad* pad);
int16_t CPad__KBSniperZoomIn(struct CPad* pad);
int16_t CPad__KBSniperZoomOut(struct CPad* pad);
int16_t CPad__KBShiftTargetLeftJustDown(struct CPad* pad);
int16_t CPad__KBShiftTargetRightJustDown(struct CPad* pad);
int16_t CPad__KBSniperModeLookLeftRight(struct CPad* pad);
int16_t CPad__KBSniperModeLookUpDown(struct CPad* pad);
int16_t CPad__KBLookAroundLeftRight(struct CPad* pad);
int16_t CPad__KBLookAroundUpDown(struct CPad* pad);
int16_t CPad__KBGuiLeft(struct CPad* pad);
int16_t CPad__KBGuiRight(struct CPad* pad);
int16_t CPad__KBGuiUp(struct CPad* pad);
int16_t CPad__KBGuiDown(struct CPad* pad);
int16_t CPad__KBGuiSelect(struct CPad* pad);
int16_t CPad__KBGuiBack(struct CPad* pad);
int16_t CPad__KBGetSkipCutscene(struct CPad* pad);
int16_t CPad__KBGetOddJobTrigger(struct CPad* pad);
int16_t CPad__KBEnterFreeAim(struct CPad* pad);
int16_t CPad__KBGetLeftStickX(struct CPad* pad);
int16_t CPad__KBGetLeftStickY(struct CPad* pad);
int16_t CPad__KBGetRightStickX(struct CPad* pad);
int16_t CPad__KBGetRightStickY(struct CPad* pad);

enum CheatTable
{
    Weapon1,
    Weapon2,
    Weapon3,
    Money,
    Armour,
    Health,
    WantedUp,
    NeverWanted,
    SunnyWeather,
    ExtraSunny,
    CloudyWeather,
    RainyWeather,
    FoggyWeather,
    Tank,
    FastWeather,
    BlowUpCars,
    Mayhem,
    PedsAttackVic,
    WeaponsForAll,
    FastTime,
    SlowTime,
    StrongGrip,
    Suicide,
    TrafficLights,
    MadCars,
    BlackCars,
    Trashmaster,
    PickUpChicks,
    FannyMagnet,
    GlassCars,
    TopsyTurvy,

    CheatsNum
};

#endif


text:
package com.swfarm.biz.ebay.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.SaleChannel;
import com.swfarm.biz.chain.srv.ChainQueryService;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.ebay.job.SynchronizeEbayOrderStatusTask;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.biz.ebay.srv.SynchronizationService;
import com.swfarm.biz.oa.srv.UserService;
import com.swfarm.biz.salechannel.dto.SearchEbayCustomerOrdersCriteria;
import com.swfarm.biz.salechannel.srv.SaleChannelQueryService;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.dto.SearchAllocationProductVouchersCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.SpringUtils;

@Controller
public class SynchronizeEbayOrderStatusController {

	private Logger logger = Logger.getLogger(SynchronizeEbayOrderStatusController.class);

	@Autowired
	private SynchronizationService synchronizationService;

	@Autowired
	private WarehouseService warehouseService;

	@Autowired
	private ChainService chainService;

	@Autowired
	private ChainQueryService chainQueryService;

	@Autowired
	private EbayService ebayService;

	@Autowired
	private UserService userService;

	@Autowired
	private SaleChannelQueryService saleChannelQueryService;

	@RequestMapping("/ebay/synchronize_ebayorderstatus.shtml")
	protected ModelAndView synchronizeEbayOrderStatus(HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		SearchEbayCustomerOrdersCriteria criteria = (SearchEbayCustomerOrdersCriteria) req.getAttribute("criteria");
		String[] orderIds = req.getParameterValues("customerOrderIds");
		String[] accountNumbers = req.getParameterValues("accountNumber");
		String customerOrderId = req.getParameter("customerOrderId");
		String apvlIdStr = req.getParameter("apvl");
		String forceUpdate = req.getParameter("forceUpdate");
		List<CustomerOrder> customerOrders = new ArrayList<CustomerOrder>();
		if (criteria != null) {
			customerOrders = saleChannelQueryService.searchEbayCustomerOrders(criteria);
		} else if (orderIds != null) {
			for (int i = 0; i < orderIds.length; i++) {
				String orderId = orderIds[i];
				CustomerOrder customerOrder = chainService.findCustomerOrder(orderId);
				if (customerOrder != null) {
					customerOrders.add(customerOrder);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(customerOrders)) {
			List customerOrderIds = new ArrayList();
			List saleChannelOrderIds = new ArrayList();
			logger.warn("total customerOrders size [" + customerOrders.size() + "]");
			for (Iterator<CustomerOrder> iterator = customerOrders.iterator(); iterator.hasNext();) {
				CustomerOrder customerOrder = iterator.next();
				logger.warn("prepare customerorder [" + customerOrder.getCustomerOrderNo() + "]");
				SearchAllocationProductVouchersCriteria searchApvsCriteria = new SearchAllocationProductVouchersCriteria();
				searchApvsCriteria.setCustomerOrderId(customerOrder.getId());
				List allocationProductVouchers = this.warehouseService
						.searchAllocationProductVouchers(searchApvsCriteria);
				if (CollectionUtils.isNotEmpty(allocationProductVouchers)) {
					customerOrderIds.add(customerOrder.getId());
					saleChannelOrderIds.add(customerOrder.getSaleChannelOrderId());
				}
			}
			if (CollectionUtils.isNotEmpty(customerOrderIds)) {
				pushEbayOrderStatus(null, customerOrderIds, null);
			}
			Map dataMap = new HashMap();
			if (criteria == null) {
				criteria = new SearchEbayCustomerOrdersCriteria();
				criteria.setSaleChannelOrderIds(saleChannelOrderIds);
			}
			dataMap = criteria.toMap();
			return new ModelAndView("redirect:/salechannel/search_ebaycustomerorders.shtml", dataMap);
		} else if (StringUtils.isNotEmpty(customerOrderId)) {
			CustomerOrder customerOrder = this.chainService.findCustomerOrder(customerOrderId);
			if (SaleChannel.CHANNEL_EBAY.equals(customerOrder.getSaleChannel())) {
				if ("true".equals(forceUpdate)) {
					// TODO
				}
				SearchAllocationProductVouchersCriteria searchApvsCriteria = new SearchAllocationProductVouchersCriteria();
				searchApvsCriteria.setCustomerOrderId(customerOrderId);
				List allocationProductVouchers = this.warehouseService
						.searchAllocationProductVouchers(searchApvsCriteria);
				if (CollectionUtils.isNotEmpty(allocationProductVouchers)) {
					List<String> customerOrderIds = new ArrayList<String>();
					customerOrderIds.add(customerOrder.getId());
					if (CollectionUtils.isNotEmpty(customerOrderIds)) {
						pushEbayOrderStatus(null, customerOrderIds, null);
					}
				}
			}
			return new ModelAndView("redirect:/chain/customerorder.ahtml", "id", customerOrderId);
		} else if (StringUtils.isNotEmpty(apvlIdStr)) {
			Long apvlId = new Long(apvlIdStr);
			AllocationProductVoucherList apvl = this.warehouseService.findAllocationProductVoucherList(apvlId);
			List<String> customerOrderIds = new ArrayList<String>();
			Set<AllocationProductVoucher> apvs = apvl.getAllocationProductVouchers();
			for (Iterator iter = apvs.iterator(); iter.hasNext();) {
				AllocationProductVoucher apv = (AllocationProductVoucher) iter.next();
				CustomerOrder customerOrder = apv.getCustomerOrder();
				customerOrderIds.add(customerOrder.getId());
			}
			if (CollectionUtils.isNotEmpty(customerOrderIds)) {
				if ("altnux".equalsIgnoreCase(Env.COMPANY_CODE)) {
					// 114需求:apvl页面同步平台状态忽略是否已经标记同步
					pushEbayOrderStatus(null, customerOrderIds, true);
				} else {
					pushEbayOrderStatus(null, customerOrderIds, null);
				}
			}
			return new ModelAndView("redirect:/warehouse/allocationproductvoucherlist.shtml", "id", apvlId);
		}
		return new ModelAndView("redirect:/salechannel/search_ebaycustomerorders.shtml");
	}

	private void pushEbayOrderStatus(String[] accountNumbers, List saleChannelOrderIds, Boolean isIgnore) {
		SynchronizeEbayOrderStatusTask task = new SynchronizeEbayOrderStatusTask();
		EbayService ebayService = (EbayService) SpringUtils.getBean("ebayService");
		ChainService chainService = (ChainService) SpringUtils.getBean("chainService");
		UserService userService = (UserService) SpringUtils.getBean("userService");
		WarehouseService warehouseService = (WarehouseService) SpringUtils.getBean("warehouseService");
		SynchronizationService synchronizationService = (SynchronizationService) SpringUtils
				.getBean("synchronizationService");
		task.setEbayService(ebayService);
		task.setChainService(chainService);
		task.setUserService(userService);
		task.setWarehouseService(warehouseService);
		task.setSynchronizationService(synchronizationService);
		if (CollectionUtils.isNotEmpty(saleChannelOrderIds)) {
			if (isIgnore != null && isIgnore == true) {
				task.pushEbayOrderStatusIgnoreStatus(saleChannelOrderIds);
			} else {
				task.pushEbayOrderStatus(saleChannelOrderIds);
			}
		}
	}
}


text:
package org.joeyb.retry;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.assertj.core.api.Java6Assertions.assertThatThrownBy;

import org.junit.Test;

import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class RetryTests {

    @Test
    public void eventuallySuccessfulCallableRetriesExpectedNumberOfTimesBeforeSucceeding() {
        int attemptsBeforeSuccess = ThreadLocalRandom.current().nextInt(10, 100);
        long expectedResult = ThreadLocalRandom.current().nextLong();
        long waitTime = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);

        MemoizingAccept<Long> memoizingAccept = new MemoizingAccept<>(Accepts.any());
        MemoizingAttemptListener<Long> memoizingAttemptListener = new MemoizingAttemptListener<>();
        MemoizingBlock memoizingBlock = new MemoizingBlock();
        MemoizingStop<Long> memoizingStop = new MemoizingStop<>(Stops.maxAttempts(attemptsBeforeSuccess + 1));
        MemoizingWait<Long> memoizingWait = new MemoizingWait<>(attempt -> waitTime);

        Retry<Long> retry = new Retry<>(
                memoizingAccept,
                Collections.singleton(memoizingAttemptListener),
                memoizingBlock,
                memoizingStop,
                memoizingWait);

        Long actualResult = retry.call(new EventuallySuccessfulCallable<>(attemptsBeforeSuccess, expectedResult));

        assertThat(actualResult).isEqualTo(expectedResult);

        assertThat(memoizingAccept.results)
                .hasSize(1)
                .contains(expectedResult);

        assertThat(memoizingAttemptListener.attempts)
                .allMatch(Attempt::hasException)
                .hasSize(attemptsBeforeSuccess);

        assertThat(memoizingBlock.waitTimes)
                .containsOnly(waitTime)
                .hasSize(attemptsBeforeSuccess);

        assertThat(memoizingStop.attempts)
                .hasSize(attemptsBeforeSuccess);

        // The memoizingStop's attempts collection should contain attempts numbered 1 to attemptsBeforeSuccess.
        assertThat(memoizingStop.attempts.stream().map(Attempt::attemptNumber).collect(Collectors.toList()))
                .containsExactlyElementsOf(
                        LongStream.rangeClosed(1, attemptsBeforeSuccess).boxed().collect(Collectors.toList()));

        ensureAttemptDelaysSinceFirstAttemptAreIncreasing(memoizingStop.attempts);

        assertThat(memoizingWait.attempts)
                .hasSize(attemptsBeforeSuccess);

        // The memoizingWait's attempts collection should contain attempts numbered 1 to attemptsBeforeSuccess.
        assertThat(memoizingWait.attempts.stream().map(Attempt::attemptNumber).collect(Collectors.toList()))
                .containsExactlyElementsOf(
                        LongStream.rangeClosed(1, attemptsBeforeSuccess).boxed().collect(Collectors.toList()));

        ensureAttemptDelaysSinceFirstAttemptAreIncreasing(memoizingWait.attempts);
    }

    @Test
    public void callableThatSucceedsButIsNotAcceptedBeforeStopThrowsRetryException() {
        int maxAttempts = ThreadLocalRandom.current().nextInt(10, 100);

        MemoizingAccept<Long> memoizingAccept = new MemoizingAccept<>(r -> r > maxAttempts);
        MemoizingAttemptListener<Long> memoizingAttemptListener = new MemoizingAttemptListener<>();
        MemoizingBlock memoizingBlock = new MemoizingBlock();
        MemoizingStop<Long> memoizingStop = new MemoizingStop<>(Stops.maxAttempts(maxAttempts));
        MemoizingWait<Long> memoizingWait = new MemoizingWait<>(Waits.noWait());

        Retry<Long> retry = new Retry<>(
                memoizingAccept,
                Collections.singleton(memoizingAttemptListener),
                memoizingBlock,
                memoizingStop,
                memoizingWait);

        assertThatThrownBy(() -> retry.call(new IncrementingCallable()))
                .isInstanceOf(RetryException.class)
                .matches(e -> ((RetryException) e).attempt().attemptNumber() == maxAttempts)
                .matches(e -> ((RetryException) e).attempt().hasResult());

        assertThat(memoizingAttemptListener.attempts)
                .hasSize(maxAttempts);
    }

    @Test
    public void callableThatDoesNotSucceedBeforeStopThrowsRetryException() {
        int attemptsBeforeSuccess = ThreadLocalRandom.current().nextInt(10, 100);
        long expectedResult = ThreadLocalRandom.current().nextLong();
        int maxAttempts = attemptsBeforeSuccess - 1;
        long waitTime = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);

        MemoizingAccept<Long> memoizingAccept = new MemoizingAccept<>(Accepts.any());
        MemoizingAttemptListener<Long> memoizingAttemptListener = new MemoizingAttemptListener<>();
        MemoizingBlock memoizingBlock = new MemoizingBlock();
        MemoizingStop<Long> memoizingStop = new MemoizingStop<>(Stops.maxAttempts(maxAttempts));
        MemoizingWait<Long> memoizingWait = new MemoizingWait<>(attempt -> waitTime);

        Retry<Long> retry = new Retry<>(
                memoizingAccept,
                Collections.singleton(memoizingAttemptListener),
                memoizingBlock,
                memoizingStop,
                memoizingWait);

        assertThatThrownBy(() -> retry.call(new EventuallySuccessfulCallable<>(attemptsBeforeSuccess, expectedResult)))
                .isInstanceOf(RetryException.class)
                .matches(e -> ((RetryException) e).attempt().attemptNumber() == maxAttempts)
                .matches(e -> ((RetryException) e).attempt().hasException());

        assertThat(memoizingAttemptListener.attempts)
                .allMatch(Attempt::hasException)
                .hasSize(maxAttempts);
    }

    @Test
    public void blockInterruptShouldThrowRetryException() {
        int attemptsBeforeSuccess = 10;
        long expectedResult = ThreadLocalRandom.current().nextLong();

        Block block = waitTime -> {
            Thread.currentThread().interrupt();
            throw new InterruptedException();
        };

        Retry<Long> retry = new Retry<>(
                Accepts.any(),
                Collections.emptySet(),
                block,
                Stops.never(),
                Waits.noWait());

        assertThatThrownBy(() -> retry.call(new EventuallySuccessfulCallable<>(attemptsBeforeSuccess, expectedResult)))
                .isInstanceOf(RetryException.class)
                .matches(e -> ((RetryException) e).attempt().attemptNumber() == 1)
                .matches(e -> ((RetryException) e).attempt().hasException());

        Thread.interrupted();
    }

    @Test
    public void builderBuildWithoutAdditionalConfig() {
        Retry<Long> retry = Retry.<Long>newBuilder()
                .build();

        assertThat(retry.getAccept()).isInstanceOf(AnyAccept.class);
        assertThat(retry.getAttemptListeners()).hasSize(0);
        assertThat(retry.getBlock()).isInstanceOf(ThreadSleepBlock.class);
        assertThat(retry.getStop()).isInstanceOf(NeverStop.class);
        assertThat(retry.getWait()).isInstanceOf(NoWait.class);
    }

    @Test
    public void builderAcceptAttemptListenerBlockStopAndWaitMethodsSetGivenImplementations() {
        int attemptsBeforeSuccess = ThreadLocalRandom.current().nextInt(10, 100);
        long waitTime = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);

        MemoizingAccept<Long> memoizingAccept = new MemoizingAccept<>(Accepts.any());
        MemoizingAttemptListener<Long> memoizingAttemptListener = new MemoizingAttemptListener<>();
        MemoizingBlock memoizingBlock = new MemoizingBlock();
        MemoizingStop<Long> memoizingStop = new MemoizingStop<>(Stops.maxAttempts(attemptsBeforeSuccess + 1));
        MemoizingWait<Long> memoizingWait = new MemoizingWait<>(attempt -> waitTime);

        Retry<Long> retry = Retry.<Long>newBuilder()
                .accept(memoizingAccept)
                .attemptListener(memoizingAttemptListener)
                .block(memoizingBlock)
                .stop(memoizingStop)
                .wait(memoizingWait)
                .build();

        assertThat(retry.getAccept()).isEqualTo(memoizingAccept);
        assertThat(retry.getAttemptListeners()).containsExactly(memoizingAttemptListener);
        assertThat(retry.getBlock()).isEqualTo(memoizingBlock);
        assertThat(retry.getStop()).isEqualTo(memoizingStop);
        assertThat(retry.getWait()).isEqualTo(memoizingWait);
    }

    @Test
    public void builderAcceptAnyResult() {
        Retry<Long> retry = Retry.<Long>newBuilder()
                .acceptAnyResult()
                .build();

        assertThat(retry.getAccept()).isInstanceOf(AnyAccept.class);
    }

    @Test
    public void builderAcceptNonNullResult() {
        Retry<Long> retry = Retry.<Long>newBuilder()
                .acceptNonNullResult()
                .build();

        assertThat(retry.getAccept()).isInstanceOf(NonNullAccept.class);
    }

    @Test
    public void builderConstantWait() {
        long waitTime = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);

        Retry<Long> retry = Retry.<Long>newBuilder()
                .constantWait(waitTime)
                .build();

        assertThat(retry.getWait()).isInstanceOf(ConstantWait.class);

        ConstantWait<Long> constantWait = (ConstantWait<Long>) retry.getWait();

        assertThat(constantWait.waitTime()).isEqualTo(waitTime);
    }

    @Test
    public void builderMaxAttempts() {
        long maxAttempts = ThreadLocalRandom.current().nextInt(10, 10000);

        Retry<Long> retry = Retry.<Long>newBuilder()
                .maxAttempts(maxAttempts)
                .build();

        assertThat(retry.getStop()).isInstanceOf(MaxAttemptsStop.class);

        MaxAttemptsStop<Long> maxAttemptsStop = (MaxAttemptsStop<Long>) retry.getStop();

        assertThat(maxAttemptsStop.maxAttempts()).isEqualTo(maxAttempts);
    }

    @Test
    public void builderMaxDelaySinceFirstAttempt() {
        long maxDelay = ThreadLocalRandom.current().nextLong(10, 10000);

        Retry<Long> retry = Retry.<Long>newBuilder()
                .maxDelaySinceFirstAttempt(maxDelay)
                .build();

        assertThat(retry.getStop()).isInstanceOf(MaxDelaySinceFirstAttemptStop.class);

        MaxDelaySinceFirstAttemptStop<Long> maxDelayStop = (MaxDelaySinceFirstAttemptStop<Long>) retry.getStop();

        assertThat(maxDelayStop.maxDelaySinceFirstAttempt()).isEqualTo(maxDelay);
    }

    @Test
    public void builderNeverStop() {
        Retry<Long> retry = Retry.<Long>newBuilder()
                .neverStop()
                .build();

        assertThat(retry.getStop()).isInstanceOf(NeverStop.class);
    }

    private void ensureAttemptDelaysSinceFirstAttemptAreIncreasing(ConcurrentLinkedQueue<Attempt<Long>> attempts) {
        long last = 0;

        for (Attempt<?> attempt : attempts) {
            assertThat(attempt.delaySinceFirstAttempt()).isGreaterThanOrEqualTo(last);

            last = attempt.delaySinceFirstAttempt();
        }
    }

    private static class MemoizingAccept<V> implements Accept<V> {

        private final Accept<V> accept;

        private final ConcurrentLinkedQueue<V> results = new ConcurrentLinkedQueue<>();

        MemoizingAccept(Accept<V> accept) {
            this.accept = accept;
        }

        @Override
        public boolean accept(V result) {
            results.add(result);
            return accept.accept(result);
        }
    }

    private static class MemoizingAttemptListener<V> implements Consumer<Attempt<V>> {

        private final ConcurrentLinkedQueue<Attempt<V>> attempts = new ConcurrentLinkedQueue<>();

        @Override
        public void accept(Attempt<V> attempt) {
            attempts.add(attempt);
        }
    }

    private static class MemoizingBlock implements Block {

        private final ConcurrentLinkedQueue<Long> waitTimes = new ConcurrentLinkedQueue<>();

        @Override
        public void block(long waitTime) throws InterruptedException {
            waitTimes.add(waitTime);
        }
    }

    private static class MemoizingStop<V> implements Stop<V> {

        private final ConcurrentLinkedQueue<Attempt<V>> attempts = new ConcurrentLinkedQueue<>();

        private final Stop<V> stop;

        MemoizingStop(Stop<V> stop) {
            this.stop = stop;
        }

        @Override
        public boolean stop(Attempt<V> attempt) {
            attempts.add(attempt);
            return stop.stop(attempt);
        }
    }

    private static class MemoizingWait<V> implements Wait<V> {

        private final ConcurrentLinkedQueue<Attempt<V>> attempts = new ConcurrentLinkedQueue<>();

        private final Wait<V> wait;

        MemoizingWait(Wait<V> wait) {
            this.wait = wait;
        }

        @Override
        public long waitTime(Attempt<V> attempt) {
            attempts.add(attempt);
            return wait.waitTime(attempt);
        }
    }

    private static class EventuallySuccessfulCallable<V> implements Callable<V> {

        private final int attemptsBeforeSuccess;
        private final V result;

        private long attempts;

        EventuallySuccessfulCallable(int attemptsBeforeSuccess, V result) {
            this.attemptsBeforeSuccess = attemptsBeforeSuccess;
            this.result = result;
        }

        @Override
        public V call() throws Exception {
            attempts++;

            if (attempts > attemptsBeforeSuccess) {
                return result;
            }

            throw new RuntimeException();
        }
    }

    private static class IncrementingCallable implements Callable<Long> {

        private long current;

        @Override
        public Long call() throws Exception {
            current++;

            return current;
        }
    }
}


text:
'use strict';

var gulp        = require('gulp');
var Server      = require('karma').Server;
var runSequence = require('run-sequence');

var config       = require('./config');
var BuildTaskDoc = require('./BuildTaskDoc');

/**
 * Run test once and exit
 */

var testTasks = [];
config.versions.forEach(function(version) {

  var testTask = 'test-videojs_' + version;

  gulp.task(testTask, function (done) {

    var autoWatch = !!config.options['watch'];

    new Server({
      configFile: __dirname + '/../karma.conf.js',
      files: config.testFiles(version),
      autoWatch: autoWatch,
      singleRun: !autoWatch
    }, function (error) {
      done(error);
    }).start();
  });
  testTasks.push(testTask);
});

gulp.task('test', function(done) {

  testTasks.push(function (error) {
      if(error){
        console.log(error.message.red);
      } else{
        console.log('TEST FINISHED SUCCESSFULLY'.green);
      }
      done(error);
    });

  runSequence.apply(this,testTasks);

});

module.exports = new BuildTaskDoc('test', 'Starts karma and test the player', 6.1);


text:
[skel,mot]=readmocapd(38);

global VARS_GLOBAL_ANIM
VARS_GLOBAL_ANIM.video_compression = 'div4';
VARS_GLOBAL_ANIM.figure_position = [10 100 512 384];
VARS_GLOBAL_ANIM.figure_camera_file = 'test_camera';

%saveCamera(gca,'test_camera.m'); % einmalig ausführen, um gegenwärtigen view zu speichern

% falls während des renderns abgebrochen wird:
% AVI-file ist noch offen, der muss dann von hand geschlossen werden: clear mex

% skel,mot,videofile,num_repeats,time_stretch_factor,downsampling_fac,range,draw_labels,fps
animateVideo(skel,mot,'test.avi',1,1,1,[],0,30);


text:
class RobotDrop_IntentionAction extends IntentionAction {

	canHandle(intention:Term, ai:RuleBasedAI) : boolean
	{
		if (intention.functor.is_a(ai.o.getSort("action.drop"))) return true;
		return false;
	}

	execute(ir:IntentionRecord, ai_raw:RuleBasedAI) : boolean
	{
		this.ir = ir;
		let ai:RobotAI = <RobotAI>ai_raw;
		let requester:TermAttribute = ir.requester;
		let alternative_actions:Term[] = ir.alternative_actions;
		if (alternative_actions == null) alternative_actions = [ir.action];
		let denyrequestCause:Term = null;
		let numberConstraint:number = ir.resolveNumberConstraint(ir.numberConstraint, alternative_actions.length);
		let itemID_l:string[] = [];
		let locationID_l:string[] = [];

		if (ai.robot.isInVehicle()) {
			if (requester != null) {
				let term:Term = Term.fromString("action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))", ai.o);
				ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
			}
			ir.succeeded = false;
			return true;
		}

		for(let intention of alternative_actions) {
			if (intention.attributes.length == 2 &&
				(intention.attributes[0] instanceof ConstantTermAttribute) &&
				(intention.attributes[1] instanceof ConstantTermAttribute)) {
				let id:string = (<ConstantTermAttribute>(intention.attributes[1])).value;
				if (id != null && itemID_l.indexOf(id) == -1) itemID_l.push(id);
			}
			if (intention.attributes.length == 3 &&
				(intention.attributes[0] instanceof ConstantTermAttribute) &&
				(intention.attributes[1] instanceof ConstantTermAttribute) &&
				(intention.attributes[2] instanceof ConstantTermAttribute)) {
				let id:string = (<ConstantTermAttribute>(intention.attributes[1])).value;
				let id2:string = (<ConstantTermAttribute>(intention.attributes[2])).value;
				if (id != null && itemID_l.indexOf(id) == -1) itemID_l.push(id);
				if (id2 != null && locationID_l.indexOf(id2) == -1) locationID_l.push(id2);
			}
			if (intention.attributes.length == 3 &&
				(intention.attributes[0] instanceof ConstantTermAttribute) &&
				(intention.attributes[1] instanceof ConstantTermAttribute) &&
				(intention.attributes[2] instanceof VariableTermAttribute) &&
				intention.attributes[2].sort.is_a(ai.o.getSort("space.here"))) {
				let id:string = (<ConstantTermAttribute>(intention.attributes[1])).value;
				if (id != null && itemID_l.indexOf(id) == -1) itemID_l.push(id);
			}
		}

		if (itemID_l.length == 0 || locationID_l.length > 1) {
			if (requester != null) {
				let tmp:string = "action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))";
				let term:Term = Term.fromString(tmp, ai.o);
				ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
			}
			ir.succeeded = false;
			return true;
		}

		let item_l:A4Object[] = [];
		for(let o of ai.robot.inventory) {
			if (itemID_l.indexOf(o.ID) != -1) {
				if (ai.objectsNotAllowedToGive.indexOf(o.ID) == -1) {
					item_l.push(o);
				} else {
					denyrequestCause = Term.fromString("#not(verb.can('"+ai.selfID+"'[#id], action.give('"+ai.selfID+"'[#id], '"+o.ID+"'[#id], "+requester+")))", ai.o);
				}
			}
		}
		if (item_l.length == 0) {
			if (requester != null) {
				if (denyrequestCause != null) {
					let term:Term = Term.fromString("action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))", ai.o);
					ai.intentions.push(new IntentionRecord(term, null, null, new CauseRecord(denyrequestCause, null, ai.timeStamp), ai.timeStamp));
				} else {
					let term:Term = Term.fromString("action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))", ai.o);
					let cause:Term = Term.fromString("#not(verb.have('"+ai.selfID+"'[#id], '"+itemID_l[0]+"'[#id]))", ai.o);
					ai.intentions.push(new IntentionRecord(term, null, null, new CauseRecord(cause, null, ai.timeStamp), ai.timeStamp));
				}
			}
			ir.succeeded = false;
			return true;
		}

		if (locationID_l.length == 0) {
			// just drop the objects:
	        let q:A4ScriptExecutionQueue = new A4ScriptExecutionQueue(ai.robot, ai.robot.map, ai.game, null);
	        for(let item of item_l) {
	    		let s:A4Script = new A4Script(A4_SCRIPT_DROP, item.ID, null, 0, false, false);
	        	q.scripts.push(s);
	        	ai.addCurrentActionLongTermTerm(alternative_actions[0]);

				// If the object was not mentioned explicitly in the performative, add it to the natural language context:
				if (ir.requestingPerformative != null) ir.requestingPerformative.addMentionToPerformative(item.ID, ai.o);

	        	numberConstraint--;
	        	if (numberConstraint <= 0) break;
	        }
	        ai.setNewAction(alternative_actions[0], requester, q, null);
			ai.intentionsCausedByRequest.push(ir);

			app.achievement_nlp_all_robot_actions[5] = true;
			app.trigger_achievement_complete_alert();

			if (requester != null) {
				let tmp:string = "action.talk('"+ai.selfID+"'[#id], perf.ack.ok("+requester+"))";
				let term:Term = Term.fromString(tmp, ai.o);
				ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
			}
			ir.succeeded = true;
		} else {
			let targetLocation:AILocation = ai.game.getAILocationByID(locationID_l[0]);
			let destinationMap:A4Map = null;
			let destinationX:number;
			let destinationY:number;
			if (targetLocation == null) {
				// check if it's an object, and redirect to put-in!
				let containerObjectL:A4Object[] = ai.game.findObjectByID(locationID_l[0]);
				if (containerObjectL != null && containerObjectL.length > 0) {
					let term2:Term = alternative_actions[0].clone([]);
					term2.functor = ai.o.getSort("action.put-in");
					let ir2:IntentionRecord = new IntentionRecord(term2, null, null, null, ai.timeStamp);
					ir2.alternative_actions = [];
					for(let aa of ir.alternative_actions) {
						let aa2:Term = aa.clone([]);
						aa2.functor = ai.o.getSort("action.put-in");
						ir2.alternative_actions.push(aa2);
					}
					ir2.numberConstraint = ir.numberConstraint;
					ai.intentions.push(ir2);
					ir.succeeded = true;
					return true;
				}
			} else {
				let tmp2:[number,number] = targetLocation.centerWalkableCoordinatesInMap(ai.robot.map, ai.robot);
				if (tmp2 != null) {
					destinationMap = ai.robot.map;
					destinationX = tmp2[0];
					destinationY = tmp2[1];
				} else {
					if (targetLocation.maps.length > 0 &&
						targetLocation.maps.indexOf(ai.robot.map) == -1) {
						// we set this so that we can later give the proper reason for why we cannot go
						destinationMap = targetLocation.maps[0];
					}
				}
			}

			// Check if the robot can go:
			let cannotGoCause:Term = ai.canGoTo(destinationMap, locationID_l[0], requester);
			if (cannotGoCause != null) {
				if (requester != null) {
					// deny request:
					let term:Term = Term.fromString("action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))", ai.o);
					let causeRecord:CauseRecord = new CauseRecord(cannotGoCause, null, ai.timeStamp)
					ai.intentions.push(new IntentionRecord(term, null, null, causeRecord, ai.timeStamp));

					// explain cause:
					term = new Term(ai.o.getSort("action.talk"),
									[new ConstantTermAttribute(ai.selfID, ai.o.getSort("#id")),
									 new TermTermAttribute(new Term(ai.o.getSort("perf.inform"),
									 		  			   [requester, new TermTermAttribute(cannotGoCause)]))]);
					ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
				}
				ir.succeeded = false;
				return true;
			}

			if (destinationMap == null) {
				if (requester != null) {
					let tmp:string = "action.talk('"+ai.selfID+"'[#id], perf.ack.denyrequest("+requester+"))";
					let cause:Term = Term.fromString("#not(verb.know('"+ai.selfID+"'[#id], #and(the(P:'path'[path], N:[singular]), noun(P, N))))", ai.o);
					let term:Term = Term.fromString(tmp, ai.o);
					ai.intentions.push(new IntentionRecord(term, null, null, new CauseRecord(cause, null, ai.timeStamp), ai.timeStamp));
				}
				ir.succeeded = false;
				return true;
			}

			app.achievement_nlp_all_robot_actions[5] = true;
			app.trigger_achievement_complete_alert();

			// go to destination:
	        let q:A4ScriptExecutionQueue = new A4ScriptExecutionQueue(ai.robot, ai.robot.map, ai.game, null);
	        let s:A4Script = null
	        s = new A4Script(A4_SCRIPT_GOTO_OPENING_DOORS, destinationMap.name, null, 0, false, false);
	        s.x = destinationX;
	        s.y = destinationY;
	        q.scripts.push(s);
	        for(let item of item_l) {
	    		s = new A4Script(A4_SCRIPT_DROP, item.ID, null, 0, false, false);
	        	q.scripts.push(s);

				// If the object was not mentioned explicitly in the performative, add it to the natural language context:
				if (ir.requestingPerformative != null) ir.requestingPerformative.addMentionToPerformative(item.ID, ai.o);

	        	numberConstraint--;
	        	if (numberConstraint <= 0) break;
	        }
			ai.setNewAction(alternative_actions[0], requester, q, null);
			ai.addCurrentActionLongTermTerm(alternative_actions[0]);
			ai.intentionsCausedByRequest.push(ir);
			if (requester != null) {
				let tmp:string = "action.talk('"+ai.selfID+"'[#id], perf.ack.ok("+requester+"))";
				let term:Term = Term.fromString(tmp, ai.o);
				ai.intentions.push(new IntentionRecord(term, null, null, null, ai.timeStamp));
			}

		}
		ir.succeeded = true;
		return true;
	}

	saveToXML(ai:RuleBasedAI) : string
	{
		return "<IntentionAction type=\"RobotDrop_IntentionAction\"/>";
	}

	static loadFromXML(xml:Element, ai:RuleBasedAI) : IntentionAction
	{
		return new RobotDrop_IntentionAction();
	}
}


text:
layout: post
date: 2018-01-17
title: "Blush Prom Style 7000 Sleeveless Sweep/Brush Train Aline/Princess"
category: Blush
tags: [Blush,Aline/Princess ,Jewel,Sweep/Brush Train,Sleeveless]
---
### Blush Prom Style 7000
Just **$579.99**
###   Sleeveless Sweep/Brush Train Aline/Princess

BRANDS	Blush

Silhouette	Aline/Princess

Neckline	Jewel

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/blush/49196-blush-prom-style-7000.html](https://www.readybrides.com/en/blush/49196-blush-prom-style-7000.html)


text:
iOSTint.js

A jQuery plugin to change the Safari URL bar tint colour on iOS7.

Download the file from here, and include it, along with jQuery, at the bottom of your HTML.
	    		<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="js/iosTint.min.js"></script>

Call the script beneath the include.
	    		<script>
    $.iosTint(color);
</script>
				You can replace color with any valid html colour such as  #69BEE5 ,  rgb(144,248,67) or even tomato .

	    	Github
	    	Twitter


text:
using Newtonsoft.Json;

namespace Gfycat.API
{
    internal class GfyResponse
    {
        [JsonProperty("gfyItem")]
        internal Models.Gfy GfyItem { get; set; }
    }
}


text:
@interface Windmill : Sprite

@end


text:
(function () {
/*global define*/
define('Core/defined',[],function() {
    "use strict";

    /**
     * Returns true if the object is defined, returns false otherwise.
     *
     * @exports defined
     *
     * @example
     * if (defined(positions)) {
     *      doSomething();
     * } else {
     *      doSomethingElse();
     * }
     */
    var defined = function(value) {
        return value !== undefined;
    };

    return defined;
});

/*global define*/
define('Workers/taskDispatcher',[
        'require',
        '../Core/defined'
    ], function(
        require,
        defined) {
    "use strict";

    var taskWorkerCache = {};

    /**
     * A worker that delegates tasks from a TaskProcessor to other workers by
     * inspecting the parameters for a "task" property, which is expected to be
     * the module ID of another worker.  This worker will load that worker, if not
     * already loaded, then pass the event to that worker.
     *
     * @exports taskDispatcher
     *
     * @see TaskProcessor
     * @see Web Workers
     * @see Transferable objects
     */
    var taskDispatcher = function(event) {
        var taskWorkerName = event.data.parameters.task;
        var taskWorker = taskWorkerCache[taskWorkerName];
        if (defined(taskWorker)) {
            taskWorker(event);
        } else {
            require(['./' + taskWorkerName], function(taskWorker) {
                taskWorkerCache[taskWorkerName] = taskWorker;
                taskWorker(event);
            });
        }
    };

    return taskDispatcher;
});
}());


text:
/** @jsx h */

import h from '../../../helpers/h'

export default function (change) {
  change.splitBlock()
}

export const input = (
  <state>
    <document>
      <paragraph>
        <link>wo<cursor />rd</link>
      </paragraph>
    </document>
  </state>
)

export const output = (
  <state>
    <document>
      <paragraph>
        <link>wo</link>
      </paragraph>
      <paragraph>
        <link><cursor />rd</link>
      </paragraph>
    </document>
  </state>
)


text:
<template name="textarea">

        Textarea:

            <textarea rows="5" cols="5" class="form-control" placeholder="Default textarea"></textarea>

</template>


text:
//
//  YKRemoteACViewController.m
//  YKCenterDemo
//
//  Created by Don on 2017/6/28.
//  Copyright © 2017年 Shenzhen Yaokan Technology Co., Ltd. All rights reserved.
//

#import "YKRemoteACViewController.h"
#import <YKCenterSDK/YKCenterSDK.h>
#import "YKCenterCommon.h"

@interface YKRemoteACViewController ()

@property (weak, nonatomic) IBOutlet UILabel *modelLabel;
@property (weak, nonatomic) IBOutlet UILabel *windLabel;
@property (weak, nonatomic) IBOutlet UILabel *sweepUDLabel;
@property (weak, nonatomic) IBOutlet UILabel *sweepLRLabel;
@property (weak, nonatomic) IBOutlet UILabel *tempLabel;

@property (nonatomic, strong) NSArray *modelKeys;
@property (nonatomic, strong) NSArray *modelKeyNames;

@property (nonatomic, copy) NSString *currentModel;
@property (nonatomic, assign) NSUInteger temperature;   // 16~30
@property (nonatomic, assign) NSUInteger currentSpeed;  // 0~9
@property (nonatomic, assign) NSUInteger currentWindU;  // 0~9
@property (nonatomic, assign) NSUInteger currentWindL;  // 0~9

@property (nonatomic, strong) NSArray<YKRemoteDeviceKey *> *asteriskDatas;

@end

@implementation YKRemoteACViewController

- (NSString *)currentModel {
    if (!_currentModel || _currentModel.length == 0) {
        _currentModel = ACModelCool; // cool
    }

    return _currentModel;
}

- (NSArray<YKRemoteDeviceKey *> *)asteriskDatas {
    if (_asteriskDatas == nil) {
        _asteriskDatas = [YKRemoteDeviceKey asteriskKeysWithRemote:self.remote];
    }

    return _asteriskDatas;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = self.remote.name;

    self.modelKeys = @[ACModelAuto, ACModelCool, ACModelDry, ACModelWind, ACModelHot];
    self.modelKeyNames = @[NSLocalizedString(@"自动", @"a"),
                           NSLocalizedString(@"制冷", @"r"),
                           NSLocalizedString(@"抽湿", @"d"),
                           NSLocalizedString(@"送风", @"w"),
                           NSLocalizedString(@"制热", @"h")];
    self.temperature = 23;

    _currentWindL = 0;
    _currentWindU = 0;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self updateStatusView];
}

- (IBAction)modelAction:(id)sender {
    NSInteger modelIndex = [self.modelKeys indexOfObject:_currentModel];
    if (modelIndex + 1 >= self.modelKeys.count) {
        modelIndex = 0;
    } else {
        modelIndex++;
    }
    _currentModel = [self.modelKeys objectAtIndex:modelIndex];

    [self remoteControl];
    [self updateStatusView];
}

/**
 风量调整

 A 表示自动档

 @param sender 消息发送的对象
 */
- (IBAction)windAction:(id)sender {
    if (_currentSpeed < 3) {
        _currentSpeed++;
    } else  {
        _currentSpeed = 0;
    }

    if ([_currentModel isEqualToString:ACModelDry]) {
        // 抽湿只有 1档s1
        _currentSpeed = 1;
    }
    if ([_currentModel isEqualToString:ACModelWind] && _currentSpeed == 0) {
        // 送风没有 s0
        _currentSpeed = 1;
    }

    [self remoteControl];
    [self updateStatusView];
}

/**
 切换上下扫风

 目前仅支持关和自动

 @param sender 消息发送的对象
 */
- (IBAction)sweepUDAction:(id)sender {
    if (_currentWindU < 1) {
        _currentWindU++;
    } else if (_currentWindU != INT_MAX) {
        _currentWindU = 0;
    }

    [self remoteControl];
    [self updateStatusView];
}

/**
 切换左右扫风

 目前仅支持关和自动

 @param sender 消息发送的对象
 */
- (IBAction)sweepLRAction:(id)sender {
    if (_currentWindL < 1) {
        _currentWindL++;
    } else if (_currentWindU != INT_MAX) {
        _currentWindL = 0;
    }

    [self remoteControl];
    [self updateStatusView];
}

- (IBAction)tempAction:(UIStepper *)sender {
    _temperature = sender.value;
    [self remoteControl];
    [self updateStatusView];
}

- (IBAction)powerOnAction:(id)sender {
    [self remoteControl];
    [self updateStatusView];
}

- (IBAction)powerOffAction:(id)sender {
    YKRemoteDeviceKey *key = [YKRemoteDeviceKey remoteDeviceKeyInRemoteDevice:self.remote
                                                                          key:KeyPowerOff];
    [YKCenterSDK sendRemoteWithYKCId:[[YKCenterCommon sharedInstance] currentYKCId]
                               datas:@[key]
                          completion:nil];
}

- (void)remoteControl {
    [YKCenterSDK sendRemoteKeyWithYKCId:[[YKCenterCommon sharedInstance] currentYKCId]
                           remoteDevice:self.remote
                               withMode:self.currentModel
                                   temp:self.temperature
                                  speed:self.currentSpeed
                                  windU:self.currentWindU
                                  windL:self.currentWindL
                          asteriskDatas:self.asteriskDatas
                             completion:^(BOOL result, NSError * _Nonnull error) {
                                 NSLog(@"result=%s, error=%@", result ? "true" : "false", error);
                             }];
}

- (void)updateStatusView {
    // 空调只有在制冷、制热模式下才显示温度,温度才可调,其它模式,温度不显示
    if (([self.currentModel isEqualToString:@"r"]
         || [self.currentModel isEqualToString:@"h"])
        && _temperature != 0)
    {
        _tempLabel.text = [NSString stringWithFormat:@"%ld", (long)_temperature];
    }
    else {
        _tempLabel.text = @"--";
    }

    self.modelLabel.text = [self.modelKeyNames objectAtIndex:[self.modelKeys indexOfObject:self.currentModel]];

    if (_currentSpeed != INT_MAX) {
        self.windLabel.text = _currentSpeed==0?@"A":[NSString stringWithFormat:@"%lu", (unsigned long)_currentSpeed];
    }
    else {
        self.windLabel.text = @"";
    }

    if (_currentWindU != INT_MAX) {
        if (_currentWindU>1) {
            // +1个区间-(关闭和自动),(u2是一档)
            self.sweepUDLabel.text = [NSString stringWithFormat:@"%ld 档", _currentWindU-1];
        } else if (_currentWindU == 1) {
            // auto mode
            self.sweepUDLabel.text = @"自动";
        } else {
            self.sweepUDLabel.text = @"--";
        }
    }
    else {
        self.sweepUDLabel.text = @"--";
    }

    if (_currentWindL != INT_MAX) {
        if (_currentWindL>1) {
            // +1个区间-(关闭和自动),(l2是一档)
            self.sweepLRLabel.text = [NSString stringWithFormat:@"%ld 档", _currentWindL-1];
        } else if (_currentWindL == 1) {
            // auto mode
            self.sweepLRLabel.text = @"自动";
        } else {
            self.sweepLRLabel.text = @"--";
        }
    }
    else {
        self.sweepLRLabel.text = @"--";
    }
}

@end


text:
package com.appleframework.data.hbase.config;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
import org.apache.hadoop.hbase.client.HTablePool;

@SuppressWarnings("deprecation")
public class PooledHTableFactory implements HTableInterfaceFactory {

	private HTablePool tablePool;

	public PooledHTableFactory(HTablePool tablePool) {
		this.tablePool = tablePool;
	}

	@Override
	public HTableInterface createHTableInterface(Configuration config, byte[] tableName) {
		return tablePool.getTable(tableName);
	}

	@Override
	public void releaseHTableInterface(HTableInterface table) throws IOException {
		table.close();
	}

}


text:
package net.automatalib.commons.util;

/**
 * The well-known disjoint-set forest data structure for dealing with partitions on a fixed-range integer domain.
 *
 * @author fhowar
 * @author Malte Isberner
 */
public final class UnionFind implements IntDisjointSets {

    private final int[] p;
    private final int[] rank;

    /**
     * Initializes the disjoint-set data structure.
     *
     * @param n
     *         the overall size of the domain
     */
    public UnionFind(int n) {
        p = new int[n];
        rank = new int[n];

        for (int i = 0; i < n; i++) {
            // primitive arrays are always zero initialized
            // rank[i] = 0;
            p[i] = i;
        }
    }

    @Override
    public int size() {
        return p.length;
    }

    /**
     * Finds the set of a given element, and compresses the path to the root node.
     *
     * @param x
     *         the element
     *
     * @return the identifier of the set which contains the given element
     */
    @Override
    public int find(int x) {
        int curr = x;
        int currp = p[curr];
        while (curr != currp) {
            curr = currp;
            currp = p[curr];
        }
        int ancestor = curr;
        curr = x;
        while (curr != ancestor) {
            int next = p[curr];
            p[curr] = ancestor;
            curr = next;
        }

        return ancestor;
    }

    /**
     * Unites two given sets. Note that the behavior of this method is not specified if the given parameters are normal
     * elements and no set identifiers.
     *
     * @param x
     *         the first set
     * @param y
     *         the second set
     *
     * @return the identifier of the resulting set (either {@code x} or {@code y})
     */
    @Override
    public int link(int x, int y) {
        int rx = rank[x], ry = rank[y];
        if (rx > ry) {
            p[y] = x;
            return x;
        }
        p[x] = y;
        if (rx == ry) {
            rank[y] = ry + 1;
        }
        return y;
    }

}