text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\PLANAUDITORIA;

/**
 * PLANAUDITORIASearch represents the model behind the search form about `app\models\PLANAUDITORIA`.
 */
class PLANAUDITORIASearch extends PLANAUDITORIA
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['AAU_ID'], 'integer'],
            [['AAU_FECHAINICIO', 'AAU_FECHAEJECUCION', 'AAU_FECHACIERRE'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = PLANAUDITORIA::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'AAU_ID' => $this->AAU_ID,
            'AAU_FECHAINICIO' => $this->AAU_FECHAINICIO,
            'AAU_FECHAEJECUCION' => $this->AAU_FECHAEJECUCION,
            'AAU_FECHACIERRE' => $this->AAU_FECHACIERRE,
        ]);

        return $dataProvider;
    }
}


text:
date: 2017-03-22T00:25:01Z
title: La plateforme
url: /fr/documentation/installation/hello-world
---

Le tableau de bord(dashboard) Waziup est en construction.

En attendant, vous pouvez accéder à toutes les fonctionnalités de Waziup en utilisant les [tutoriels](/fr/documentation/tutorials/).

![Dashboard](/documentation/installation/Waziup-dashboard.png)

redpajama_set_name: RedPajamaGithub


text:
var App;
(function (App) {
    (function (Services) {
        var AppService = (function () {
            function AppService($http, $q, $authService, $notifyService, baseUrl, $identityService) {
                this.$http = $http;
                this.$q = $q;
                this.$authService = $authService;
                this.$notifyService = $notifyService;
                this.baseUrl = baseUrl;
                this.$identityService = $identityService;
            }
            AppService.prototype.getUsers = function (page, filter) {
                var url = "api/users?";

                if (page) {
                    url += "page=" + page + "&";
                }

                if (filter && filter !== "") {
                    url += "username=" + filter;
                }

                return this._getRequest(url);
            };

            AppService.prototype.getAlbums = function (page, filter) {
                var url = this.$identityService.currentUser._id + "/albums?";

                if (page) {
                    url += "page=" + page + "&";
                }

                if (filter && filter !== "") {
                    url += "filter=" + filter;
                }

                return this._getRequest(url);
            };

            AppService.prototype.getAlbum = function (albumId) {
                var url = this.$identityService.currentUser._id + "/albums/" + albumId;
                return this._getRequest(url);
            };

            AppService.prototype.createAlbum = function (album) {
                var url = this.$identityService.currentUser._id + "/albums";
                return this._postRequest(url, album);
            };

            AppService.prototype.updateAlbum = function (album) {
                var url = this.$identityService.currentUser._id + "/albums";
                return this._putRequest(url, album);
            };

            AppService.prototype.addPhotoToAlbum = function (albumId, photo) {
                var url = this.$identityService.currentUser._id + "/" + albumId;
                return this._postRequest(url, photo);
            };

            AppService.prototype.getUserDetails = function (id) {
                var url = "api/drivers/" + id;
                if (this.$identityService.isAuthenticated()) {
                    return this._getRequest(url);
                }
            };

            AppService.prototype._postRequest = function (address, data) {
                var _this = this;
                var promise = this.$http.post(this.baseUrl + address, data);
                promise.error(function (error) {
                    return _this.$notifyService.error(error);
                });

                return promise;
            };

            AppService.prototype._putRequest = function (address, data) {
                var _this = this;
                var promise = this.$http.put(this.baseUrl + address, data);
                promise.error(function (error) {
                    return _this.$notifyService.error(error);
                });

                return promise;
            };

            AppService.prototype._getRequest = function (address) {
                var _this = this;
                var promise = this.$http.get(this.baseUrl + address);
                promise.error(function (error) {
                    return _this.$notifyService.error(error);
                });

                return promise;
            };
            return AppService;
        })();
        Services.AppService = AppService;
    })(App.Services || (App.Services = {}));
    var Services = App.Services;
})(App || (App = {}));
//# sourceMappingURL=appService.js.map


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.yoyuapp</groupId>
	<artifactId>sqlBuilder</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>

			<!-- 默认跳过测试 -->
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<argLine>-Dfile.encoding=UTF-8</argLine>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>

			<plugin>  <!-- 生成源码包 -->
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<attach>true</attach>
				</configuration>
				<executions>
					<execution>
						<phase>compile</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<!--私服发布地址 -->
	<distributionManagement>
		<repository>
			<id>nexus-releases</id>
			<url>http://192.168.1.112:8082/nexus/content/repositories/releases/</url>
		</repository>
		<snapshotRepository>
			<id>nexus-snapshots</id>
			<url>http://192.168.1.112:8082/nexus/content/repositories/snapshots/</url>
		</snapshotRepository>
	</distributionManagement>
</project>


text:
package edu.umd.cs.psl.reasoner.function;

/**
 * A {@link FunctionTerm} with at most one {@link FunctionVariable}.
 */
public interface FunctionSingleton extends FunctionTerm {

}


text:
void dump_ast(struct node *root, const char *path);

#endif


text:
<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * Contacts table.
 */
class Transactions extends CI_Model
{
    // Constructor
    function __construct()
    {
        parent::__construct();
    }
    //grab the data from server and populate the database
    function init($values)
    {
        $query = $this->db->query("DELETE FROM transactions");
        for($i = 1; $i < sizeof($values); $i++)
        {
            $tran = str_getcsv($values[$i], ",");
            $query = $this->db->query('Insert into transactions values("'.$tran[0].'","'.$tran[1].'",'
                    . '"'.$tran[2].'","'.$tran[3].'","'.$tran[4].'","'.$tran[5].'","'.$tran[6].'")');
        }
    }

    // return all transactions
    function all()
    {
        $this->db->order_by("DateTime", "asc");
        $query = $this->db->get('transactions');
        return $query->result_array();
    }
    //get all transaction belonging to one player
    public function get_all_by_player($which)
    {
        $sql = "SELECT * FROM transactions WHERE Player = ?";
        $query = $this->db->query($sql, array($which));
        if ($query->num_rows() > 0)
            return $query->result_array();
        return null;
    }
    //get the value of a specific stock
    public function get_stock_value($stock)
    {
        $stock_value = null;
        $sql = "SELECT  s.Value "
                . "FROM stocks s "
                . "WHERE s.Code = '"
                . $stock
                . "'";
        $query = $this->db->query($sql)->result_array();
        if (!empty($query)) {
            $stock_value = $query[0]['Value'];
        }
        return $stock_value;
    }

    //get transactions belonging to a stock
    public function get_stock($stock)
    {
        $stock_value = null;
        $sql = "SELECT  * "
                . "FROM transactions t "
                . "WHERE t.Stock = '"
                . $stock
                . "'";
        $query = $this->db->query($sql)->result_array();
        return $query;
    }
}


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <title><%= props.name %> Demo</title>
    <script src="../../webcomponentsjs/webcomponents-lite.min.js"></script>
    <link rel="import" href="../<%= props.name %>.html">
  </head>
  <body unresolved>
    <<%= props.name %>>Hello World</<%= props.name %>>
  </body>
</html>


text:
set -o errexit
set -o nounset
set -o pipefail

KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${KUBE_ROOT}/hack/lib/init.sh"

kube::golang::setup_env

GO111MODULE=on GOPROXY=off go install k8s.io/code-generator/cmd/import-boss

packages=(
  "k8s.io/kubernetes/pkg/..."
  "k8s.io/kubernetes/cmd/..."
  "k8s.io/kubernetes/plugin/..."
  "k8s.io/kubernetes/test/e2e/framework/..."
  "k8s.io/kubernetes/test/integration/..."
)
for d in staging/src/k8s.io/*/; do
  if [ -d "$d" ]; then
    packages+=("./vendor/${d#"staging/src/"}...")
  fi
done

$(kube::util::find-binary "import-boss") --include-test-files=true --verify-only --input-dirs "$(IFS=, ; echo "${packages[*]}")"


text:
'use strict';

/**
 * @fileoverview Ensures `<meta http-equiv="refresh">` is not used.
 * See base class in axe-audit.js for audit() implementation.
 */

const AxeAudit = require('./axe-audit.js');
const i18n = require('../../lib/i18n/i18n.js');

const UIStrings = {
  /** Title of an accesibility audit that evaluates if the page uses a meta tag that refreshes the page automatically. This title is descriptive of the successful state and is shown to users when no user action is required. */
  title: 'The document does not use `<meta http-equiv="refresh">`',
  /** Title of an accesibility audit that evaluates if the page uses a meta tag that refreshes the page automatically. This title is descriptive of the failing state and is shown to users when there is a failure that needs to be addressed. */
  failureTitle: 'The document uses `<meta http-equiv="refresh">`',
  /** Description of a Lighthouse audit that tells the user *why* they should try to pass. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
  description: 'Users do not expect a page to refresh automatically, and doing so will move ' +
      'focus back to the top of the page. This may create a frustrating or ' +
      'confusing experience. ' +
      '[Learn more](https://web.dev/meta-refresh/).',
};

const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

class MetaRefresh extends AxeAudit {
  /**
   * @return {LH.Audit.Meta}
   */
  static get meta() {
    return {
      id: 'meta-refresh',
      title: str_(UIStrings.title),
      failureTitle: str_(UIStrings.failureTitle),
      description: str_(UIStrings.description),
      requiredArtifacts: ['Accessibility'],
    };
  }
}

module.exports = MetaRefresh;
module.exports.UIStrings = UIStrings;


text:
from __future__ import unicode_literals

from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible

from series.models import Series

@python_2_unicode_compatible
class Monster(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField()
    series = models.ManyToManyField(
        Series, blank=True, limit_choices_to=Q(series__isnull=True), related_name='monsters'
    )

    class Meta(object):
        ordering = ('name',)

    def __str__(self):
        return self.name


text:
package org.apache.giraph.types;

import org.apache.hadoop.io.Writable;

import com.google.common.collect.Maps;

import java.util.Map;

import static org.apache.giraph.types.JavaWritablePair.BOOLEAN_BOOLEAN_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.BYTE_BYTE_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.DOUBLE_DOUBLE_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.DOUBLE_FLOAT_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.FLOAT_FLOAT_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.INT_BYTE_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.INT_INT_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.LONG_BYTE_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.LONG_INT_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.LONG_LONG_WRITABLE;
import static org.apache.giraph.types.JavaWritablePair.SHORT_BYTE_WRITABLE;

/**
 * Mapping of all the known Writable wrappers.
 */
public class WritableUnwrappers {
  /** Map of (Writable,Java)-type pair to wrapper for those types */
  private static final Map<JavaWritablePair, WritableUnwrapper> MAP;

  static {
    MAP = Maps.newHashMap();
    MAP.put(BOOLEAN_BOOLEAN_WRITABLE, new BooleanWritableToBooleanUnwrapper());
    MAP.put(BYTE_BYTE_WRITABLE, new ByteWritableToByteUnwrapper());
    MAP.put(DOUBLE_DOUBLE_WRITABLE, new DoubleWritableToDoubleUnwrapper());
    MAP.put(DOUBLE_FLOAT_WRITABLE, new FloatWritableToDoubleUnwrapper());
    MAP.put(FLOAT_FLOAT_WRITABLE, new FloatWritableToFloatUnwrapper());
    MAP.put(INT_BYTE_WRITABLE, new ByteWritableToIntUnwrapper());
    MAP.put(INT_INT_WRITABLE, new IntWritableToIntUnwrapper());
    MAP.put(SHORT_BYTE_WRITABLE, new ByteWritableToShortUnwrapper());
    MAP.put(LONG_BYTE_WRITABLE, new ByteWritableToLongUnwrapper());
    MAP.put(LONG_INT_WRITABLE, new IntWritableToLongUnwrapper());
    MAP.put(LONG_LONG_WRITABLE, new LongWritableToLongUnwrapper());
  }

  /** Don't construct */
  private WritableUnwrappers() { }

  /**
   * Lookup type converter
   *
   * @param writableClass class of Writable
   * @param javaClass class of Java type
   * @param <W> Writable type
   * @param <J> Java type
   * @return {@link WritableUnwrapper}
   */
  public static <W extends Writable, J> WritableUnwrapper<W, J> lookup(
      Class<W> writableClass, Class<J> javaClass) {
    return lookup(JavaWritablePair.create(writableClass, javaClass));
  }

  /**
   * Lookup type converter
   *
   * @param classes JavaAndWritableClasses
   * @param <W> Writable type
   * @param <J> Java type
   * @return {@link WritableUnwrapper}
   */
  public static <W extends Writable, J> WritableUnwrapper<W, J> lookup(
      JavaWritablePair<W, J> classes) {
    return MAP.get(classes);
  }
}


text:
@interface QN_UploadFileWithCRC32 : BaseVC<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *choseBtn;
@property (weak, nonatomic) IBOutlet UIButton *uploadBtn;
@property (weak, nonatomic) IBOutlet UILabel *showLabel;
@property (weak, nonatomic) IBOutlet UIImageView * uploadImage;
@property (weak, nonatomic) IBOutlet UIProgressView *prograssView;
@property (weak, nonatomic) IBOutlet UITextField *fillKey;
@property (weak, nonatomic) IBOutlet UISwitch *isUseCRC32;

@end


text:
module MemoryProfiler

  class Monochrome

    def path(text)
      text
    end

    def string(text)
      text
    end

    def line(text)
      text
    end
  end

end


text:
namespace fs = utils::fs;

namespace {

/// Constant that represents the path to stdout.
static const fs::path stdout_path("/dev/stdout");

/// Constant that represents the path to stderr.
static const fs::path stderr_path("/dev/stderr");

}  // anonymous namespace

/// Opens a new file for output, respecting the stdout and stderr streams.
///
/// \param path The path to the output file to be created.
///
/// \return A pointer to a new output stream.
std::auto_ptr< std::ostream >
utils::open_ostream(const fs::path& path)
{
    std::auto_ptr< std::ostream > out;
    if (path == stdout_path) {
        out.reset(new std::ofstream());
        out->copyfmt(std::cout);
        out->clear(std::cout.rdstate());
        out->rdbuf(std::cout.rdbuf());
    } else if (path == stderr_path) {
        out.reset(new std::ofstream());
        out->copyfmt(std::cerr);
        out->clear(std::cerr.rdstate());
        out->rdbuf(std::cerr.rdbuf());
    } else {
        out.reset(new std::ofstream(path.c_str()));
        if (!(*out)) {
            throw std::runtime_error(F("Cannot open output file %s") % path);
        }
    }
    INV(out.get() != NULL);
    return out;
}

/// Gets the length of a stream.
///
/// \param is The input stream for which to calculate its length.
///
/// \return The length of the stream.  This is of size_t type instead of
/// directly std::streampos to simplify the caller.  Some systems do not
/// support comparing a std::streampos directly to an integer (see
/// NetBSD 1.5.x), which is what we often want to do.
///
/// \throw std::exception If calculating the length fails due to a stream error.
std::size_t
utils::stream_length(std::istream& is)
{
    const std::streampos current_pos = is.tellg();
    try {
        is.seekg(0, std::ios::end);
        const std::streampos length = is.tellg();
        is.seekg(current_pos, std::ios::beg);
        return static_cast< std::size_t >(length);
    } catch (...) {
        is.seekg(current_pos, std::ios::beg);
        throw;
    }
}

/// Reads a whole file into memory.
///
/// \param path The file to read.
///
/// \return A plain string containing the raw contents of the file.
///
/// \throw std::runtime_error If the file cannot be opened.
std::string
utils::read_file(const fs::path& path)
{
    std::ifstream input(path.c_str());
    if (!input)
        throw std::runtime_error(F("Failed to open '%s' for read") % path);
    return read_stream(input);
}

/// Reads the whole contents of a stream into memory.
///
/// \param input The input stream from which to read.
///
/// \return A plain string containing the raw contents of the file.
std::string
utils::read_stream(std::istream& input)
{
    std::ostringstream buffer;

    char tmp[1024];
    while (input.good()) {
        input.read(tmp, sizeof(tmp));
        if (input.good() || input.eof()) {
            buffer.write(tmp, input.gcount());
        }
    }

    return buffer.str();
}


text:
class Adm::Reports::BaseController < Adm::BaseController
  inherit_resources
  responders :csv
  respond_to :csv
  actions :index
end


text:
using System;

namespace ExactOnline.Client.Sdk.Exceptions
{
    [Serializable]
    public class InternalServerErrorException : Exception // HTTP 500
    {
        public InternalServerErrorException() { }
        public InternalServerErrorException(string message) : base(message) { }
        public InternalServerErrorException(string message, Exception inner) : base(message, inner) { }
        protected InternalServerErrorException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }
}


text:
package io.moxd.moco2016.backgroundoperations;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class AlarmActivity extends AppCompatActivity {

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

    public void clickButtonAlarmOkay(View view) {
        finish();
    }
}


text:
{% extends "base.html" %}

{% block stuff %}

Projects with application {{ application }}

{% end %}


text:
/*eslint strict:0*/

casper.test.begin('logging tests', 4, function(test) {
    casper.start('tests/site/index.html');

    var oldLevel = casper.options.logLevel;

    casper.options.logLevel = 'info';
    casper.options.verbose = false;

    casper.log('foo', 'info');
    casper.test.assert(casper.result.log.some(function(e) {
        return e.message === 'foo' && e.level === 'info';
    }), 'Casper.log() adds a log entry');

    casper.options.logLevel = oldLevel;
    casper.options.verbose = true;

    casper.then(function() {
        var oldLevel = casper.options.logLevel;
        casper.options.logLevel = 'debug';
        casper.options.verbose = false;
        casper.evaluate(function() {
            __utils__.log('debug message');
            __utils__.log('info message', 'info');
        });
        test.assert(casper.result.log.some(function(e) {
            return e.message === 'debug message' && e.level === 'debug' && e.space === 'remote';
        }), 'ClientUtils.log() adds a log entry');
        test.assert(casper.result.log.some(function(e) {
            return e.message === 'info message' && e.level === 'info' && e.space === 'remote';
        }), 'ClientUtils.log() adds a log entry at a given level');
        casper.options.logLevel = oldLevel;
        casper.options.verbose = true;
    });

    casper.run(function() {
        test.assertEquals(this.result.log.length, 3, 'Casper.log() logged messages');
        test.done();
    });
});


text:
npm-onupdate
============

CLI for [npm-onupdate.info](http://npm-onupdate.info), a [NPM](https://npmjs.org/) registry email notification service.

The server side source code be found [here](https://github.com/pwalczyszyn/npm-onupdate-server).

###INSTALLATION

    > npm install -g npm-onupdate

###USAGE

####Adding new package alert

    $ npm-onupdate add express

####Adding multiple package alerts

    $ npm-onupdate add 'express ejs'

####Adding alerts for all dependencies from package.info file in current dir

    $ npm-onupdate add

####Removing package alert

    $ npm-onupdate rm express

####Removing multiple package alerts

    $ npm-onupdate rm 'express ejs'

####Listing all registered alerts

    $ npm-onupdate ls

####Get account info

    $ npm-onupdate account info

####Change account password

    $ npm-onupdate account password

####Delete account

    $ npm-onupdate account delete

####Logout

    $ npm-onupdate account logout

###License

  MIT


text:
package web2tcp

import (
	"crypto/tls"
	"log"
	"net"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	"github.com/gorilla/websocket"
	"github.com/igm/sockjs-go/sockjs"
)

type FrontendOptions struct {
	Endpoint string
	Route    string
	Tls      struct {
		Enabled     bool
		CertFile    string
		CertKeyFile string
	}
}

type Frontend struct {
	options *FrontendOptions
	router  *mux.Router
}

var wsUpgrader = websocket.Upgrader{
	ReadBufferSize:  4096,
	WriteBufferSize: 4096,
	CheckOrigin:     func(r *http.Request) bool { return true },
}

var sockjsOptions = sockjs.DefaultOptions

func NewFrontend(options *FrontendOptions) *Frontend {
	frontend := &Frontend{
		options: options,
		router:  mux.NewRouter(),
	}

	return frontend
}

func (f Frontend) Listen() {
	var err error
	var listener net.Listener

	http.Handle("/", f.router)

	if f.options.Tls.Enabled {
		cert, certErr := tls.LoadX509KeyPair(f.options.Tls.CertFile, f.options.Tls.CertKeyFile)

		if certErr != nil {
			log.Println(certErr)
			return
		}

		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
		}

		listener, err = tls.Listen("tcp4", f.options.Endpoint, tlsConfig)
		//err = http.ListenAndServeTLS(f.options.Endpoint, f.options.Tls.CertFile, f.options.Tls.CertKeyFile, nil)
	} else {
		listener, err = net.Listen("tcp4", f.options.Endpoint)
		//err = http.ListenAndServe(f.options.Endpoint, nil)
	}

	http.Serve(listener, nil)

	if err != nil {
		log.Panic(err)
	}
}

func (f *Frontend) RouteHandler(route string, handler func(Session)) {
	log.Printf("Registering SockJS Route [\\%s]\n", route)
	log.Printf("Registering WebSocket Route [\\%s\\websocket]\n", route)

	f.router.PathPrefix("/" + route + "/websocket").HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		wsConn, _ := wsUpgrader.Upgrade(resp, req, nil)
		xfHeader := req.Header.Get("X-Forwarded-For")
		var clientAddr string

		if len(xfHeader) > 0 {
			clientAddr = strings.Split(xfHeader, ",")[0]
			if !strings.ContainsRune(clientAddr, ':') {
				clientAddr = clientAddr + ":0"
			}
		} else {
			clientAddr = req.RemoteAddr
		}

		go handler(newWSSession(wsConn, clientAddr))
	})

	sockjsHandler := sockjs.NewHandler("/"+route, sockjsOptions, func(session sockjs.Session) {
		var clientAddr string

		xfHeader := session.Request().Header.Get("X-Forwarded-For")

		if len(xfHeader) > 0 {
			clientAddr = strings.Split(xfHeader, ",")[0]

			if !strings.ContainsRune(clientAddr, ':') {
				clientAddr = clientAddr + ":0"
			}
		} else {
			clientAddr = session.Request().RemoteAddr
		}

		go handler(newSockJSSession(session, clientAddr))
	})

	f.router.PathPrefix("/" + route + "/").Handler(sockjsHandler)
}


text:
/*
 * Created on Feb 28, 2004
 *
 */
package groovy.jface.factory;

import groovy.lang.Closure;
import groovy.swt.ClosureSupport;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Event;

/**
 * @author <a href:ckl at dacelo.nl">Christiaan ten Klooster </a>
 * @version $Revision: 1561 $
 */
public class ActionImpl extends Action implements ClosureSupport {

    private Closure closure;

    private Event event;

    public void runWithEvent(Event event) {
        if (closure == null) {
            throw new NullPointerException("No closure has been configured for this Listener");
        }
        this.event = event;

        closure.call(event);
    }

    public Closure getClosure() {
        return closure;
    }

    public void setClosure(Closure closure) {
        this.closure = closure;
    }

    public Event getEvent() {
        return event;
    }
}


text:
package ru.job4j.chess;

/**
 * Class Figure.
 * @author Alexander Ivanov
 * @since 12.02.2017
 * @version 1.0
 */
public abstract class Figure {

    /**
     * Starting position.
     */
    final Cell position;

    /**
     * Constructor for Figure.
     * @param position for start.
     */
    Figure(Cell position) {
        this.position = position;
    }

    /**
     * Method for return possible move of figure.
     * @param dist - cell for destination.
     * @return array of cell.
     * @throws ImpossibleMoveException when move is impossible.
     */
    abstract Cell[] way(Cell dist) throws ImpossibleMoveException;

    /**
     * Method for clone figure.
     * @param dist - destination cell for clone.
     * @return new figure.
     */
    abstract Figure clone(Cell dist);
}


text:
package org.apache.qpid.protonj2.codec.messaging;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.buffer.ProtonBufferInputStream;
import org.apache.qpid.protonj2.buffer.ProtonByteBufferAllocator;
import org.apache.qpid.protonj2.codec.CodecTestSupport;
import org.apache.qpid.protonj2.codec.DecodeException;
import org.apache.qpid.protonj2.codec.EncodingCodes;
import org.apache.qpid.protonj2.codec.StreamTypeDecoder;
import org.apache.qpid.protonj2.codec.TypeDecoder;
import org.apache.qpid.protonj2.codec.decoders.messaging.PropertiesTypeDecoder;
import org.apache.qpid.protonj2.codec.encoders.messaging.PropertiesTypeEncoder;
import org.apache.qpid.protonj2.types.Binary;
import org.apache.qpid.protonj2.types.UnsignedInteger;
import org.apache.qpid.protonj2.types.messaging.Modified;
import org.apache.qpid.protonj2.types.messaging.Properties;
import org.junit.jupiter.api.Test;

/**
 * Test for decoder of AMQP Properties type.
 */
public class PropertiesTypeCodecTest extends CodecTestSupport {

    @Test
    public void testTypeClassReturnsCorrectType() throws IOException {
        assertEquals(Properties.class, new PropertiesTypeDecoder().getTypeClass());
        assertEquals(Properties.class, new PropertiesTypeEncoder().getTypeClass());
    }

    @Test
    public void testDescriptors() throws IOException {
        assertEquals(Properties.DESCRIPTOR_CODE, new PropertiesTypeDecoder().getDescriptorCode());
        assertEquals(Properties.DESCRIPTOR_CODE, new PropertiesTypeEncoder().getDescriptorCode());
        assertEquals(Properties.DESCRIPTOR_SYMBOL, new PropertiesTypeDecoder().getDescriptorSymbol());
        assertEquals(Properties.DESCRIPTOR_SYMBOL, new PropertiesTypeEncoder().getDescriptorSymbol());
    }

    @Test
    public void testDecodeSmallSeriesOfPropertiess() throws IOException {
        doTestDecodePropertiesSeries(SMALL_SIZE, false);
    }

    @Test
    public void testDecodeLargeSeriesOfPropertiess() throws IOException {
        doTestDecodePropertiesSeries(LARGE_SIZE, false);
    }

    @Test
    public void testDecodeSmallSeriesOfPropertiessFromStream() throws IOException {
        doTestDecodePropertiesSeries(SMALL_SIZE, true);
    }

    @Test
    public void testDecodeLargeSeriesOfPropertiessStream() throws IOException {
        doTestDecodePropertiesSeries(LARGE_SIZE, true);
    }

    private void doTestDecodePropertiesSeries(int size, boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);

        final Random random = new Random();
        random.setSeed(System.nanoTime());

        final int randomGroupSequence = random.nextInt();
        final int randomAbsoluteExpiry = random.nextInt();
        final int randomCreateTime = random.nextInt();

        final Properties properties = new Properties();

        properties.setMessageId("ID:Message-1:1:1:0");
        properties.setUserId(new Binary(new byte[1]));
        properties.setTo("queue:work");
        properties.setSubject("help");
        properties.setReplyTo("queue:temp:me");
        properties.setContentEncoding("text/UTF-8");
        properties.setContentType("text");
        properties.setCorrelationId("correlation-id");
        properties.setAbsoluteExpiryTime(randomAbsoluteExpiry);
        properties.setCreationTime(randomCreateTime);
        properties.setGroupId("group-1");
        properties.setGroupSequence(randomGroupSequence);
        properties.setReplyToGroupId("group-1");

        for (int i = 0; i < size; ++i) {
            encoder.writeObject(buffer, encoderState, properties);
        }

        for (int i = 0; i < size; ++i) {
            final Object result;
            if (fromStream) {
                result = streamDecoder.readObject(stream, streamDecoderState);
            } else {
                result = decoder.readObject(buffer, decoderState);
            }

            assertNotNull(result);
            assertTrue(result instanceof Properties);

            Properties decoded = (Properties) result;

            assertNotNull(decoded.getAbsoluteExpiryTime());
            assertEquals(Integer.toUnsignedLong(randomAbsoluteExpiry), decoded.getAbsoluteExpiryTime());
            assertEquals("text/UTF-8", decoded.getContentEncoding());
            assertEquals("text", decoded.getContentType());
            assertEquals("correlation-id", decoded.getCorrelationId());
            assertEquals(Integer.toUnsignedLong(randomCreateTime), decoded.getCreationTime());
            assertEquals("group-1", decoded.getGroupId());
            assertEquals(Integer.toUnsignedLong(randomGroupSequence), decoded.getGroupSequence());
            assertEquals("ID:Message-1:1:1:0", decoded.getMessageId());
            assertEquals("queue:temp:me", decoded.getReplyTo());
            assertEquals("group-1", decoded.getReplyToGroupId());
            assertEquals("help", decoded.getSubject());
            assertEquals("queue:work", decoded.getTo());
            assertTrue(decoded.getUserId() instanceof Binary);
        }
    }

    @Test
    public void testEncodeAndDecodeWithMaxUnsignedValuesFromLongs() throws IOException {
        doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(false);
    }

    @Test
    public void testEncodeAndDecodeWithMaxUnsignedValuesFromLongsFromStream() throws IOException {
        doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(true);
    }

    private void doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);
        final Properties properties = new Properties();

        properties.setAbsoluteExpiryTime(UnsignedInteger.MAX_VALUE.longValue());
        properties.setCreationTime(UnsignedInteger.MAX_VALUE.longValue());
        properties.setGroupSequence(UnsignedInteger.MAX_VALUE.longValue());

        encoder.writeObject(buffer, encoderState, properties);

        final Object result;
        if (fromStream) {
            result = streamDecoder.readObject(stream, streamDecoderState);
        } else {
            result = decoder.readObject(buffer, decoderState);
        }

        assertNotNull(result);
        assertTrue(result instanceof Properties);

        Properties decoded = (Properties) result;

        assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getAbsoluteExpiryTime());
        assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getCreationTime());
        assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getGroupSequence());
    }

    @Test
    public void testSkipValue() throws IOException {
        doTestSkipValue(false);
    }

    @Test
    public void testSkipValueFromStream() throws IOException {
        doTestSkipValue(true);
    }

    public void doTestSkipValue(boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);

        Properties properties = new Properties();
        properties.setAbsoluteExpiryTime(100);
        properties.setContentEncoding("UTF8");

        for (int i = 0; i < 10; ++i) {
            encoder.writeObject(buffer, encoderState, properties);
        }

        encoder.writeObject(buffer, encoderState, new Modified());

        for (int i = 0; i < 10; ++i) {
            if (fromStream) {
                StreamTypeDecoder<?> typeDecoder = streamDecoder.readNextTypeDecoder(stream, streamDecoderState);
                assertEquals(Properties.class, typeDecoder.getTypeClass());
                typeDecoder.skipValue(stream, streamDecoderState);
            } else {
                TypeDecoder<?> typeDecoder = decoder.readNextTypeDecoder(buffer, decoderState);
                assertEquals(Properties.class, typeDecoder.getTypeClass());
                typeDecoder.skipValue(buffer, decoderState);
            }
        }

        final Object result;
        if (fromStream) {
            result = streamDecoder.readObject(stream, streamDecoderState);
        } else {
            result = decoder.readObject(buffer, decoderState);
        }

        assertNotNull(result);
        assertTrue(result instanceof Modified);
        Modified modified = (Modified) result;
        assertFalse(modified.isUndeliverableHere());
        assertFalse(modified.isDeliveryFailed());
    }

    @Test
    public void testDecodeWithInvalidMap32Type() throws IOException {
        doTestDecodeWithInvalidMapType(EncodingCodes.MAP32, false);
    }

    @Test
    public void testDecodeWithInvalidMap8Type() throws IOException {
        doTestDecodeWithInvalidMapType(EncodingCodes.MAP8, false);
    }

    @Test
    public void testDecodeWithInvalidMap32TypeFromStream() throws IOException {
        doTestDecodeWithInvalidMapType(EncodingCodes.MAP32, true);
    }

    @Test
    public void testDecodeWithInvalidMap8TypeFromStream() throws IOException {
        doTestDecodeWithInvalidMapType(EncodingCodes.MAP8, true);
    }

    private void doTestDecodeWithInvalidMapType(byte mapType, boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);

        buffer.writeByte((byte) 0); // Described Type Indicator
        buffer.writeByte(EncodingCodes.SMALLULONG);
        buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
        if (mapType == EncodingCodes.MAP32) {
            buffer.writeByte(EncodingCodes.MAP32);
            buffer.writeInt((byte) 0);  // Size
            buffer.writeInt((byte) 0);  // Count
        } else {
            buffer.writeByte(EncodingCodes.MAP8);
            buffer.writeByte((byte) 0);  // Size
            buffer.writeByte((byte) 0);  // Count
        }

        if (fromStream) {
            try {
                streamDecoder.readObject(stream, streamDecoderState);
                fail("Should not decode type with invalid encoding");
            } catch (DecodeException ex) {}
        } else {
            try {
                decoder.readObject(buffer, decoderState);
                fail("Should not decode type with invalid encoding");
            } catch (DecodeException ex) {}
        }
    }

    @Test
    public void testSkipValueWithInvalidMap32Type() throws IOException {
        doTestSkipValueWithInvalidMapType(EncodingCodes.MAP32, false);
    }

    @Test
    public void testSkipValueWithInvalidMap8Type() throws IOException {
        doTestSkipValueWithInvalidMapType(EncodingCodes.MAP8, false);
    }

    @Test
    public void testSkipValueWithInvalidMap32TypeFromStream() throws IOException {
        doTestSkipValueWithInvalidMapType(EncodingCodes.MAP32, true);
    }

    @Test
    public void testSkipValueWithInvalidMap8TypeFromStream() throws IOException {
        doTestSkipValueWithInvalidMapType(EncodingCodes.MAP8, true);
    }

    private void doTestSkipValueWithInvalidMapType(byte mapType, boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);

        buffer.writeByte((byte) 0); // Described Type Indicator
        buffer.writeByte(EncodingCodes.SMALLULONG);
        buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
        if (mapType == EncodingCodes.MAP32) {
            buffer.writeByte(EncodingCodes.MAP32);
            buffer.writeInt((byte) 0);  // Size
            buffer.writeInt((byte) 0);  // Count
        } else {
            buffer.writeByte(EncodingCodes.MAP8);
            buffer.writeByte((byte) 0);  // Size
            buffer.writeByte((byte) 0);  // Count
        }

        if (fromStream) {
            StreamTypeDecoder<?> typeDecoder = streamDecoder.readNextTypeDecoder(stream, streamDecoderState);
            assertEquals(Properties.class, typeDecoder.getTypeClass());

            try {
                typeDecoder.skipValue(stream, streamDecoderState);
                fail("Should not be able to skip type with invalid encoding");
            } catch (DecodeException ex) {}
        } else {
            TypeDecoder<?> typeDecoder = decoder.readNextTypeDecoder(buffer, decoderState);
            assertEquals(Properties.class, typeDecoder.getTypeClass());

            try {
                typeDecoder.skipValue(buffer, decoderState);
                fail("Should not be able to skip type with invalid encoding");
            } catch (DecodeException ex) {}
        }
    }

    @Test
    public void testEncodeDecodeArray() throws IOException {
        doTestEncodeDecodeArray(false);
    }

    @Test
    public void testEncodeDecodeArrayFromStream() throws IOException {
        doTestEncodeDecodeArray(true);
    }

    private void doTestEncodeDecodeArray(boolean fromStream) throws IOException {
        final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        final InputStream stream = new ProtonBufferInputStream(buffer);

        Properties[] array = new Properties[3];

        array[0] = new Properties();
        array[1] = new Properties();
        array[2] = new Properties();

        array[0].setAbsoluteExpiryTime(1);
        array[1].setAbsoluteExpiryTime(2);
        array[2].setAbsoluteExpiryTime(3);

        encoder.writeObject(buffer, encoderState, array);

        final Object result;
        if (fromStream) {
            result = streamDecoder.readObject(stream, streamDecoderState);
        } else {
            result = decoder.readObject(buffer, decoderState);
        }

        assertTrue(result.getClass().isArray());
        assertEquals(Properties.class, result.getClass().getComponentType());

        Properties[] resultArray = (Properties[]) result;

        for (int i = 0; i < resultArray.length; ++i) {
            assertNotNull(resultArray[i]);
            assertTrue(resultArray[i] instanceof Properties);
            assertEquals(array[i].getAbsoluteExpiryTime(), resultArray[i].getAbsoluteExpiryTime());
        }
    }

    @Test
    public void testDecodeWithNotEnoughListEntriesList8() throws IOException {
        doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST8, false);
    }

    @Test
    public void testDecodeWithNotEnoughListEntriesList32() throws IOException {
        doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST32, false);
    }

    @Test
    public void testDecodeWithNotEnoughListEntriesList8FromStream() throws IOException {
        doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST8, true);
    }

    @Test
    public void testDecodeWithNotEnoughListEntriesList32FromStream() throws IOException {
        doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST32, true);
    }

    private void doTestDecodeWithNotEnoughListEntriesList32(byte listType, boolean fromStream) throws IOException {
        ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        InputStream stream = new ProtonBufferInputStream(buffer);

        buffer.writeByte((byte) 0); // Described Type Indicator
        buffer.writeByte(EncodingCodes.SMALLULONG);
        buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
        if (listType == EncodingCodes.LIST32) {
            buffer.writeByte(EncodingCodes.LIST32);
            buffer.writeInt(128);  // Size
            buffer.writeInt(-1);  // Count, reads as negative as encoder treats these as signed ints.
        } else if (listType == EncodingCodes.LIST8) {
            buffer.writeByte(EncodingCodes.LIST8);
            buffer.writeByte((byte) 128);  // Size
            buffer.writeByte((byte) 0xFF);  // Count
        }

        if (fromStream) {
            try {
                streamDecoder.readObject(stream, streamDecoderState);
                fail("Should not decode type with invalid min entries");
            } catch (DecodeException ex) {}
        } else {
            try {
                decoder.readObject(buffer, decoderState);
                fail("Should not decode type with invalid min entries");
            } catch (DecodeException ex) {}
        }
    }

    @Test
    public void testDecodeWithToManyListEntriesList8() throws IOException {
        doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST8, false);
    }

    @Test
    public void testDecodeWithToManyListEntriesList32() throws IOException {
        doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST32, false);
    }

    @Test
    public void testDecodeWithToManyListEntriesList8FromStream() throws IOException {
        doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST8, true);
    }

    @Test
    public void testDecodeWithToManyListEntriesList32FromStream() throws IOException {
        doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST32, true);
    }

    private void doTestDecodeWithToManyListEntriesList32(byte listType, boolean fromStream) throws IOException {
        ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
        InputStream stream = new ProtonBufferInputStream(buffer);

        buffer.writeByte((byte) 0); // Described Type Indicator
        buffer.writeByte(EncodingCodes.SMALLULONG);
        buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
        if (listType == EncodingCodes.LIST32) {
            buffer.writeByte(EncodingCodes.LIST32);
            buffer.writeInt(128);  // Size
            buffer.writeInt(127);  // Count
        } else if (listType == EncodingCodes.LIST8) {
            buffer.writeByte(EncodingCodes.LIST8);
            buffer.writeByte((byte) 128);  // Size
            buffer.writeByte((byte) 127);  // Count
        }

        if (fromStream) {
            try {
                streamDecoder.readObject(stream, streamDecoderState);
                fail("Should not decode type with invalid min entries");
            } catch (DecodeException ex) {}
        } else {
            try {
                decoder.readObject(buffer, decoderState);
                fail("Should not decode type with invalid min entries");
            } catch (DecodeException ex) {}
        }
    }
}


text:
<!DOCTYPE HTML>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="generator" content="JsDoc Toolkit" />
	<title>JsDoc Reference - $.fn.swipe.directions</title>

	<link media="all" rel="stylesheet" href="../css/common.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../css/prettify.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../css/bootstrap.min.css" type="text/css" />
	<link media="print" rel="stylesheet" href="../css/print.css" type="text/css" />

				JsDoc Reference

Class Index

File Index

Classes

$

fn

swipe

defaults

directions

fingers

pageScroll

phases

_global_

				$.fn.swipe.directions

Hierarchy

$.fn.swipe«

$.fn«

$«

directions

		Instance members

Namespace

							$.fn.swipe.directions

							Static

								The direction constants that are passed to the event handlers.
These properties are read only, attempting to change them will not alter the values passed to the event handlers.

									code »

Instance members

Instance PropertiesDefined By

									DOWN
									 : string

									$.fn.swipe.directions

											Constant indicating the down direction. Value is "cancel".
											code »

									IN
									 : string

									$.fn.swipe.directions

											Constant indicating the in direction. Value is "in".
											code »

									LEFT
									 : string

									$.fn.swipe.directions

											Constant indicating the left direction. Value is "left".
											code »

									OUT
									 : string

									$.fn.swipe.directions

											Constant indicating the out direction. Value is "out".
											code »

									RIGHT
									 : string

									$.fn.swipe.directions

											Constant indicating the right direction. Value is "right".
											code »

									UP
									 : string

									$.fn.swipe.directions

											Constant indicating the up direction. Value is "up".
											code »

Documentation generated by JsDoc Toolkit 2.4.0 on Wed Jun 04 2014 13:36:57 GMT+0100 (BST)


text:
package org.apache.camel.component.smpp;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.spi.ExceptionHandler;
import org.jsmpp.PDUStringException;
import org.jsmpp.bean.AlertNotification;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.extra.ProcessRequestException;
import org.jsmpp.session.DataSmResult;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.util.MessageIDGenerator;
import org.jsmpp.util.MessageId;
import org.junit.Before;
import org.junit.Test;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

public class MessageReceiverListenerImplTest {

    private MessageReceiverListenerImpl listener;
    private SmppEndpoint endpoint;
    private Processor processor;
    private ExceptionHandler exceptionHandler;

    @Before
    public void setUp() {
        endpoint = createMock(SmppEndpoint.class);
        processor = createMock(Processor.class);
        exceptionHandler = createMock(ExceptionHandler.class);

        listener = new MessageReceiverListenerImpl(endpoint, processor, exceptionHandler);
        listener.setMessageIDGenerator(new MessageIDGenerator() {
            public MessageId newMessageId() {
                try {
                    return new MessageId("1");
                } catch (PDUStringException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @Test
    public void onAcceptAlertNotificationSuccess() throws Exception {
        AlertNotification alertNotification = createMock(AlertNotification.class);
        Exchange exchange = createMock(Exchange.class);

        expect(endpoint.createOnAcceptAlertNotificationExchange(alertNotification))
            .andReturn(exchange);
        processor.process(exchange);

        replay(endpoint, processor, exceptionHandler, alertNotification, exchange);

        listener.onAcceptAlertNotification(alertNotification);

        verify(endpoint, processor, exceptionHandler, alertNotification, exchange);
    }

    @Test
    public void onAcceptAlertNotificationException() throws Exception {
        AlertNotification alertNotification = createMock(AlertNotification.class);
        Exchange exchange = createMock(Exchange.class);
        Exception exception = new Exception("forced exception for test");

        expect(endpoint.createOnAcceptAlertNotificationExchange(alertNotification))
            .andReturn(exchange);
        processor.process(exchange);
        expectLastCall().andThrow(exception);
        exceptionHandler.handleException(exception);

        replay(endpoint, processor, exceptionHandler, alertNotification, exchange);

        listener.onAcceptAlertNotification(alertNotification);

        verify(endpoint, processor, exceptionHandler, alertNotification, exchange);
    }

    @Test
    public void onAcceptDeliverSmSuccess() throws Exception {
        DeliverSm deliverSm = createMock(DeliverSm.class);
        Exchange exchange = createMock(Exchange.class);
        Exception exception = new Exception("forced exception for test");

        expect(endpoint.createOnAcceptDeliverSmExchange(deliverSm))
            .andReturn(exchange);
        processor.process(exchange);
        expectLastCall().andThrow(exception);
        exceptionHandler.handleException(exception);

        replay(endpoint, processor, exceptionHandler, deliverSm, exchange);

        listener.onAcceptDeliverSm(deliverSm);

        verify(endpoint, processor, exceptionHandler, deliverSm, exchange);
    }

    @Test
    public void onAcceptDeliverSmException() throws Exception {
        DeliverSm deliverSm = createMock(DeliverSm.class);
        Exchange exchange = createMock(Exchange.class);

        expect(endpoint.createOnAcceptDeliverSmExchange(deliverSm))
            .andReturn(exchange);
        processor.process(exchange);

        replay(endpoint, processor, exceptionHandler, deliverSm, exchange);

        listener.onAcceptDeliverSm(deliverSm);

        verify(endpoint, processor, exceptionHandler, deliverSm, exchange);
    }

    @Test
    public void onAcceptDeliverSmProcessRequestException() throws Exception {
        DeliverSm deliverSm = createMock(DeliverSm.class);
        Exchange exchange = createMock(Exchange.class);
        ProcessRequestException exception = new ProcessRequestException("forced exception for test", 100);

        expect(endpoint.createOnAcceptDeliverSmExchange(deliverSm))
            .andReturn(exchange);
        processor.process(exchange);
        expectLastCall().andThrow(exception);
        exceptionHandler.handleException(exception);

        replay(endpoint, processor, exceptionHandler, deliverSm, exchange);

        try {
            listener.onAcceptDeliverSm(deliverSm);
            fail("ProcessRequestException expected");
        } catch (ProcessRequestException e) {
            assertEquals(100, e.getErrorCode());
            assertEquals("forced exception for test", e.getMessage());
            assertNull(e.getCause());
        }

        verify(endpoint, processor, exceptionHandler, deliverSm, exchange);
    }

    @Test
    public void onAcceptDataSmSuccess() throws Exception {
        SMPPSession session = createMock(SMPPSession.class);
        DataSm dataSm = createMock(DataSm.class);
        Exchange exchange = createMock(Exchange.class);
        OptionalParameter[] optionalParameters = new OptionalParameter[]{};

        expect(endpoint.createOnAcceptDataSm(dataSm, "1"))
            .andReturn(exchange);
        processor.process(exchange);
        expect(dataSm.getOptionalParametes())
            .andReturn(optionalParameters);

        replay(endpoint, processor, exceptionHandler, session, dataSm, exchange);

        DataSmResult result = listener.onAcceptDataSm(dataSm, session);

        verify(endpoint, processor, exceptionHandler, session, dataSm, exchange);

        assertEquals("1", result.getMessageId());
        assertSame(optionalParameters, result.getOptionalParameters());
    }

    @Test
    public void onAcceptDataSmException() throws Exception {
        SMPPSession session = createMock(SMPPSession.class);
        DataSm dataSm = createMock(DataSm.class);
        Exchange exchange = createMock(Exchange.class);
        Exception exception = new Exception("forced exception for test");

        expect(endpoint.createOnAcceptDataSm(dataSm, "1"))
            .andReturn(exchange);
        processor.process(exchange);
        expectLastCall().andThrow(exception);
        exceptionHandler.handleException(exception);

        replay(endpoint, processor, exceptionHandler, session, dataSm, exchange);

        try {
            listener.onAcceptDataSm(dataSm, session);
            fail("ProcessRequestException expected");
        } catch (ProcessRequestException e) {
            assertEquals(255, e.getErrorCode());
            assertEquals("forced exception for test", e.getMessage());
            assertSame(exception, e.getCause());
        }

        verify(endpoint, processor, exceptionHandler, session, dataSm, exchange);
    }

    @Test
    public void onAcceptDataSmProcessRequestException() throws Exception {
        SMPPSession session = createMock(SMPPSession.class);
        DataSm dataSm = createMock(DataSm.class);
        Exchange exchange = createMock(Exchange.class);
        ProcessRequestException exception = new ProcessRequestException("forced exception for test", 100);

        expect(endpoint.createOnAcceptDataSm(dataSm, "1"))
            .andReturn(exchange);
        processor.process(exchange);
        expectLastCall().andThrow(exception);
        exceptionHandler.handleException(exception);

        replay(endpoint, processor, exceptionHandler, session, dataSm, exchange);

        try {
            listener.onAcceptDataSm(dataSm, session);
            fail("ProcessRequestException expected");
        } catch (ProcessRequestException e) {
            assertEquals(100, e.getErrorCode());
            assertEquals("forced exception for test", e.getMessage());
            assertNull(e.getCause());
        }

        verify(endpoint, processor, exceptionHandler, session, dataSm, exchange);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>7</version>
    </parent>

    <groupId>com.cronutils</groupId>
    <artifactId>cron-utils-spring</artifactId>
    <version>1.0.2-SNAPSHOT</version>

    <name>cron-utils-spring</name>
    <description>A Java library to describe cron expressions in human readable language at Spring framework</description>
    <url>http://cron-parser.com/</url>

    <licenses>
        <license>
            <name>Apache 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>jmrozanec</id>
            <url>https://github.com/jmrozanec</url>
        </developer>
    </developers>

    <issueManagement>
        <url>https://github.com/jmrozanec/cron-utils-spring/issues</url>
        <system>GitHub Issues</system>
    </issueManagement>

    <scm>
        <url>https://github.com/jmrozanec/cron-utils-spring</url>
        <connection>scm:git:git@github.com:jmrozanec/cron-utils-spring.git</connection>
        <developerConnection>scm:git:git@github.com:jmrozanec/cron-utils-spring.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

    <distributionManagement>
        <repository>
            <id>ossrh</id>
            <name>Release Repository</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
        <snapshotRepository>
            <id>ossrh</id>
            <name>Snapshots Repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>com.cronutils</groupId>
            <artifactId>cron-utils</artifactId>
            <version>9.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.9.RELEASE</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>2.5</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
                <version>2.5.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>1.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.1</version>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.2</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>2.5.3</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>clirr-maven-plugin</artifactId>
                <version>2.6.1</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>2.1</version>
            </plugin>

            <!--   Get code coverage reports!     -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <format>xml</format>
                </configuration>
            </plugin>
        </plugins>

        <extensions>
            <!-- Needed to deploy using Webdav -->
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav</artifactId>
                <version>1.0-beta-2</version>
            </extension>
        </extensions>
    </build>

    <profiles>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- Profile for TravisCI to handle coverage metrics, etc. -->
        <profile>
            <id>travis</id>
            <activation>
                <property>
                    <name>env.TRAVIS</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.eluder.coveralls</groupId>
                        <artifactId>coveralls-maven-plugin</artifactId>
                        <version>2.2.0</version>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
package nl.tno.idsa.tools;

/**
 * Very simple debug logger.
 */
public class DebugPrinter {
    private static boolean DEBUG = false;

    public static void println(String format, Object... args) {
        if (DEBUG) {
            System.out.println(String.format(format, args));
        }
    }

    public static void println(String x) {
        if (DEBUG) {
            System.out.println(x);
        }
    }
}


text:
set -e -u -x

## Variables -----------------------------------------------------------------

# Successerator: How many times do we try before failing
export MAX_RETRIES=${MAX_RETRIES:-"2"}

# tempest and testr options, default is to run tempest in serial
export TESTR_OPTS=${TESTR_OPTS:-''}

# Disable the python output buffering so that jenkins gets the output properly
export PYTHONUNBUFFERED=1

# Extra options to pass to the AIO bootstrap process
export BOOTSTRAP_OPTS=${BOOTSTRAP_OPTS:-''}

# Ensure the terminal type is set
export TERM=linux

# Store the clone repo root location
export OSA_CLONE_DIR="$(readlink -f $(dirname ${0})/..)"

# Set the role fetch mode to git-clone to avoid interactions
# with the Ansible galaxy API.
export ANSIBLE_ROLE_FETCH_MODE="git-clone"

# The directory in which the ansible logs will be placed
export ANSIBLE_LOG_DIR="/openstack/log/ansible-logging"

# Set the scenario to execute based on the first CLI parameter
export SCENARIO=${1:-"aio"}

# Set the action base on the second CLI parameter
# Actions available: [ 'deploy', 'upgrade' ]
export ACTION=${2:-"deploy"}

# Set the source branch for upgrade tests
# Be sure to change this whenever a new stable branch
# is created. The checkout must always be N-1.
export UPGRADE_SOURCE_BRANCH=${UPGRADE_SOURCE_BRANCH:-'stable/pike'}

## Change branch for Upgrades ------------------------------------------------
# If the action is to upgrade, then store the current SHA,
# checkout the source SHA before executing the greenfield
# deployment.
# This needs to be done before the first "source" to ensure
# the correct functions are used for the branch.
if [[ "${ACTION}" == "upgrade" ]]; then
    # Store the target SHA/branch
    export UPGRADE_TARGET_BRANCH=$(git rev-parse HEAD)

    # Now checkout the source SHA/branch
    git checkout origin/${UPGRADE_SOURCE_BRANCH}
fi

## Functions -----------------------------------------------------------------
info_block "Checking for required libraries." 2> /dev/null || source "${OSA_CLONE_DIR}/scripts/scripts-library.sh"

## Main ----------------------------------------------------------------------

# Set gate job exit traps, this is run regardless of exit state when the job finishes.
trap gate_job_exit_tasks EXIT

# Log some data about the instance and the rest of the system
log_instance_info

if [ "$GATE_EXIT_RUN_DSTAT" == true ]; then
  run_dstat
fi

# Get minimum disk size
DATA_DISK_MIN_SIZE="$((1024**3 * $(awk '/bootstrap_host_data_disk_min_size/{print $2}' "${OSA_CLONE_DIR}/tests/roles/bootstrap-host/defaults/main.yml") ))"

# Determine the largest secondary disk device that meets the minimum size
DATA_DISK_DEVICE=$(lsblk -brndo NAME,TYPE,RO,SIZE | awk '/d[b-z]+ disk 0/{ if ($4>m && $4>='$DATA_DISK_MIN_SIZE'){m=$4; d=$1}}; END{print d}')

# Only set the secondary disk device option if there is one
if [ -n "${DATA_DISK_DEVICE}" ]; then
  export BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS} bootstrap_host_data_disk_device=${DATA_DISK_DEVICE}"
fi

# Bootstrap Ansible
source "${OSA_CLONE_DIR}/scripts/bootstrap-ansible.sh"

# Install ARA and add it to the callback path provided by bootstrap-ansible.sh/openstack-ansible.rc
# This is added *here* instead of bootstrap-ansible so it's used for CI purposes only.
ARA_SRC_HOME="${HOME}/src/git.openstack.org/openstack/ara"
if [[ -d "${ARA_SRC_HOME}" ]]; then
  # This installs from a git checkout
  /opt/ansible-runtime/bin/pip install ${ARA_SRC_HOME} "${ANSIBLE_PACKAGE:-ansible}"
else
  # This installs from pypi
  /opt/ansible-runtime/bin/pip install ara "${ANSIBLE_PACKAGE:-ansible}"
fi
# Dynamically retrieve the location of the ARA callback so we are able to find
# it on both py2 and py3
ara_location=$(/opt/ansible-runtime/bin/python -c "import os,ara; print(os.path.dirname(ara.__file__))")
export ANSIBLE_CALLBACK_PLUGINS="/etc/ansible/roles/plugins/callback:${ara_location}/plugins/callbacks"

# Log some data about the instance and the rest of the system
log_instance_info

# Flush all the iptables rules set by openstack-infra
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

# Bootstrap an AIO
unset ANSIBLE_VARS_PLUGINS
unset HOST_VARS_PATH
unset GROUP_VARS_PATH

pushd "${OSA_CLONE_DIR}/tests"
  if [ -z "${BOOTSTRAP_OPTS}" ]; then
    /opt/ansible-runtime/bin/ansible-playbook bootstrap-aio.yml \
                     -i test-inventory.ini \
                     ${ANSIBLE_PARAMETERS}
  else
    /opt/ansible-runtime/bin/ansible-playbook bootstrap-aio.yml \
                     -i test-inventory.ini \
                     -e "${BOOTSTRAP_OPTS}" \
                     ${ANSIBLE_PARAMETERS}
  fi
popd

pushd "${OSA_CLONE_DIR}/playbooks"
  # Disable Ansible color output
  export ANSIBLE_NOCOLOR=1

  # Create ansible logging directory
  mkdir -p ${ANSIBLE_LOG_DIR}

  # Log some data about the instance and the rest of the system
  log_instance_info

  # First we gather facts about the hosts to populate the fact cache.
  # We can't gather the facts for all hosts yet because the containers
  # aren't built yet.
  ansible -m setup -a 'gather_subset=network,hardware,virtual' hosts 2>${ANSIBLE_LOG_DIR}/facts-hosts.log

  # Prepare the hosts
  export ANSIBLE_LOG_PATH="${ANSIBLE_LOG_DIR}/setup-hosts.log"
  openstack-ansible setup-hosts.yml -e osa_gather_facts=False

  # Log some data about the instance and the rest of the system
  log_instance_info

  # Once setup-hosts is complete, we should gather facts for everything
  # (now including containers) so that the fact cache is complete for the
  # remainder of the run.
  ansible -m setup -a 'gather_subset=network,hardware,virtual' all 1>${ANSIBLE_LOG_DIR}/facts-all.log

  # Prepare the infrastructure
  export ANSIBLE_LOG_PATH="${ANSIBLE_LOG_DIR}/setup-infrastructure.log"
  openstack-ansible setup-infrastructure.yml -e osa_gather_facts=False

  # Log some data about the instance and the rest of the system
  log_instance_info

  # Setup OpenStack
  export ANSIBLE_LOG_PATH="${ANSIBLE_LOG_DIR}/setup-openstack.log"
  openstack-ansible setup-openstack.yml -e osa_gather_facts=False

  # Log some data about the instance and the rest of the system
  log_instance_info

popd

# If the action is to upgrade, then checkout the original SHA for
# the checkout, and execute the upgrade.
if [[ "${ACTION}" == "upgrade" ]]; then

    # Checkout the original HEAD we started with
    git checkout ${UPGRADE_TARGET_BRANCH}

    # There is a protection in the run-upgrade script
    # to prevent people doing anything silly. We need
    # to bypass that for an automated test.
    export I_REALLY_KNOW_WHAT_I_AM_DOING=true

    # Unset environment variables used by the bootstrap-ansible
    # script to allow newer versions of Ansible and global
    # requirements to be installed.
    unset ANSIBLE_PACKAGE
    unset UPPER_CONSTRAINTS_FILE

    # Source the current scripts-library.sh functions
    source "${OSA_CLONE_DIR}/scripts/scripts-library.sh"

    # Kick off the data plane tester
    bash ${OSA_CLONE_DIR}/tests/data-plane-test.sh &> /var/log/data-plane-error.log &

    # Fetch script to execute API availability tests, then
    # background them while the upgrade runs.
    get_bowling_ball_tests
    start_bowling_ball_tests

    # To execute the upgrade script we need to provide
    # an affirmative response to the warning that the
    # upgrade is irreversable.
    echo 'YES' | bash "${OSA_CLONE_DIR}/scripts/run-upgrade.sh"

    # Terminate the API availability tests
    kill_bowling_ball_tests

    # Terminate the data plane tester
    rm -f /var/run/data-plane-test.socket

    # Wait 10s for the tests to complete
    sleep 10

    # Output the API availability test results
    print_bowling_ball_results

    # Check for any data plane failures, and fail if there are
    if ! egrep -q "^FAIL: 0$" /var/log/data-plane-test.log; then
        echo -e "\n\nFAIL: The L3 data plane check failed!\n\n"
        exit 1
    fi

    # Check for any disk access failures, and fail if there are
    if ! egrep -q "^FAIL: 0$" /var/log/disk-access-test.log; then
        echo -e "\n\nFAIL: The disk access data plane check failed!\n\n"
        exit 1
    fi

fi

exit_success


text:
/*jshint smarttabs:true */
(function (root, factory) {
	"use strict";
	if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like enviroments that support module.exports,
		// like Node.
		module.exports = factory();
	} else if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([],factory);
	} else {
		// Browser globals (root is window)
		root.getTLIdEncoderDecoder = factory();
	}
})(this, function () {

"use strict";
// Author: Matthew Forrester <matt_at_keyboardwritescode.com>
// Copyright: Matthew Forrester
// License: MIT/BSD-style

/**
 * # getTLIdEncoderDecoder()
 *
 * Generate time based local Id's which are guarenteed to be unique for that
 * particular constructor call.
 *
 * ## Parameters
 *
 * * **@param {Number} `epoch`** A timestamp, all unique Id's will use this as
 *	thier base time.
 * * **@param {Number} `uniqueLength`** Id's will be based on a timestamp and a
 *	extra sequence number if we happen to generate two Id's in the same
 *	millisecond. If you leave this at the default of 1, 32 unique Id's can be
 *	generated per millisecond (because it's a 32bit number represented in a
 *	string), I have found this to be sufficient, but you can increase this
 *	number if it is not.
 * * **@return {Object} `return`** The return value includes three seperate Functions,
 *	these are:
 * *   **@return {Function} `return.encode`** Encode now by default (or the
 *		first parameter) into an Id.
 * *   **@return {Function} `return.decode`** Decode an Id back into a
 *		timestamp (Id is the first parameter).
 * *   **@return {Function} `return.sort`** Compatible with Array.sort() and
 *		will soft based on the encode time / first parameter.
 *
 * ## Example
 *
 * ```javascript
 * // Use one character (32 bit number) to ensure uniqueness within a millisecond
 * var uniquenessPerMillisecond = 1;
 * // As close as possible (but lower) than the lowest date to give shorter Id's
 * var epoch = new Date(1970,0,1).getTime();
 *
 *
 * // Get the TLId Encoder / Decoder
 * var encoderDecoder = getTLIdEncoderDecoder(epoch,uniquenessPerMillisecond);
 *
 * // Encode a date into a unique string
 * var dates = [
 *   encoderDecoder.encode(),
 *   encoderDecoder.encode(new Date(1980,1,6).getTime()),
 *   encoderDecoder.encode(new Date(1981,3,15).getTime()),
 *   encoderDecoder.encode(new Date(1986,8,9).getTime()),
 *   encoderDecoder.encode(new Date(1983,10,3).getTime()),
 *   encoderDecoder.encode(new Date(1982,0,6).getTime()),
 *   encoderDecoder.encode()
 * ];
 *
 * // Get the dates it was encoded
 * var originalTimestamps = dates.map(encoderDecoder.decode);
 *
 * // Sort them in date order
 * var sortedDates = dates.sort(encoderDecoder.sort);*
 * console.log("The first Date is " + new Date(encoderDecoder.decode(sortedDates[0])));
 * ```
 */
return function(epoch,uniqueLength) {

  var lastDate = null;
  var index = -1;
  if (uniqueLength === undefined) {
	uniqueLength = 1;
  }

  if (typeof epoch != 'number') {
    throw "Only takes timestamps";
  }

  var genUid = function(now) {

    if (now === undefined) {
      now = new Date().getTime();
    }
	if (typeof now == 'object') {
      throw "Only takes timestamps";
	}

    if ((lastDate === null) || (now !== lastDate)) {
      index = -1;
    }

	var superUnique = (++index).toString(32);
	if (superUnique.length < uniqueLength) {
		superUnique = '0' + superUnique;
	}
	var timeEncoded = (now - epoch).toString(32);

	if (superUnique.length > uniqueLength) {
      throw "getUidGenerator.genUid cannot generate TLId until next millisecond!";
	}

    lastDate = now;
	if (timeEncoded.substr(0,1) <= '9') {
		return "X"+timeEncoded+superUnique;
	}
	return timeEncoded+superUnique;
  };

  var uidToTimestamp = function(tlid) {
	if (tlid.substr(0,1) == 'X') {
		tlid = tlid.substr(1);
	}
	tlid = tlid.substr(0, tlid.length - uniqueLength);
    return parseInt(tlid,32) + epoch;
  };

  var sort = function(tlidA, tlidB) {
	if (tlidA.substr(0,1) == 'X') {
		tlidA = tlidA.substr(1);
	}
	if (tlidB.substr(0,1) == 'X') {
		tlidB = tlidB.substr(1);
	}
	tlidA = tlidA.replace(/.*\./,'');
	tlidB = tlidB.replace(/.*\./,'');
	if (tlidA.length != tlidB.length) {
		return (tlidA.length < tlidB.length) ? -1 : 1;
	}
	return (tlidA < tlidB) ? -1 : 1;
  };

  return {encode: genUid, decode: uidToTimestamp, sort: sort};
};

});


text:
package org.elasticsearch.client.ml.job.config;

import org.elasticsearch.xcontent.ParseField;

import java.util.Locale;

/**
 * Enum representing logical comparisons on doubles
 */
public enum Operator {
    GT {
        @Override
        public boolean test(double lhs, double rhs) {
            return Double.compare(lhs, rhs) > 0;
        }
    },
    GTE {
        @Override
        public boolean test(double lhs, double rhs) {
            return Double.compare(lhs, rhs) >= 0;
        }
    },
    LT {
        @Override
        public boolean test(double lhs, double rhs) {
            return Double.compare(lhs, rhs) < 0;
        }
    },
    LTE {
        @Override
        public boolean test(double lhs, double rhs) {
            return Double.compare(lhs, rhs) <= 0;
        }
    };
    // EQ was considered but given the oddity of such a
    // condition and the fact that it would be a numerically
    // unstable condition, it was rejected.

    public static final ParseField OPERATOR_FIELD = new ParseField("operator");

    public boolean test(double lhs, double rhs) {
        return false;
    }

    public static Operator fromString(String name) {
        return valueOf(name.trim().toUpperCase(Locale.ROOT));
    }

    @Override
    public String toString() {
        return name().toLowerCase(Locale.ROOT);
    }
}


text:
@class NSString;

@protocol GTMLogFormatter <NSObject>
- (NSString *)stringForFunc:(NSString *)arg1 withFormat:(NSString *)arg2 valist:(char *)arg3 level:(int)arg4;
@end


text:
import pytest
import uuid
import shutil
import tempfile
import os
from boto3facade.ec2 import Ec2
from boto3facade.redshift import Redshift
from boto3facade.config import Config
from boto3facade.exceptions import InvalidConfiguration

@pytest.fixture
def config(scope='module'):
    return Ec2(active_profile='test').config

@pytest.yield_fixture
def dummyparam(config, scope='module'):
    yield 'dummyparam'
    config.config.remove_option('default', 'dummyparam')

@pytest.fixture
def custom_aws_config_dir(scope='module'):
    return tempfile.gettempdir()

@pytest.yield_fixture
def custom_aws_config_file(custom_aws_config_dir, scope='function'):
    filename = os.path.join(custom_aws_config_dir, str(uuid.uuid4()))
    yield filename
    if os.path.isfile(filename):
        os.remove(filename)

@pytest.fixture
def custom_profile(scope='module'):
    return 'test'

@pytest.fixture
def ec2_config(random_file_path, custom_profile, scope='module'):
    return Ec2(active_profile=custom_profile,
               config_file=random_file_path).config

@pytest.fixture
def vanilla_config(random_file_path, scope='module'):
    return Config(config_file=random_file_path)

@pytest.fixture
def custom_fallback(custom_keys, scope='module'):
    # Use a random fallback for the first two keys
    keys = custom_keys[:2]
    return {keys[0]: str(uuid.uuid4()), keys[1]: str(uuid.uuid4())}

@pytest.fixture
def custom_env_prefix(scope='module'):
    return str(uuid.uuid4()).replace('-', '') + '_'

def test_read_config(config):
    """Sets value for an existing configuration option"""
    profile_name = config.get('default', 'profile')
    assert profile_name == 'default'

def test_write_config(config, dummyparam):
    dummyvalue = str(uuid.uuid4())
    config.set('default', dummyparam, dummyvalue)
    config.save()
    config.load()
    assert config.get('default', dummyparam) == dummyvalue

def test_read_ec2_config(ec2_config, random_file_path):
    """Reads a parameter from a custom config file"""
    profile_name = ec2_config.get('default', 'profile')
    assert profile_name == 'default'
    assert ec2_config.config_file == random_file_path
    assert os.path.isfile(random_file_path)

def test_write_config_in_ec2_config(ec2_config, dummyparam, config):
    dummyvalue = str(uuid.uuid4())
    ec2_config.set('default', dummyparam, dummyvalue)
    ec2_config.save()
    ec2_config.load()
    assert ec2_config.get('default', dummyparam) == dummyvalue
    assert config.config_file != ec2_config.config_file
    config.load()
    assert config.get('default', dummyparam) != dummyvalue

def test_constructor_ifc(custom_env_prefix, custom_profile, custom_keys,
                         custom_fallback, random_file_path):

    config = Config(
        env_prefix=custom_env_prefix,
        config_file=random_file_path,
        active_profile=custom_profile,
        keys=custom_keys,
        required_keys=custom_keys,
        fallback=custom_fallback)
    assert config.env_prefix == custom_env_prefix
    assert config.config_file == random_file_path
    assert config.active_profile == custom_profile
    assert config.keys == custom_keys
    assert config.required_keys == custom_keys
    assert config.fallback == custom_fallback

def test_invalid_configuration(blank_config):
    with pytest.raises(InvalidConfiguration):
        blank_config.configure(ask=False)

def test_configure_with_envvars(blank_config):
    # If the fixture ran without errors then we are already good
    pass

def test_configure_local_file(configured_config, monkeypatch):
    # Create a fake home dir
    dirpath = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
    os.mkdir(dirpath)
    monkeypatch.setattr(os.path, 'curdir', dirpath)
    orig_file = configured_config.config_file
    configured_config.configure(ask=False, local=True)
    assert orig_file != configured_config.config_file
    assert os.path.dirname(configured_config.config_file) == dirpath
    orig_basename = os.path.basename(orig_file)
    assert os.path.basename(configured_config.config_file) == orig_basename
    # cleanup
    shutil.rmtree(dirpath)

def test_configure_new_local_profile(configured_config, monkeypatch):
    # Create a fake home dir
    dirpath = os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))
    os.mkdir(dirpath)
    monkeypatch.setattr(os.path, 'curdir', dirpath)
    orig_file = configured_config.config_file
    profile_name = str(uuid.uuid4())
    configured_config.activate_profile(profile_name)
    configured_config.configure(ask=False, local=True)
    assert orig_file != configured_config.config_file
    assert os.path.dirname(configured_config.config_file) == dirpath
    orig_basename = os.path.basename(orig_file)
    assert os.path.basename(configured_config.config_file) == orig_basename
    # cleanup
    shutil.rmtree(dirpath)

def test_constructor_with_config_object(vanilla_config):
    rs = Redshift(config=vanilla_config)
    assert rs.config.config_file == vanilla_config.config_file