text:
var gulp = require('gulp'),
    del = require('del'),
    header = require('gulp-header'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglifyjs'),
    using = require('gulp-using')
    date = require('moment'),
    gzip = require('gulp-gzip'),
    karma = require('karma').server,
    webserver = require('gulp-webserver'),
    protractor = require('gulp-protractor').protractor,
    webdriver_update = require('gulp-protractor').webdriver_update,
    exit = require('gulp-exit'),
    preprocess = require('gulp-preprocess'),
    runSequence = require('run-sequence');

var paths = {
    baseDir: 'src',
    distDir: 'dist',
    tempDir: 'tmp',
    e2e: 'tests/e2e',
    ''
    ].join('\n');

gulp.task('clean', function (cb) {
    del([paths.distDir, paths.tempDir], cb);
});

gulp.task('concat', function () {
    return gulp.src([
        'build/module.prefix',
        paths.baseDir + '/localization*.js',
        'build/module.suffix'
    ])
        .pipe(concat('angular-localization.js'))
        .pipe(header(banner, { pkg : pkg } ))
        .pipe(gulp.dest(paths.distDir))
});

gulp.task('uglify', function () {
    return gulp.src(paths.distDir + '/angular-localization.js')
        .pipe(uglify('angular-localization.min.js', {
            outSourceMap: 'angular-localization.min.map',
            basePath: 'dist/',
            output: {
                comments: /Copyright/
            }
        }))
        .pipe(gulp.dest(paths.distDir))
});

gulp.task('compress', function () {
    return gulp.src(paths.distDir + '/*.min.js')
        .pipe(gzip())
        .pipe(gulp.dest(paths.distDir))
});

gulp.task('karma', function (cb) {
    karma.start({
        configFile: __dirname + '/build/karma.conf.js'
    }, cb);
});

// use this helper task to update webdriver to the latest version
gulp.task('webdriver-update', webdriver_update);

gulp.task('connect', function () {
    gulp.src('.')
        .pipe(webserver({
            port: 9001
        }));
});

gulp.task('preprocess', function () {
    return gulp.src(paths.distDir + '/angular-localization.js')
        .pipe(preprocess({
            context: { VERSION: pkg.version }
        }))
        .pipe(gulp.dest(paths.distDir));
});

gulp.task('protractor', ['webdriver-update', 'connect'], function () {
    gulp.src(paths.e2e)
        .pipe((protractor({
            configFile: 'build/protractor.conf.js'
        })).on('error', function (e) {
            throw e;
        }))
        .pipe(exit());
});

gulp.task('build', function () {
    runSequence('clean', 'concat', 'preprocess', 'uglify', 'compress');
});

gulp.task('test', ['karma']);


text:
package perftest

import (
	"net/http"
	"strings"

	"github.com/jabong/florest-core/src/core/service"
	"github.com/jabong/florest-core/src/test/api"
	testService "github.com/jabong/florest-core/src/test/servicetest"
	"github.com/julienschmidt/httprouter"
)

type route struct {
	method string
	path   string
}

type mockResponseWriter struct{}

func (m *mockResponseWriter) Header() (h http.Header) {
	return http.Header{}
}

func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
	return len(p), nil
}

func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
	return len(s), nil
}

func (m *mockResponseWriter) WriteHeader(int) {}

func httpHandlerFunc(w http.ResponseWriter, r *http.Request) {}

func httpRouterHandle(_ http.ResponseWriter, _ *http.Request, _ httprouter.Params) {}

func loadHTTPServeMux(routes []route) http.Handler {
	serveMux := http.NewServeMux()
	for _, route := range routes {
		serveMux.HandleFunc(route.path, httpHandlerFunc)
	}
	return serveMux
}

func loadFlorestSingle(action string, version string, resource string, path string) {
	testAPI := new(api.TestAPI)
	testAPI.SetVersion(action, version, resource, path)
	service.RegisterAPI(testAPI)
	testService.InitializeTestService()
}

func loadFlorest(version string, resource string, routes []route) {
	for _, route := range routes {
		testAPI := new(api.TestAPI)
		testAPI.SetVersion(route.method, version, resource, route.path[1:])
		service.RegisterAPI(testAPI)
	}
	testService.InitializeTestService()
}

func convertColonToBraces(routes []route) []route {
	result := make([]route, len(routes))

	for index, oldRoute := range routes {
		path := oldRoute.path[1:]
		pathArr := strings.Split(path, "/")
		convertedPath := ""
		for _, pathParam := range pathArr {
			if strings.Index(pathParam, ":") == 0 {
				pathParam = "{" + pathParam[1:] + "}"
			}
			convertedPath = convertedPath + "/" + pathParam
		}
		newRoute := new(route)
		newRoute.path = convertedPath
		newRoute.method = oldRoute.method
		result[index] = *newRoute
	}

	return result
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Application\Web\Admin\QueryString;

abstract class BaseQS
{
    /**
     * @var array
     */
    public $params = array();

    /**
     * @param array $except
     * @param array $extra
     * @return string
     */
    public function createQueryString(array $except = array(), array $extra = array())
    {
        $params = array();
        foreach ($this->params as $key => $value) {
            if (!in_array($key, $except)) {
                $params[$key] = $value;
            }
        }

        $params = array_merge($params, $extra);
        return http_build_query($params);
    }
}


text:
Info
====

.. doxygenfunction:: GSM_GetNetworkName
.. doxygenfunction:: GSM_GetCountryName
.. doxygenfunction:: GSM_FeatureToString
.. doxygenfunction:: GSM_FeatureFromString
.. doxygenfunction:: GSM_IsPhoneFeatureAvailable
.. doxygenfunction:: GSM_AddPhoneFeature
.. doxygenfunction:: GSM_GetManufacturer
.. doxygenfunction:: GSM_GetModel
.. doxygenfunction:: GSM_GetModelInfo
.. doxygenfunction:: GSM_GetFirmware
.. doxygenfunction:: GSM_GetIMEI
.. doxygenfunction:: GSM_GetOriginalIMEI
.. doxygenfunction:: GSM_GetManufactureMonth
.. doxygenfunction:: GSM_GetProductCode
.. doxygenfunction:: GSM_GetHardware
.. doxygenfunction:: GSM_GetPPM
.. doxygenfunction:: GSM_GetSIMIMSI
.. doxygenfunction:: GSM_GetBatteryCharge
.. doxygenfunction:: GSM_GetSignalQuality
.. doxygenfunction:: GSM_GetNetworkInfo
.. doxygenfunction:: GSM_GetDisplayStatus
.. doxygenenum:: GSM_NetworkInfo_State
.. doxygenenum:: GSM_GPRS_State
.. doxygenstruct:: GSM_NetworkInfo
.. doxygenstruct:: GSM_SignalQuality
.. doxygenenum:: GSM_ChargeState
.. doxygenenum:: GSM_BatteryType
.. doxygenstruct:: GSM_BatteryCharge
.. doxygenenum:: GSM_DisplayFeature
.. doxygenstruct:: GSM_DisplayFeatures
.. doxygenenum:: GSM_Feature
.. doxygenstruct:: GSM_PhoneModel


text:
<?php

/**
 * This file is part of the FOSCommentBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace FOS\CommentBundle\SpamDetection;

use FOS\CommentBundle\Model\CommentInterface;
use Ornicar\AkismetBundle\Akismet\AkismetInterface;

/**
 * Detects spam by querying the Akismet service.
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 */
class AkismetSpamDetection implements SpamDetectionInterface
{
    /**
     * @var AkismetInterface
     */
    protected $akismet;

    /**
     * @param AkismetInterface $akismet
     */
    public function __construct(AkismetInterface $akismet)
    {
        $this->akismet = $akismet;
    }

    /**
     * Returns true if Akismet believes the comment to be spam.
     *
     * @param  CommentInterface $comment
     * @return bool
     */
    public function isSpam(CommentInterface $comment)
    {
        return $this->akismet->isSpam($this->getCommentData($comment));
    }

    /**
     * Compiles comment data into a format Akismet accepts.
     *
     * @param  CommentInterface $comment
     * @return array
     */
    protected function getCommentData(CommentInterface $comment)
    {
        $data = array(
            'comment_type'    => 'comment',
            'comment_content' => $comment->getBody()
        );

        $data['comment_author'] = $comment->getAuthorName();

        return $data;
    }
}


text:
'''
Code for cifar10_v1 network, and visualizing filters.
'''

from __future__ import print_function
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD, adadelta, rmsprop
from keras.layers.normalization import BatchNormalization
from keras.utils import np_utils
import cPickle
import numpy as np

def cifar(weights='MODS_keras_weights_3_he_normal_0.5_rmsprop_24.h5'):

	nb_classes = 2

	#Hyperparameters for tuning
	weight_init = 'he_normal'
	dropout = 0.5

	# input image dimensions
	img_rows, img_cols = 256, 192

	# my images are images are greyscale
	img_channels = 1

	model = Sequential()

	model.add(Convolution2D(128, 3, 3,
		                input_shape=(img_channels, img_rows, img_cols), init=weight_init, name='conv1_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(128, 3, 3,init=weight_init, name='conv1_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(256, 3, 3,init=weight_init, name='conv2_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(256, 3, 3,init=weight_init, name='conv2_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(256, 3, 3,init=weight_init, name='conv2_3'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(512, 3, 3, init=weight_init, name='conv3_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(512, 3, 3, init=weight_init, name='conv3_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Convolution2D(1024, 3,3,border_mode='same',init=weight_init, name='conv4_1'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(Convolution2D(1024, 3,3,border_mode='same',init=weight_init, name='conv4_2'))
	model.add(BatchNormalization())
	model.add(Activation('relu'))
	model.add(MaxPooling2D(pool_size=(2, 2)))
	model.add(Dropout(dropout))

	model.add(Flatten())
	model.add(Dense(120,init=weight_init))
	model.add(Activation('relu'))
	model.add(Dropout(dropout))

	model.add(Dropout(dropout))
	model.add(Dense(nb_classes))
	#model.add(Activation('softmax'))
	model.add(Activation('sigmoid'))

	model.load_weights(weights)

	return model


text:
<?php

namespace Magento\Framework\Api;

/**
 * Custom Attribute Data object builder
 */
class AttributeDataBuilder extends AbstractSimpleObjectBuilder
{
    /**
     * Set attribute code
     *
     * @param string $attributeCode
     * @return $this
     */
    public function setAttributeCode($attributeCode)
    {
        return $this->_set(AttributeValue::ATTRIBUTE_CODE, $attributeCode);
    }

    /**
     * Set attribute value
     *
     * @param string $value
     * @return $this
     */
    public function setValue($value)
    {
        return $this->_set(AttributeValue::VALUE, $value);
    }

    /**
     * Return the Data type class name
     *
     * @return string
     */
    protected function _getDataObjectType()
    {
        return '\Magento\Framework\Api\AttributeValue';
    }
}


text:
<!doctype html>
<title>Hello from Flask</title>
{% for file_ in files %}

{% endfor %}


text:
import os
from collections import OrderedDict

import sys
from django.conf import settings
from django.apps import apps
from django.conf.urls import url, include

class DefaultModelSerializer(object):
    def __init__(self, name='REST API', description=''):
        self.name = name
        self.description = description

    def generate_root(self, request):

        from rest_framework.reverse import reverse
        from rest_framework.response import Response
        from rest_framework.decorators import api_view

        index = OrderedDict((
            ('Auth', OrderedDict((
                ('Получение токена по логину/паролю', reverse('get_token', request=request)),
                ('Обновление токена', reverse('refresh_token', request=request)),
                ('Проверка токена', reverse('check_token', request=request)),
            ))),
        ))
        project_apps = settings.PROJECT_APPS
        for app_name in project_apps:
            index[app_name.capitalize()] = {}
            models = dict(apps.all_models[app_name])
            for name, model in models.items():
                model_dict = {}
                from rest_framework.reverse import reverse_lazy
                model_dict[name] = reverse_lazy('api:{}-list'.format(name.lower()), request=request)
                index[app_name.capitalize()].update(model_dict)

        def root_view(request):
            return Response(index)

        root_view.__name__ = self.name
        root_view.__doc__ = self.description

        return api_view(['GET'])(root_view)(request)

    def register_models(self):
        from .models import RestModel
        from rest_framework.routers import SimpleRouter
        router = SimpleRouter()
        for app_name in settings.PROJECT_APPS:
            models = dict(apps.all_models[app_name]).values()
            for model in models:
                if RestModel in model.__bases__:
                    router.register(*model._rest_endpoint())

        return router

    def urls(self):
        ROOT_ROUTE = getattr(settings, 'API_ENDPOINT', 'api')
        return [
            url(r'^{root_route}$'.format(root_route=ROOT_ROUTE), self.generate_root),
            url(r'^{root_route}/'.format(root_route=ROOT_ROUTE), include(self.register_models().urls, namespace='api')),
        ]

class APIManager(object):
    def __init__(self, root, settings):
        self.root = os.path.abspath(os.path.dirname(root))
        self.settings = settings

    def apply(self):
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api_tools.settings")
        os.environ.setdefault('API_ROOT', self.root)
        os.environ.setdefault('PROJECT_SETTINGS', self.settings)

    def set_app_dir(self, path):
        sys.path.insert(0, os.path.join(self.root, path))


text:
<?php

if(!defined('INCLUDE_DIR')) die('403');

include_once(INCLUDE_DIR.'class.ticket.php');
require_once(INCLUDE_DIR.'class.ajax.php');
require_once(INCLUDE_DIR.'class.note.php');
include_once INCLUDE_DIR . 'class.thread_actions.php';

class TicketsAjaxAPI extends AjaxController {

    function lookup() {
        global $thisstaff;

        $limit = isset($_REQUEST['limit']) ? (int) $_REQUEST['limit']:25;
        $tickets=array();
        // Bail out of query is empty
        if (!$_REQUEST['q'])
            return $this->json_encode($tickets);

        $visibility = Q::any(array(
            'staff_id' => $thisstaff->getId(),
            'team_id__in' => $thisstaff->teams->values_flat('team_id'),
        ));

        if (!$thisstaff->showAssignedOnly() && ($depts=$thisstaff->getDepts())) {
            $visibility->add(array('dept_id__in' => $depts));
        }

        $hits = TicketModel::objects()
            ->filter($visibility)
            ->values('user__default_email__address')
            ->annotate(array(
                'number' => new SqlCode('null'),
                'tickets' => SqlAggregate::COUNT('ticket_id', true)))
            ->limit($limit);

        $q = $_REQUEST['q'];

        if (strlen($q) < 3)
            return $this->encode(array());

        global $ost;
        $hits = $ost->searcher->find($q, $hits)
            ->order_by(new SqlCode('__relevance__'), QuerySet::DESC);

        if (preg_match('/\d{2,}[^*]/', $q, $T = array())) {
            $hits = TicketModel::objects()
                ->values('user__default_email__address', 'number')
                ->annotate(array(
                    'tickets' => new SqlCode('1'),
                    '__relevance__' => new SqlCode(1)
                ))
                ->filter($visibility)
                ->filter(array('number__startswith' => $q))
                ->limit($limit)
                ->union($hits);
        }
        elseif (!count($hits) && preg_match('`\w$`u', $q)) {
            // Do wild-card fulltext search
            $_REQUEST['q'] = $q.'*';
            return $this->lookup();
        }

        foreach ($hits as $T) {
            $email = $T['user__default_email__address'];
            $count = $T['tickets'];
            if ($T['number']) {
                $tickets[] = array('id'=>$T['number'], 'value'=>$T['number'],
                    'info'=>"{$T['number']} — {$email}",
                    'matches'=>$_REQUEST['q']);
            }
            else {
                $tickets[] = array('email'=>$email, 'value'=>$email,
                    'info'=>"$email ($count)", 'matches'=>$_REQUEST['q']);
            }
        }

        return $this->json_encode($tickets);
    }

    function acquireLock($tid) {
        global $cfg, $thisstaff;

        if(!$cfg || !$cfg->getLockTime() || $cfg->getTicketLockMode() == Lock::MODE_DISABLED)
            Http::response(418, $this->encode(array('id'=>0, 'retry'=>false)));

        if(!$tid || !is_numeric($tid) || !$thisstaff)
            return 0;

        if (!($ticket = Ticket::lookup($tid)) || !$ticket->checkStaffPerm($thisstaff))
            return $this->encode(array('id'=>0, 'retry'=>false, 'msg'=>__('Lock denied!')));

        //is the ticket already locked?
        if ($ticket->isLocked() && ($lock=$ticket->getLock()) && !$lock->isExpired()) {
            /*Note: Ticket->acquireLock does the same logic...but we need it here since we need to know who owns the lock up front*/
            //Ticket is locked by someone else.??
            if ($lock->getStaffId() != $thisstaff->getId())
                return $this->json_encode(array('id'=>0, 'retry'=>false,
                    'msg' => sprintf(__('Currently locked by %s'),
                        $lock->getStaff()->getAvatarAndName())
                    ));

            //Ticket already locked by staff...try renewing it.
            $lock->renew(); //New clock baby!
        } elseif(!($lock=$ticket->acquireLock($thisstaff->getId(),$cfg->getLockTime()))) {
            //unable to obtain the lock..for some really weired reason!
            //Client should watch for possible loop on retries. Max attempts?
            return $this->json_encode(array('id'=>0, 'retry'=>true));
        }

        return $this->json_encode(array(
            'id'=>$lock->getId(), 'time'=>$lock->getTime(),
            'code' => $lock->getCode()
        ));
    }

    function renewLock($id, $ticketId) {
        global $thisstaff;

        if (!$id || !is_numeric($id) || !$thisstaff)
            Http::response(403, $this->encode(array('id'=>0, 'retry'=>false)));
        if (!($lock = Lock::lookup($id)))
            Http::response(404, $this->encode(array('id'=>0, 'retry'=>'acquire')));
        if (!($ticket = Ticket::lookup($ticketId)) || $ticket->lock_id != $lock->lock_id)
            // Ticket / Lock mismatch
            Http::response(400, $this->encode(array('id'=>0, 'retry'=>false)));

        if (!$lock->getStaffId() || $lock->isExpired())
            // Said lock doesn't exist or is is expired — fetch a new lock
            return self::acquireLock($ticket->getId());

        if ($lock->getStaffId() != $thisstaff->getId())
            // user doesn't own the lock anymore??? sorry...try to next time.
            Http::response(403, $this->encode(array('id'=>0, 'retry'=>false,
                'msg' => sprintf(__('Currently locked by %s'),
                    $lock->getStaff->getAvatarAndName())
            ))); //Give up...

        // Ensure staff still has access
        if (!$ticket->checkStaffPerm($thisstaff))
            Http::response(403, $this->encode(array('id'=>0, 'retry'=>false,
                'msg' => sprintf(__('You no longer have access to #%s.'),
                $ticket->getNumber())
            )));

        // Renew the lock.
        // Failure here is not an issue since the lock is not expired yet.. client need to check time!
        $lock->renew();

        return $this->encode(array('id'=>$lock->getId(), 'time'=>$lock->getTime(),
            'code' => $lock->getCode()));
    }

    function releaseLock($id) {
        global $thisstaff;

        if (!$id || !is_numeric($id) || !$thisstaff)
            Http::response(403, $this->encode(array('id'=>0, 'retry'=>true)));
        if (!($lock = Lock::lookup($id)))
            Http::response(404, $this->encode(array('id'=>0, 'retry'=>true)));

        // You have to own the lock
        if ($lock->getStaffId() != $thisstaff->getId()) {
            return 0;
        }
        // Can't be expired
        if ($lock->isExpired()) {
            return 1;
        }
        return $lock->release() ? 1 : 0;
    }

    function previewTicket ($tid) {
        global $thisstaff;

        if(!$thisstaff || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, __('No such ticket'));

        include STAFFINC_DIR . 'templates/ticket-preview.tmpl.php';
    }

    function viewUser($tid) {
        global $thisstaff;

        if(!$thisstaff
                || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'No such ticket');

        if(!($user = User::lookup($ticket->getOwnerId())))
            Http::response(404, 'Unknown user');

        $info = array(
            'title' => sprintf(__('Ticket #%s: %s'), $ticket->getNumber(),
                Format::htmlchars($user->getName()))
            );

        ob_start();
        include(STAFFINC_DIR . 'templates/user.tmpl.php');
        $resp = ob_get_contents();
        ob_end_clean();
        return $resp;

    }

    function updateUser($tid) {

        global $thisstaff;

        if(!$thisstaff
                || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff)
                || !($user = User::lookup($ticket->getOwnerId())))
            Http::response(404, 'No such ticket/user');

        $errors = array();
        if($user->updateInfo($_POST, $errors, true))
             Http::response(201, $user->to_json());

        $forms = $user->getForms();

        $info = array(
            'title' => sprintf(__('Ticket #%s: %s'), $ticket->getNumber(),
                Format::htmlchars($user->getName()))
            );

        ob_start();
        include(STAFFINC_DIR . 'templates/user.tmpl.php');
        $resp = ob_get_contents();
        ob_end_clean();
        return $resp;
    }

    function changeUserForm($tid) {
        global $thisstaff;

        if(!$thisstaff
                || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'No such ticket');

        $user = User::lookup($ticket->getOwnerId());

        $info = array(
                'title' => sprintf(__('Change user for ticket #%s'), $ticket->getNumber())
                );

        return self::_userlookup($user, null, $info);
    }

    function _userlookup($user, $form, $info) {
        global $thisstaff;

        ob_start();
        include(STAFFINC_DIR . 'templates/user-lookup.tmpl.php');
        $resp = ob_get_contents();
        ob_end_clean();
        return $resp;

    }

    function manageForms($ticket_id) {
        global $thisstaff;

        if (!$thisstaff)
            Http::response(403, "Login required");
        elseif (!($ticket = Ticket::lookup($ticket_id)))
            Http::response(404, "No such ticket");
        elseif (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_EDIT))
            Http::response(403, "Access Denied");

        $forms = DynamicFormEntry::forTicket($ticket->getId());
        $info = array('action' => '#tickets/'.$ticket->getId().'/forms/manage');
        include(STAFFINC_DIR . 'templates/form-manage.tmpl.php');
    }

    function updateForms($ticket_id) {
        global $thisstaff;

        if (!$thisstaff)
            Http::response(403, "Login required");
        elseif (!($ticket = Ticket::lookup($ticket_id)))
            Http::response(404, "No such ticket");
        elseif (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_EDIT))
            Http::response(403, "Access Denied");
        elseif (!isset($_POST['forms']))
            Http::response(422, "Send updated forms list");

        // Add new forms
        $forms = DynamicFormEntry::forTicket($ticket_id);
        foreach ($_POST['forms'] as $sort => $id) {
            $found = false;
            foreach ($forms as $e) {
                if ($e->get('form_id') == $id) {
                    $e->set('sort', $sort);
                    $e->save();
                    $found = true;
                    break;
                }
            }
            // New form added
            if (!$found && ($new = DynamicForm::lookup($id))) {
                $f = $new->instanciate();
                $f->set('sort', $sort);
                $f->setTicketId($ticket_id);
                $f->save();
            }
        }

        // Deleted forms
        foreach ($forms as $idx => $e) {
            if (!in_array($e->get('form_id'), $_POST['forms']))
                $e->delete();
        }

        Http::response(201, 'Successfully managed');
    }

    function cannedResponse($tid, $cid, $format='text') {
        global $thisstaff, $cfg;

        if (!($ticket = Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown ticket ID');

        if ($cid && !is_numeric($cid)) {
            if (!($response=$ticket->getThread()->getVar($cid)))
                Http::response(422, 'Unknown ticket variable');

            // Ticket thread variables are assumed to be quotes
            $response = "

{$response->asVar()}

";

            //  Return text if html thread is not enabled
            if (!$cfg->isRichTextEnabled())
                $response = Format::html2text($response, 90);
            else
                $response = Format::viewableImages($response);

            // XXX: assuming json format for now.
            return Format::json_encode(array('response' => $response));
        }

        if (!$cfg->isRichTextEnabled())
            $format.='.plain';

        $varReplacer = function (&$var) use($ticket) {
            return $ticket->replaceVars($var);
        };

        include_once(INCLUDE_DIR.'class.canned.php');
        if (!$cid || !($canned=Canned::lookup($cid)) || !$canned->isEnabled())
            Http::response(404, 'No such premade reply');

        return $canned->getFormattedResponse($format, $varReplacer);
    }

    function transfer($tid) {
        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid)))
            Http::response(404, __('No such ticket'));

        if (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_TRANSFER))
            Http::response(403, __('Permission denied'));

        $errors = array();

        $info = array(
                ':title' => sprintf(__('Ticket #%s: %s'),
                    $ticket->getNumber(),
                    __('Transfer')),
                ':action' => sprintf('#tickets/%d/transfer',
                    $ticket->getId())
                );

        $form = $ticket->getTransferForm($_POST);
        if ($_POST && $form->isValid()) {
            if ($ticket->transfer($form, $errors)) {
                $_SESSION['::sysmsgs']['msg'] = sprintf(
                        __('%s successfully'),
                        sprintf(
                            __('%s transferred to %s department'),
                            __('Ticket'),
                            $ticket->getDept()
                            )
                        );
                Http::response(201, $ticket->getId());
            }

            $form->addErrors($errors);
            $info['error'] = $errors['err'] ?: __('Unable to transfer ticket');
        }

        $info['dept_id'] = $info['dept_id'] ?: $ticket->getDeptId();

        include STAFFINC_DIR . 'templates/transfer.tmpl.php';
    }

    function assign($tid, $target=null) {
        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid)))
            Http::response(404, __('No such ticket'));

        if (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_ASSIGN)
                || !($form = $ticket->getAssignmentForm($_POST,
                        array('target' => $target))))
            Http::response(403, __('Permission denied'));

        $errors = array();
        $info = array(
                ':title' => sprintf(__('Ticket #%s: %s'),
                    $ticket->getNumber(),
                    sprintf('%s %s',
                        $ticket->isAssigned() ?
                            __('Reassign') :  __('Assign'),
                        !strcasecmp($target, 'agents') ?
                            __('to an Agent') : __('to a Team')
                    )),
                ':action' => sprintf('#tickets/%d/assign%s',
                    $ticket->getId(),
                    ($target  ? "/$target": '')),
                );

        if ($ticket->isAssigned()) {
            if ($ticket->getStaffId() == $thisstaff->getId())
                $assigned = __('you');
            else
                $assigned = $ticket->getAssigned();

            $info['notice'] = sprintf(__('%s is currently assigned to %s'),
                    __('This ticket'),
                    Format::htmlchars($assigned)
                    );
        }

        if ($_POST && $form->isValid()) {
            if ($ticket->assign($form, $errors)) {
                $_SESSION['::sysmsgs']['msg'] = sprintf(
                        __('%s successfully'),
                        sprintf(
                            __('%s assigned to %s'),
                            __('Ticket'),
                            $form->getAssignee())
                        );
                Http::response(201, $ticket->getId());
            }

            $form->addErrors($errors);
            $info['error'] = $errors['err'] ?: __('Unable to assign ticket');
        }

        include STAFFINC_DIR . 'templates/assign.tmpl.php';
    }

    function claim($tid) {

        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid)))
            Http::response(404, __('No such ticket'));

        // Check for premissions and such
        if (!$ticket->checkStaffPerm($thisstaff, Ticket::PERM_ASSIGN)
                || !$ticket->isOpen() // Claim only open
                || $ticket->getStaff() // cannot claim assigned ticket
                || !($form = $ticket->getClaimForm($_POST)))
            Http::response(403, __('Permission denied'));

        $errors = array();
        $info = array(
                ':title' => sprintf(__('Ticket #%s: %s'),
                    $ticket->getNumber(),
                    __('Claim')),
                ':action' => sprintf('#tickets/%d/claim',
                    $ticket->getId()),

                );

        if ($ticket->isAssigned()) {
            if ($ticket->getStaffId() == $thisstaff->getId())
                $assigned = __('you');
            else
                $assigned = $ticket->getAssigned();

            $info['error'] = sprintf(__('%s is currently assigned to %s'),
                    __('This ticket'),
                    $assigned);
        } else {
            $info['warn'] = sprintf(__('Are you sure you want to CLAIM %s?'),
                    __('this ticket'));
        }

        if ($_POST && $form->isValid()) {
            if ($ticket->claim($form, $errors)) {
                $_SESSION['::sysmsgs']['msg'] = sprintf(
                        __('%s successfully'),
                        sprintf(
                            __('%s assigned to %s'),
                            __('Ticket'),
                            __('you'))
                        );
                Http::response(201, $ticket->getId());
            }

            $form->addErrors($errors);
            $info['error'] = $errors['err'] ?: __('Unable to claim ticket');
        }

        $verb = sprintf('%s, %s', __('Yes'), __('Claim'));

        include STAFFINC_DIR . 'templates/assign.tmpl.php';

    }

    function massProcess($action, $w=null)  {
        global $thisstaff, $cfg;

        $actions = array(
                'transfer' => array(
                    'verbed' => __('transferred'),
                    ),
                'assign' => array(
                    'verbed' => __('assigned'),
                    ),
                'claim' => array(
                    'verbed' => __('assigned'),
                    ),
                'delete' => array(
                    'verbed' => __('deleted'),
                    ),
                'reopen' => array(
                    'verbed' => __('reopen'),
                    ),
                'close' => array(
                    'verbed' => __('closed'),
                    ),
                );

        if (!isset($actions[$action]))
            Http::response(404, __('Unknown action'));

        $info = $errors = $e = array();
        $inc = null;
        $i = $count = 0;
        if ($_POST) {
            if (!$_POST['tids'] || !($count=count($_POST['tids'])))
                $errors['err'] = sprintf(
                        __('You must select at least %s.'),
                        __('one ticket'));
        } else {
            $count  =  $_REQUEST['count'];
        }
        switch ($action) {
        case 'claim':
            $w = 'me';
        case 'assign':
            $inc = 'assign.tmpl.php';
            $info[':action'] = "#tickets/mass/assign/$w";
            $info[':title'] = sprintf('Assign %s',
                    _N('selected ticket', 'selected tickets', $count));

            $form = AssignmentForm::instantiate($_POST);

            $assignCB = function($t, $f, $e) {
                return $t->assign($f, $e);
            };

            $assignees = null;
            switch ($w) {
                case 'agents':
                    $depts = array();
                    $tids = $_POST['tids'] ?: array_filter(explode(',', $_REQUEST['tids']));
                    if ($tids) {
                        $tickets = TicketModel::objects()
                            ->distinct('dept_id')
                            ->filter(array('ticket_id__in' => $tids));

                        $depts = $tickets->values_flat('dept_id');
                    }
                    $members = Staff::objects()
                        ->distinct('staff_id')
                        ->filter(array(
                                    'onvacation' => 0,
                                    'isactive' => 1,
                                    )
                                );

                    if ($depts) {
                        $members->filter(Q::any( array(
                                        'dept_id__in' => $depts,
                                        Q::all(array(
                                            'dept_access__dept__id__in' => $depts,
                                            Q::not(array('dept_access__dept__flags__hasbit'
                                                => Dept::FLAG_ASSIGN_MEMBERS_ONLY))
                                            ))
                                        )));
                    }

                    switch ($cfg->getAgentNameFormat()) {
                    case 'last':
                    case 'lastfirst':
                    case 'legal':
                        $members->order_by('lastname', 'firstname');
                        break;

                    default:
                        $members->order_by('firstname', 'lastname');
                    }

                    $prompt  = __('Select an Agent');
                    $assignees = array();
                    foreach ($members as $member)
                         $assignees['s'.$member->getId()] = $member->getName();

                    if (!$assignees)
                        $info['warn'] =  __('No agents available for assignment');
                    break;
                case 'teams':
                    $assignees = array();
                    $prompt = __('Select a Team');
                    foreach (Team::getActiveTeams() as $id => $name)
                        $assignees['t'.$id] = $name;

                    if (!$assignees)
                        $info['warn'] =  __('No teams available for assignment');
                    break;
                case 'me':
                    $info[':action'] = '#tickets/mass/claim';
                    $info[':title'] = sprintf('Claim %s',
                            _N('selected ticket', 'selected tickets', $count));
                    $info['warn'] = sprintf(
                            __('Are you sure you want to CLAIM %s?'),
                            _N('selected ticket', 'selected tickets', $count));
                    $verb = sprintf('%s, %s', __('Yes'), __('Claim'));
                    $id = sprintf('s%s', $thisstaff->getId());
                    $assignees = array($id => $thisstaff->getName());
                    $vars = $_POST ?: array('assignee' => array($id));
                    $form = ClaimForm::instantiate($vars);
                    $assignCB = function($t, $f, $e) {
                        return $t->claim($f, $e);
                    };
                    break;
            }

            if ($assignees != null)
                $form->setAssignees($assignees);

            if ($prompt && ($f=$form->getField('assignee')))
                $f->configure('prompt', $prompt);

            if ($_POST && $form->isValid()) {
                foreach ($_POST['tids'] as $tid) {
                    if (($t=Ticket::lookup($tid))
                            // Make sure the agent is allowed to
                            // access and assign the task.
                            && $t->checkStaffPerm($thisstaff, Ticket::PERM_ASSIGN)
                            // Do the assignment
                            && $assignCB($t, $form, $e)
                            )
                        $i++;
                }

                if (!$i) {
                    $info['error'] = sprintf(
                            __('Unable to %1$s %2$s'),
                            __('assign'),
                            _N('selected ticket', 'selected tickets', $count));
                }
            }
            break;
        case 'transfer':
            $inc = 'transfer.tmpl.php';
            $info[':action'] = '#tickets/mass/transfer';
            $info[':title'] = sprintf('Transfer %s',
                    _N('selected ticket', 'selected tickets', $count));
            $form = TransferForm::instantiate($_POST);
            if ($_POST && $form->isValid()) {
                foreach ($_POST['tids'] as $tid) {
                    if (($t=Ticket::lookup($tid))
                            // Make sure the agent is allowed to
                            // access and transfer the task.
                            && $t->checkStaffPerm($thisstaff, Ticket::PERM_TRANSFER)
                            // Do the transfer
                            && $t->transfer($form, $e)
                            )
                        $i++;
                }

                if (!$i) {
                    $info['error'] = sprintf(
                            __('Unable to %1$s %2$s'),
                            __('transfer'),
                            _N('selected ticket', 'selected tickets', $count));
                }
            }
            break;
        case 'delete':
            $inc = 'delete.tmpl.php';
            $info[':action'] = '#tickets/mass/delete';
            $info[':title'] = sprintf('Delete %s',
                    _N('selected ticket', 'selected tickets', $count));

            $info[':placeholder'] = sprintf(__(
                        'Optional reason for deleting %s'),
                    _N('selected ticket', 'selected tickets', $count));
            $info['warn'] = sprintf(__(
                        'Are you sure you want to DELETE %s?'),
                    _N('selected ticket', 'selected tickets', $count));
            $info[':extra'] = sprintf('%s',
                        __('Deleted tickets CANNOT be recovered, including any associated attachments.')
                        );

            // Generic permission check.
            if (!$thisstaff->hasPerm(Ticket::PERM_DELETE, false))
                $errors['err'] = sprintf(
                        __('You do not have permission %s'),
                        __('to delete tickets'));

            if ($_POST && !$errors) {
                foreach ($_POST['tids'] as $tid) {
                    if (($t=Ticket::lookup($tid))
                            && $t->checkStaffPerm($thisstaff, Ticket::PERM_DELETE)
                            && $t->delete($_POST['comments'], $e)
                            )
                        $i++;
                }

                if (!$i) {
                    $info['error'] = sprintf(
                            __('Unable to %1$s %2$s'),
                            __('delete'),
                            _N('selected ticket', 'selected tickets', $count));
                }
            }
            break;
        default:
            Http::response(404, __('Unknown action'));
        }

        if ($_POST && $i) {

            // Assume success
            if ($i==$count) {
                $msg = sprintf(__('Successfully %s %s.'),
                        $actions[$action]['verbed'],
                        sprintf('%1$d %2$s',
                            $count,
                            _N('selected ticket', 'selected tickets', $count))
                        );
                $_SESSION['::sysmsgs']['msg'] = $msg;
            } else {
                $warn = sprintf(
                        __('%1$d of %2$d %3$s %4$s'
                        /* Tokens are <x> of <y> <selected ticket(s)> <actioned> */),
                        $i, $count,
                        _N('selected ticket', 'selected tickets',
                            $count),
                        $actions[$action]['verbed']);
                $_SESSION['::sysmsgs']['warn'] = $warn;
            }
            Http::response(201, 'processed');
        } elseif($_POST && !isset($info['error'])) {
            $info['error'] = $errors['err'] ?: sprintf(
                    __('Unable to %1$s %2$s'),
                    __('process'),
                    _N('selected ticket', 'selected tickets', $count));
        }

        if ($_POST)
            $info = array_merge($info, Format::htmlchars($_POST));

        include STAFFINC_DIR . "templates/$inc";
        //  Copy checked tickets to the form.
        echo "
        ";

    }

    function changeTicketStatus($tid, $status, $id=0) {
        global $thisstaff;

        if (!$thisstaff)
            Http::response(403, 'Access denied');
        elseif (!$tid
                || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown ticket #');

        $role = $thisstaff->getRole($ticket->getDeptId());

        $info = array();
        $state = null;
        switch($status) {
            case 'open':
            case 'reopen':
                $state = 'open';
                break;
            case 'close':
                if (!$role->hasPerm(TicketModel::PERM_CLOSE))
                    Http::response(403, 'Access denied');
                $state = 'closed';

                // Check if ticket is closeable
                if (is_string($closeable=$ticket->isCloseable()))
                    $info['warn'] =  $closeable;

                break;
            case 'delete':
                if (!$role->hasPerm(TicketModel::PERM_DELETE))
                    Http::response(403, 'Access denied');
                $state = 'deleted';
                break;
            default:
                $state = $ticket->getStatus()->getState();
                $info['warn'] = sprintf(__('%s: Unknown or invalid'),
                        __('status'));
        }

        $info['status_id'] = $id ?: $ticket->getStatusId();

        return self::_changeTicketStatus($ticket, $state, $info);
    }

    function setTicketStatus($tid) {
        global $thisstaff, $ost;

        if (!$thisstaff)
            Http::response(403, 'Access denied');
        elseif (!$tid
                || !($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown ticket #');

        $errors = $info = array();
        if (!$_POST['status_id']
                || !($status= TicketStatus::lookup($_POST['status_id'])))
            $errors['status_id'] = sprintf('%s %s',
                    __('Unknown or invalid'), __('status'));
        elseif ($status->getId() == $ticket->getStatusId())
            $errors['err'] = sprintf(__('Ticket already set to %s status'),
                    __($status->getName()));
        elseif (($role = $thisstaff->getRole($ticket->getDeptId()))) {
            // Make sure the agent has permission to set the status
            switch(mb_strtolower($status->getState())) {
                case 'open':
                    if (!$role->hasPerm(TicketModel::PERM_CLOSE)
                            && !$role->hasPerm(TicketModel::PERM_CREATE))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to reopen tickets'));
                    break;
                case 'closed':
                    if (!$role->hasPerm(TicketModel::PERM_CLOSE))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to resolve/close tickets'));
                    break;
                case 'deleted':
                    if (!$role->hasPerm(TicketModel::PERM_DELETE))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to archive/delete tickets'));
                    break;
                default:
                    $errors['err'] = sprintf('%s %s',
                            __('Unknown or invalid'), __('status'));
            }
        } else {
            $errors['err'] = __('Access denied');
        }

        $state = strtolower($status->getState());

        if (!$errors && $ticket->setStatus($status, $_REQUEST['comments'], $errors)) {

            if ($state == 'deleted') {
                $msg = sprintf('%s %s',
                        sprintf(__('Ticket #%s'), $ticket->getNumber()),
                        __('deleted sucessfully')
                        );
            } elseif ($state != 'open') {
                 $msg = sprintf(__('%s status changed to %s'),
                         sprintf(__('Ticket #%s'), $ticket->getNumber()),
                         $status->getName());
            } else {
                $msg = sprintf(
                        __('%s status changed to %s'),
                        __('Ticket'),
                        $status->getName());
            }

            $_SESSION['::sysmsgs']['msg'] = $msg;

            Http::response(201, 'Successfully processed');
        } elseif (!$errors['err']) {
            $errors['err'] =  __('Error updating ticket status');
        }

        $state = $state ?: $ticket->getStatus()->getState();
        $info['status_id'] = $status
            ? $status->getId() : $ticket->getStatusId();

        return self::_changeTicketStatus($ticket, $state, $info, $errors);
    }

    function changeSelectedTicketsStatus($status, $id=0) {
        global $thisstaff, $cfg;

        if (!$thisstaff)
            Http::response(403, 'Access denied');

        $state = null;
        $info = array();
        switch($status) {
            case 'open':
            case 'reopen':
                $state = 'open';
                break;
            case 'close':
                if (!$thisstaff->hasPerm(TicketModel::PERM_CLOSE, false))
                    Http::response(403, 'Access denied');
                $state = 'closed';
                break;
            case 'delete':
                if (!$thisstaff->hasPerm(TicketModel::PERM_DELETE, false))
                    Http::response(403, 'Access denied');

                $state = 'deleted';
                break;
            default:
                $info['warn'] = sprintf('%s %s',
                        __('Unknown or invalid'), __('status'));
        }

        $info['status_id'] = $id;

        return self::_changeSelectedTicketsStatus($state, $info);
    }

    function setSelectedTicketsStatus($state) {
        global $thisstaff, $ost;

        $errors = $info = array();
        if (!$thisstaff || !$thisstaff->canManageTickets())
            $errors['err'] = sprintf('%s %s',
                    sprintf(__('You do not have permission %s'),
                        __('to mass manage tickets')),
                    __('Contact admin for such access'));
        elseif (!$_REQUEST['tids'] || !count($_REQUEST['tids']))
            $errors['err']=sprintf(__('You must select at least %s.'),
                    __('one ticket'));
        elseif (!($status= TicketStatus::lookup($_REQUEST['status_id'])))
            $errors['status_id'] = sprintf('%s %s',
                    __('Unknown or invalid'), __('status'));
        elseif (!$errors) {
            // Make sure the agent has permission to set the status
            switch(mb_strtolower($status->getState())) {
                case 'open':
                    if (!$thisstaff->hasPerm(TicketModel::PERM_CLOSE, false)
                            && !$thisstaff->hasPerm(TicketModel::PERM_CREATE, false))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to reopen tickets'));
                    break;
                case 'closed':
                    if (!$thisstaff->hasPerm(TicketModel::PERM_CLOSE, false))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to resolve/close tickets'));
                    break;
                case 'deleted':
                    if (!$thisstaff->hasPerm(TicketModel::PERM_DELETE, false))
                        $errors['err'] = sprintf(__('You do not have permission %s'),
                                __('to archive/delete tickets'));
                    break;
                default:
                    $errors['err'] = sprintf('%s %s',
                            __('Unknown or invalid'), __('status'));
            }
        }

        $count = count($_REQUEST['tids']);
        if (!$errors) {
            $i = 0;
            $comments = $_REQUEST['comments'];
            foreach ($_REQUEST['tids'] as $tid) {

                if (($ticket=Ticket::lookup($tid))
                        && $ticket->getStatusId() != $status->getId()
                        && $ticket->checkStaffPerm($thisstaff)
                        && $ticket->setStatus($status, $comments, $errors))
                    $i++;
            }

            if (!$i) {
                $errors['err'] = $errors['err']
                    ?: sprintf(__('Unable to change status for %s'),
                        _N('the selected ticket', 'any of the selected tickets', $count));
            }
            else {
                // Assume success
                if ($i==$count) {

                    if (!strcasecmp($status->getState(), 'deleted')) {
                        $msg = sprintf(__( 'Successfully deleted %s.'),
                                _N('selected ticket', 'selected tickets',
                                    $count));
                    } else {
                       $msg = sprintf(
                            __(
                                /* 1$ will be 'selected ticket(s)', 2$ is the new status */
                                'Successfully changed status of %1$s to %2$s'),
                            _N('selected ticket', 'selected tickets',
                                $count),
                            $status->getName());
                    }

                    $_SESSION['::sysmsgs']['msg'] = $msg;
                } else {

                    if (!strcasecmp($status->getState(), 'deleted')) {
                        $warn = sprintf(__('Successfully deleted %s.'),
                                sprintf(__('%1$d of %2$d selected tickets'),
                                    $i, $count)
                                );
                    } else {

                        $warn = sprintf(
                                __('%1$d of %2$d %3$s status changed to %4$s'),$i, $count,
                                _N('selected ticket', 'selected tickets',
                                    $count),
                                $status->getName());
                    }

                    $_SESSION['::sysmsgs']['warn'] = $warn;
                }

                Http::response(201, 'Successfully processed');
            }
        }

        return self::_changeSelectedTicketsStatus($state, $info, $errors);
    }

    function triggerThreadAction($ticket_id, $thread_id, $action) {
        $thread = ThreadEntry::lookup($thread_id);
        if (!$thread)
            Http::response(404, 'No such ticket thread entry');
        if ($thread->getThread()->getObjectId() != $ticket_id)
            Http::response(404, 'No such ticket thread entry');

        $valid = false;
        foreach ($thread->getActions() as $group=>$list) {
            foreach ($list as $name=>$A) {
                if ($A->getId() == $action) {
                    $valid = true; break;
                }
            }
        }
        if (!$valid)
            Http::response(400, 'Not a valid action for this thread');

        $thread->triggerAction($action);
    }

    private function _changeSelectedTicketsStatus($state, $info=array(), $errors=array()) {

        $count = $_REQUEST['count'] ?:
            ($_REQUEST['tids'] ?  count($_REQUEST['tids']) : 0);

        $info['title'] = sprintf(__('Change Status — %1$d %2$s selected'),
                 $count,
                 _N('ticket', 'tickets', $count)
                 );

        if (!strcasecmp($state, 'deleted')) {

            $info['warn'] = sprintf(__(
                        'Are you sure you want to DELETE %s?'),
                    _N('selected ticket', 'selected tickets', $count)
                    );

            $info['extra'] = sprintf('%s', __(
                        'Deleted tickets CANNOT be recovered, including any associated attachments.')
                    );

            $info['placeholder'] = sprintf(__(
                        'Optional reason for deleting %s'),
                    _N('selected ticket', 'selected tickets', $count));
        }

        $info['status_id'] = $info['status_id'] ?: $_REQUEST['status_id'];
        $info['comments'] = Format::htmlchars($_REQUEST['comments']);

        return self::_changeStatus($state, $info, $errors);
    }

    private function _changeTicketStatus($ticket, $state, $info=array(), $errors=array()) {

        $verb = TicketStateField::getVerb($state);

        $info['action'] = sprintf('#tickets/%d/status', $ticket->getId());
        $info['title'] = sprintf(__(
                    /* 1$ will be a verb, like 'open', 2$ will be the ticket number */
                    '%1$s Ticket #%2$s'),
                $verb ?: $state,
                $ticket->getNumber()
                );

        // Deleting?
        if (!strcasecmp($state, 'deleted')) {

            $info['placeholder'] = sprintf(__(
                        'Optional reason for deleting %s'),
                    __('this ticket'));
            $info[ 'warn'] = sprintf(__(
                        'Are you sure you want to DELETE %s?'),
                        __('this ticket'));
            //TODO: remove message below once we ship data retention plug
            $info[ 'extra'] = sprintf('%s',
                        __('Deleted tickets CANNOT be recovered, including any associated attachments.')
                        );
        }

        $info['status_id'] = $info['status_id'] ?: $ticket->getStatusId();
        $info['comments'] = Format::htmlchars($_REQUEST['comments']);

        return self::_changeStatus($state, $info, $errors);
    }

    private function _changeStatus($state, $info=array(), $errors=array()) {

        if ($info && isset($info['errors']))
            $errors = array_merge($errors, $info['errors']);

        if (!$info['error'] && isset($errors['err']))
            $info['error'] = $errors['err'];

        include(STAFFINC_DIR . 'templates/ticket-status.tmpl.php');
    }

    function tasks($tid) {
        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown ticket');

         include STAFFINC_DIR . 'ticket-tasks.inc.php';
    }

    function addTask($tid) {
        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid)))
            Http::response(404, 'Unknown ticket');

        if (!$ticket->checkStaffPerm($thisstaff, Task::PERM_CREATE))
            Http::response(403, 'Permission denied');

        $info=$errors=array();

        if ($_POST) {
            Draft::deleteForNamespace(
                    sprintf('ticket.%d.task', $ticket->getId()),
                    $thisstaff->getId());
            // Default form
            $form = TaskForm::getInstance();
            $form->setSource($_POST);
            // Internal form
            $iform = TaskForm::getInternalForm($_POST);
            $isvalid = true;
            if (!$iform->isValid())
                $isvalid = false;
            if (!$form->isValid())
                $isvalid = false;

            if ($isvalid) {
                $vars = $_POST;
                $vars['object_id'] = $ticket->getId();
                $vars['object_type'] = ObjectModel::OBJECT_TYPE_TICKET;
                $vars['default_formdata'] = $form->getClean();
                $vars['internal_formdata'] = $iform->getClean();
                $desc = $form->getField('description');
                if ($desc
                        && $desc->isAttachmentsEnabled()
                        && ($attachments=$desc->getWidget()->getAttachments()))
                    $vars['cannedattachments'] = $attachments->getClean();
                $vars['staffId'] = $thisstaff->getId();
                $vars['poster'] = $thisstaff;
                $vars['ip_address'] = $_SERVER['REMOTE_ADDR'];
                if (($task=Task::create($vars, $errors)))
                    Http::response(201, $task->getId());
            }

            $info['error'] = __('Error adding task - try again!');
        }

        $info['action'] = sprintf('#tickets/%d/add-task', $ticket->getId());
        $info['title'] = sprintf(
                __( 'Ticket #%1$s: %2$s'),
                $ticket->getNumber(),
                __('Add New Task')
                );

         include STAFFINC_DIR . 'templates/task.tmpl.php';
    }

    function task($tid, $id) {
        global $thisstaff;

        if (!($ticket=Ticket::lookup($tid))
                || !$ticket->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown ticket');

        // Lookup task and check access
        if (!($task=Task::lookup($id))
                || !$task->checkStaffPerm($thisstaff))
            Http::response(404, 'Unknown task');

        $info = $errors = array();
        $note_attachments_form = new SimpleForm(array(
            'attachments' => new FileUploadField(array('id'=>'attach',
                'name'=>'attach:note',
                'configuration' => array('extensions'=>'')))
        ));

        $reply_attachments_form = new SimpleForm(array(
            'attachments' => new FileUploadField(array('id'=>'attach',
                'name'=>'attach:reply',
                'configuration' => array('extensions'=>'')))
        ));

        if ($_POST) {
            $vars = $_POST;
            switch ($_POST['a']) {
            case 'postnote':
                $attachments = $note_attachments_form->getField('attachments')->getClean();
                $vars['cannedattachments'] = array_merge(
                    $vars['cannedattachments'] ?: array(), $attachments);
                if (($note=$task->postNote($vars, $errors, $thisstaff))) {
                    $msg=__('Note posted successfully');
                    // Clear attachment list
                    $note_attachments_form->setSource(array());
                    $note_attachments_form->getField('attachments')->reset();
                    Draft::deleteForNamespace('task.note.'.$task->getId(),
                            $thisstaff->getId());
                } else {
                    if (!$errors['err'])
                        $errors['err'] = __('Unable to post the note - missing or invalid data.');
                }
                break;
            case 'postreply':
                $attachments = $reply_attachments_form->getField('attachments')->getClean();
                $vars['cannedattachments'] = array_merge(
                    $vars['cannedattachments'] ?: array(), $attachments);
                if (($response=$task->postReply($vars, $errors))) {
                    $msg=__('Update posted successfully');
                    // Clear attachment list
                    $reply_attachments_form->setSource(array());
                    $reply_attachments_form->getField('attachments')->reset();
                    Draft::deleteForNamespace('task.reply.'.$task->getId(),
                            $thisstaff->getId());
                } else {
                    if (!$errors['err'])
                        $errors['err'] = __('Unable to post the reply - missing or invalid data.');
                }
                break;
            default:
                $errors['err'] = __('Unknown action');
            }
        }

        include STAFFINC_DIR . 'templates/task-view.tmpl.php';
    }
}
?>


text:
[jvm]
Content
open override fun [build](build.md)(): [ArrayLoad](../index.md)
More info

Build the object of type T.

#### Return

Instance of object of type T.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using IDI.Central.Common.Enums;
using IDI.Central.Domain.Modules.Sales.AggregateRoots;
using IDI.Central.Models.Sales;
using IDI.Core.Common;
using IDI.Core.Common.Extensions;
using IDI.Core.Infrastructure.DependencyInjection;
using IDI.Core.Infrastructure.Queries;
using IDI.Core.Repositories;

namespace IDI.Central.Domain.Modules.Sales.Queries
{
    public class QueryOrderSetCondition : Condition
    {
        public DocumentCategory Category { get; set; }

        public DateTime Deadline { get; set; }
    }

    public class QueryOrderSet : Query<QueryOrderSetCondition, Set<OrderModel>>
    {
        [Injection]
        public IQueryableRepository<Order> Orders { get; set; }

        public override Result<Set<OrderModel>> Execute(QueryOrderSetCondition condition)
        {
            var orders = this.Orders.Include(e => e.Customer).Get(e => e.Category == condition.Category && e.Date >= condition.Deadline);

            var collection = orders.OrderBy(e => e.Date).Select(e => new OrderModel
            {
                Id = e.Id,
                Category = e.Category,
                CustomerId = e.CustomerId.HasValue ? e.CustomerId.Value : Guid.Empty,
                CustomerName = e.Customer == null ? string.Empty : e.Customer.Name,
                Date = e.Date.AsLongDate(),
                SN = e.SN,
                Status = e.Status,
                StatusDesc = Localization.Get(e.Status),
                Remark = e.Remark,
                Items = new List<OrderItemModel>()
            }).ToList();

            return Result.Success(new Set<OrderModel>(collection));
        }
    }
}


text:
[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors)
[![Ansible Galaxy](https://img.shields.io/badge/ansible--galaxy-letsenctypt-blue.svg?style=flat-square)](https://galaxy.ansible.com/auxilincom/letsencrypt)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=flat-square)](https://github.com/auxilin/ansible-letsencrypt/blob/master/LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)

[![Watch on GitHub](https://img.shields.io/github/watchers/auxilincom/ansible-letsencrypt.svg?style=social&label=Watch)](https://github.com/auxilincom/ansible-letsencrypt/watchers)
[![Star on GitHub](https://img.shields.io/github/stars/auxilincom/ansible-letsencrypt.svg?style=social&label=Stars)](https://github.com/auxilincom/ansible-letsencrypt/stargazers)
[![Tweet](https://img.shields.io/twitter/url/https/github.com/auxilincom/ansible-letsencrypt.svg?style=social)](https://twitter.com/intent/tweet?text=I%27m%20using%20Auxilin%20components%20to%20build%20my%20next%20product%20🚀.%20Check%20it%20out:%20https://github.com/auxilincom/ansible-letsencrypt)

The ansible role for generating [letsecrypt](https://letsencrypt.org/) certificates.

## Features

* 🔐 Ability to generate single certificates for specific domains/subdomains
* 🔐 Ability to generate wildcard certificates using settings for the corresponding DNS provider
* ⚡ Automatically renew certificates every month
* 🔧 Generated certificates stored in the directory `/etc/letsencrypt/live/{{app_domain}}` where `app_domain` is the name of domain/subdomain for which we generated certificates and ready for use with any HTTP-server

## Role Variables

Available variables:

|Name|Default|Description|
|:--:|:--:|:----------|
|**`use_dns_plugin`**|`no`|Use certbot dns provider (use this if you need wildcard sertificate) or certbot itselt.|
|**`certbot_version`**|`latest`|# Version of certbot or certbot dns plugin (if `use_dns_plugin` is `yes`), see other versions [here](https://hub.docker.com/r/certbot/certbot/tags)|
|**`dns_plugin`**|`cloudflare`|Dsn plugin that will be used with certbot (when `use_dns_plugin` is `yes`), list of plugins can be found [here](https://certbot.eff.org/docs/using.html#dns-plugins)|
|**`email`**|`Email that will be used for notifications`|Email that will be used for notifications|
|**`domains_list`**|`- "{{ ansible_fqdn }}"`|List of domain for which you want to get a certificates|

Additional variables for Cloudflare

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_email`**|`""`|DNS email|
|**`dns_api_key`**|`""`|DNS api key|

Additional variables for CloudXNS

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_api_key`**|`""`|DNS api key|
|**`dns_secret_key`**|`""`|DNS secret key|

Additional variables for DigitalOcean

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_token`**|`""`|DNS token|

Additional variables for DNSimple

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_token`**|`""`|DNS token|

Additional variables for DNS Made Easy

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_api_key`**|`""`|DNS api key|
|**`dns_secret_key`**|`""`|DNS secret key|

Additional variables for Linode

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_key`**|`""`|DNS key|

Additional variables for LuaDNS

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_email`**|`""`|DNS email|
|**`dns_token`**|`""`|DNS token|

Additional variables for NS1

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_api_key`**|`""`|DNS api key|

Additional variables for OVH

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_endpoint`**|`""`|DNS endpoint|
|**`dns_application_key`**|`""`|DNS application key|
|**`dns_application_secret`**|`""`|DNS application secret|
|**`dns_consumer_key`**|`""`|DNS consumer key|

Additional variables for RFC 2136

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_server`**|`""`|Target DNS server|
|**`dns_port`**|`""`|Target DNS port|
|**`dns_name`**|`""`|TSIG key name|
|**`dns_secret`**|`""`|TSIG key secret|
|**`dns_algorithm`**|`""`|TSIG key algorithm|

Additional variables for Route 53

|Name|Default|Description|
|:--:|:--:|:----------|
|**`dns_access_key_id`**|`""`|DNS access key id|
|**`dns_secret_access_key`**|`""`|DNS secret access key id|

## Dependencies

[Docker](https://www.docker.com/) must be installed on the server in order to use this role. If you don't have docker on your server we recommend [angstwad.docker_ubuntu](https://github.com/angstwad/docker.ubuntu) Ansible role.

Example of using `angstwad.docker_ubuntu`:
```yml
---
- name: Setup server
  hosts: server
  become: true
  roles:
    - { role: angstwad.docker_ubuntu }
```

## Quick example

Example of the playbook file:

```yml
---
- name: Setup server
  hosts: server
  become: true
  roles:
    - role: auxilincom.letsencrypt
      use_dns_plugin: yes
      certbot_version: v0.26.1
      dns_plugin: cloudflare
      email: ship@test.com
      domains_list:
        - "*.ship.com"
      dns_email: ship_dns@test.com
      dns_api_key: 0123456789abcdef0123456789abcdef01234567
```

## Change Log

This project adheres to [Semantic Versioning](http://semver.org/).
Every release is documented on the Github [Releases](https://github.com/auxilincom/ansible-letsencrypt/releases) page.

## License

Ansible-letsencrypt is released under the [MIT License](https://github.com/auxilincom/ansible-letsencrypt/blob/master/LICENSE).

## Contributing

Please read [CONTRIBUTING.md](https://github.com/auxilincom/ansible-letsencrypt/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

## Contributors

Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):

Evgeny Zhivitsa
📖 🤔 💻

Andrew Orsich
🤔 👀

This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome!


text:
@implementation LanternBrowserTests

- (void)setUp
{
    [super setUp];

    // Set-up code here.
}

- (void)tearDown
{
    // Tear-down code here.

    [super tearDown];
}

- (void)testExample
{
    STFail(@"Unit tests are not implemented yet in LanternBrowserTests");
}

@end


text:
<?php

use yii\helpers\Inflector;

/* @var $this yii\web\View */
/* @var $generator \infinitydevphp\gii\crud\Generator */

/* @var $model \yii\db\ActiveRecord */
$model = new $generator->modelClass();
\infinitydevphp\gii\assets\ModelGeneratorAssets::register($this);
$safeAttributes = $model->safeAttributes();
if (empty($safeAttributes)) {
    $safeAttributes = $model->attributes();
}

echo "<?php\n";

foreach ($generator->used as $use) {
    if (is_string($use)) {
        echo "use {$use};" . PHP_EOL;
    }
}
?>

/* @var $this yii\web\View */
/* @var $model <?= ltrim($generator->modelClass, '\\') ?> */
/* @var $form yii\widgets\ActiveForm */

?>

<?php
foreach ($generator->expressions as $expression) {
    if (is_string($expression)) {
        echo "{$expression};";
    }
}
?>

<div class="<?= Inflector::camel2id($generator->getModelNameForView()) ?>-form">

    <?= "<?php " ?>$form = ActiveForm::begin([
        'options' => [
            'class' => 'form-vertical'
        ],
    ]); ?>

<?php
if (count($generator->columns)) {
    foreach ($generator->columns as $column) {
        /** @var $column \infinitydevphp\gii\models\WidgetsCrud */
        $arrays = explode('.', $column->fieldName);
        $field = end($arrays);
        echo "    <?php \n    echo " . str_replace(['{field}', '{model}', '{field_action}'],
                ['\'' . $field . '\'', '$model', $field], $generator->generateWidgetActiveField($column)) . " \n    ?>\n\n";
    }
} else {
foreach ($safeAttributes as $attribute) {
    echo "    <?php echo " . $generator->generateActiveField($attribute) . " ?>\n\n";
}} ?>

        <?= "<?php \n echo " ?>Html::submitButton($model->isNewRecord ? <?= $generator->generateString('Create') ?> : <?= $generator->generateString('Update') ?>, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) <?= "\n" ?> ?>

    <?= "<?php " ?>ActiveForm::end(); ?>


text:
#include <uavcan/node/service_client.hpp>

namespace uavcan
{
/*
 * ServiceClientBase::CallState
 */
void ServiceClientBase::CallState::handleDeadline(MonotonicTime)
{
    UAVCAN_TRACE("ServiceClient::CallState", "Timeout from nid=%d, tid=%d, dtname=%s",
                 int(id_.server_node_id.get()), int(id_.transfer_id.get()),
                 (owner_.data_type_descriptor_ == NULL) ? "???" : owner_.data_type_descriptor_->getFullName());
    /*
     * What we're doing here is relaying execution from this call stack to a different one.
     * We need it because call registry cannot release memory from this callback, because this will destroy the
     * object method of which we're executing now.
     */
    UAVCAN_ASSERT(timed_out_ == false);
    timed_out_ = true;
    owner_.generateDeadlineImmediately();
    UAVCAN_TRACE("ServiceClient::CallState", "Relaying execution to the owner's handler via timer callback");
}

/*
 * ServiceClientBase
 */
int ServiceClientBase::prepareToCall(INode& node,
                                     const char* dtname,
                                     NodeID server_node_id,
                                     ServiceCallID& out_call_id)
{
    /*
     * Making sure we're not going to get transport error because of invalid input data
     */
    if (!server_node_id.isUnicast() || (server_node_id == node.getNodeID()))
    {
        UAVCAN_TRACE("ServiceClient", "Invalid Server Node ID");
        return -ErrInvalidParam;
    }
    out_call_id.server_node_id = server_node_id;

    /*
     * Determining the Data Type ID
     */
    if (data_type_descriptor_ == NULL)
    {
        GlobalDataTypeRegistry::instance().freeze();
        data_type_descriptor_ = GlobalDataTypeRegistry::instance().find(DataTypeKindService, dtname);
        if (data_type_descriptor_ == NULL)
        {
            UAVCAN_TRACE("ServiceClient", "Type [%s] is not registered", dtname);
            return -ErrUnknownDataType;
        }
        UAVCAN_TRACE("ServiceClient", "Data type descriptor inited: %s", data_type_descriptor_->toString().c_str());
    }
    UAVCAN_ASSERT(data_type_descriptor_ != NULL);

    /*
     * Determining the Transfer ID
     */
    const OutgoingTransferRegistryKey otr_key(data_type_descriptor_->getID(),
                                              TransferTypeServiceRequest, server_node_id);
    const MonotonicTime otr_deadline = node.getMonotonicTime() + TransferSender::getDefaultMaxTransferInterval();
    TransferID* const otr_tid =
        node.getDispatcher().getOutgoingTransferRegistry().accessOrCreate(otr_key, otr_deadline);
    if (!otr_tid)
    {
        UAVCAN_TRACE("ServiceClient", "OTR access failure, dtd=%s", data_type_descriptor_->toString().c_str());
        return -ErrMemory;
    }
    out_call_id.transfer_id = *otr_tid;
    otr_tid->increment();

    return 0;
}

}


text:
using System;
/// <summary>
///
///
///
/// </summary>
class OddNumber
{
    static void Main()
    {
        long n = long.Parse(Console.ReadLine());

        long result = long.Parse(Console.ReadLine());
        for (int i = 1; i < n; i++)
        {
            result ^= long.Parse(Console.ReadLine());
        }
        Console.WriteLine(result);
    }
}


text:
<!DOCTYPE html>

    <title>PushNotifications  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

IBMPushNotifications Docs (48% documented)

View on GitHub

        IBMPushNotifications Reference

        PushNotifications  Reference

            Notification

                Notification

                – Message

                – Target

                – Settings

            PushNotifications

                PushNotifications

                – Region

            PushNotificationsError

                PushNotificationsError

            Other Enumerations

                ApnsType

                FCMType

                GcmLED

                GcmPriority

                GcmStyleTypes

                GcmVisibility

                TargetPlatform

            Other Type Aliases

                PushNotificationsCompletionHandler

PushNotifications

                    PushNotifications

Used to send Push notifications via a IBM Cloud Push Notifications service.

                        See more

Declaration

Swift

public class PushNotifications

© 2020 IBM. All rights reserved. (Last updated: 2020-04-30)

Generated by jazzy ♪♫ v0.13.3, a Realm project.


text:
package org.nbone.persistence.jdbc.dialect;

/**
 * A dialect compatible with the H2 database.
 *
 * @author Thomas Mueller
 * @author thinking
 *
 */
public class H2Dialect extends Dialect {

    public boolean supportsLimit() {
        return true;
    }

	public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) {
		return new StringBuffer(sql.length() + 40).
			append(sql).
			append((offset > 0) ? " limit "+limitPlaceholder+" offset "+offsetPlaceholder : " limit "+limitPlaceholder).
			toString();
	}

	@Override
	public boolean supportsLimitOffset() {
		return true;
	}

//    public boolean bindLimitParametersInReverseOrder() {
//        return true;
//    }
//
//    public boolean bindLimitParametersFirst() {
//        return false;
//    }

}


text: demonstrative webapp for project on elliptic curve cryptography


text:
package northwind.jpamodel;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name="`Order`")
public class Order {

    private int orderID;
    private String customerID;
    private Integer employeeID;
    private Date orderDate;
    private Date requiredDate;
    private Date shippedDate;
    private BigDecimal freight;
    private String shipName;
    private String shipAddress;
    private String shipCity;
    private String shipRegion;
    private String shipPostalCode;
    private String shipCountry;
    private int rowVersion;

    private Customer customer;
    private Employee employee;
    private InternationalOrder internationalOrder;
    private Set<OrderDetail> orderDetails;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
	public int getOrderID() {
		return orderID;
	}
	public void setOrderID(int orderID) {
		this.orderID = orderID;
	}
    @Column(insertable=false, updatable=false)
	public String getCustomerID() {
		return customerID;
	}
	public void setCustomerID(String customerID) {
		this.customerID = customerID;
	}
    @Column(insertable=false, updatable=false)
	public Integer getEmployeeID() {
		return employeeID;
	}
	public void setEmployeeID(Integer employeeID) {
		this.employeeID = employeeID;
	}
	public Date getOrderDate() {
		return orderDate;
	}
	public void setOrderDate(Date orderDate) {
		this.orderDate = orderDate;
	}
	public Date getRequiredDate() {
		return requiredDate;
	}
	public void setRequiredDate(Date requiredDate) {
		this.requiredDate = requiredDate;
	}
	public Date getShippedDate() {
		return shippedDate;
	}
	public void setShippedDate(Date shippedDate) {
		this.shippedDate = shippedDate;
	}
	public BigDecimal getFreight() {
		return freight;
	}
	public void setFreight(BigDecimal freight) {
		this.freight = freight;
	}
    @Column(length=40)
	public String getShipName() {
		return shipName;
	}
	public void setShipName(String shipName) {
		this.shipName = shipName;
	}
    @Column(length=60)
	public String getShipAddress() {
		return shipAddress;
	}
	public void setShipAddress(String shipAddress) {
		this.shipAddress = shipAddress;
	}
    @Column(length=15)
	public String getShipCity() {
		return shipCity;
	}
	public void setShipCity(String shipCity) {
		this.shipCity = shipCity;
	}
    @Column(length=15)
	public String getShipRegion() {
		return shipRegion;
	}
	public void setShipRegion(String shipRegion) {
		this.shipRegion = shipRegion;
	}
    @Column(length=10)
	public String getShipPostalCode() {
		return shipPostalCode;
	}
	public void setShipPostalCode(String shipPostalCode) {
		this.shipPostalCode = shipPostalCode;
	}
    @Column(length=15)
	public String getShipCountry() {
		return shipCountry;
	}
	public void setShipCountry(String shipCountry) {
		this.shipCountry = shipCountry;
	}
	@Version
	public int getRowVersion() {
		return rowVersion;
	}
	public void setRowVersion(int rowVersion) {
		this.rowVersion = rowVersion;
	}
	@ManyToOne
    @JoinColumn(name="customerID")
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
	@ManyToOne
    @JoinColumn(name="employeeID")
	public Employee getEmployee() {
		return employee;
	}
	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
	@OneToOne(mappedBy="order")
	public InternationalOrder getInternationalOrder() {
		return internationalOrder;
	}
	public void setInternationalOrder(InternationalOrder internationalOrder) {
		this.internationalOrder = internationalOrder;
	}
	@OneToMany(mappedBy="order")
	public Set<OrderDetail> getOrderDetails() {
		return orderDetails;
	}
	public void setOrderDetails(Set<OrderDetail> orderDetails) {
		this.orderDetails = orderDetails;
	}

}


text:
package org.nd4j.linalg.api.ops.impl.transforms;

import lombok.NoArgsConstructor;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.common.base.Preconditions;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@NoArgsConstructor
public class Cholesky extends DynamicCustomOp {

    public Cholesky(INDArray input) {
        addInputArgument(input);
    }

    public Cholesky(SameDiff sameDiff, SDVariable sdInput) {
        super(sameDiff, new SDVariable[]{sdInput});
    }

    @Override
    public String opName() {
        return "cholesky";
    }

    @Override
    public String tensorflowName() {
        return "Cholesky";
    }

    @Override
    public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
        TFGraphMapper.initFunctionFromProperties(nodeDef.getOp(), this, attributesForNode, nodeDef, graph);
    }

    @Override
    public List<SDVariable> doDiff(List<SDVariable> f1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){
        Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == 1, "Expected exactly 1 input datatypes for %s, got %s", getClass(), inputDataTypes);
        return Collections.singletonList(inputDataTypes.get(0));
    }
}


text:
// +build linux

package kubelet

import (
	"github.com/opencontainers/runc/libcontainer/selinux"
)

// getRootDirContext gets the SELinux context of the kubelet rootDir
// or returns an error.
func (kl *Kubelet) getRootDirContext() (string, error) {
	// If SELinux is not enabled, return an empty string
	if !selinux.SelinuxEnabled() {
		return "", nil
	}

	// Get the SELinux context of the rootDir.
	return selinux.Getfilecon(kl.getRootDir())
}