text:
using System;
using Assets.PostProcessing.Runtime.Models;
using UnityEngine;

namespace Assets.PostProcessing.Runtime
{
    public class PostProcessingProfile : ScriptableObject
    {
        #pragma warning disable 0169 // "field x is never used"

        public BuiltinDebugViewsModel debugViews = new BuiltinDebugViewsModel();
        public FogModel fog = new FogModel();
        public AntialiasingModel antialiasing = new AntialiasingModel();
        public AmbientOcclusionModel ambientOcclusion = new AmbientOcclusionModel();
        public ScreenSpaceReflectionModel screenSpaceReflection = new ScreenSpaceReflectionModel();
        public DepthOfFieldModel depthOfField = new DepthOfFieldModel();
        public MotionBlurModel motionBlur = new MotionBlurModel();
        public EyeAdaptationModel eyeAdaptation = new EyeAdaptationModel();
        public BloomModel bloom = new BloomModel();
        public ColorGradingModel colorGrading = new ColorGradingModel();
        public UserLutModel userLut = new UserLutModel();
        public ChromaticAberrationModel chromaticAberration = new ChromaticAberrationModel();
        public GrainModel grain = new GrainModel();
        public VignetteModel vignette = new VignetteModel();
        public DitheringModel dithering = new DitheringModel();

#if UNITY_EDITOR
        // Monitor settings
        [Serializable]
        public class MonitorSettings
        {
            // Callback used in the editor to grab the rendered frame and sent it to monitors
            public Action<RenderTexture> onFrameEndEditorOnly;

            // Global
            public int currentMonitorID = 0;
            public bool refreshOnPlay = false;

            // Histogram
            public enum HistogramMode
            {
                Red = 0,
                Green = 1,
                Blue = 2,
                Luminance = 3,
                RGBMerged,
                RGBSplit
            }

            public HistogramMode histogramMode = HistogramMode.Luminance;

            // Waveform
            public float waveformExposure = 0.12f;
            public bool waveformY = false;
            public bool waveformR = true;
            public bool waveformG = true;
            public bool waveformB = true;

            // Parade
            public float paradeExposure = 0.12f;

            // Vectorscope
            public float vectorscopeExposure = 0.12f;
            public bool vectorscopeShowBackground = true;
        }

        public MonitorSettings monitors = new MonitorSettings();
#endif
    }
}


text:
<?php

namespace Doctrine\MongoDB\Tests\Aggregation\Stage;

use Doctrine\MongoDB\Aggregation\Stage\Match;
use Doctrine\MongoDB\Tests\Aggregation\AggregationTestCase;
use Doctrine\MongoDB\Tests\TestCase;

class MatchTest extends TestCase
{
    use AggregationTestCase;

    public function testMatchStage()
    {
        $matchStage = new Match($this->getTestAggregationBuilder());
        $matchStage
            ->field('someField')
            ->equals('someValue');

        $this->assertSame(['$match' => ['someField' => 'someValue']], $matchStage->getExpression());
    }

    public function testMatchFromBuilder()
    {
        $builder = $this->getTestAggregationBuilder();
        $builder
            ->match()
            ->field('someField')
            ->equals('someValue');

        $this->assertSame([['$match' => ['someField' => 'someValue']]], $builder->getPipeline());
    }

    /**
     * @dataProvider provideProxiedExprMethods
     */
    public function testProxiedExprMethods($method, array $args = [])
    {
        $expr = $this->getMockQueryExpr();
        $expr
            ->expects($this->once())
            ->method($method)
            ->with(...$args);

        $stage = $this->getStubStage();
        $stage->setQuery($expr);

        $this->assertSame($stage, $stage->$method(...$args));
    }

    public function provideProxiedExprMethods()
    {
        return [
            'field()' => ['field', ['fieldName']],
            'equals()' => ['equals', ['value']],
            'in()' => ['in', [['value1', 'value2']]],
            'notIn()' => ['notIn', [['value1', 'value2']]],
            'notEqual()' => ['notEqual', ['value']],
            'gt()' => ['gt', [1]],
            'gte()' => ['gte', [1]],
            'lt()' => ['gt', [1]],
            'lte()' => ['gte', [1]],
            'range()' => ['range', [0, 1]],
            'size()' => ['size', [1]],
            'exists()' => ['exists', [true]],
            'type()' => ['type', [7]],
            'all()' => ['all', [['value1', 'value2']]],
            'maxDistance' => ['maxDistance', [5]],
            'minDistance' => ['minDistance', [5]],
            'mod()' => ['mod', [2, 0]],
            'geoIntersects()' => ['geoIntersects', [$this->getMockGeometry()]],
            'geoWithin()' => ['geoWithin', [$this->getMockGeometry()]],
            'geoWithinBox()' => ['geoWithinBox', [1, 2, 3, 4]],
            'geoWithinCenter()' => ['geoWithinCenter', [1, 2, 3]],
            'geoWithinCenterSphere()' => ['geoWithinCenterSphere', [1, 2, 3]],
            'geoWithinPolygon()' => ['geoWithinPolygon', [[0, 0], [1, 1], [1, 0]]],
            'addAnd() array' => ['addAnd', [[]]],
            'addAnd() Expr' => ['addAnd', [$this->getMockQueryExpr()]],
            'addOr() array' => ['addOr', [[]]],
            'addOr() Expr' => ['addOr', [$this->getMockQueryExpr()]],
            'addNor() array' => ['addNor', [[]]],
            'addNor() Expr' => ['addNor', [$this->getMockQueryExpr()]],
            'not()' => ['not', [$this->getMockQueryExpr()]],
            'language()' => ['language', ['en']],
            'text()' => ['text', ['foo']],
        ];
    }

    private function getStubStage()
    {
        return new MatchStub($this->getTestAggregationBuilder());
    }

    private function getMockGeometry()
    {
        return $this->getMockBuilder('GeoJson\Geometry\Geometry')
            ->disableOriginalConstructor()
            ->getMock();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package repo

import (
	"errors"
	"net/http"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/convert"
	api "code.gitea.io/gitea/modules/structs"
	"code.gitea.io/gitea/modules/web"
	"code.gitea.io/gitea/routers/api/v1/utils"
)

// ListCollaborators list a repository's collaborators
func ListCollaborators(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/collaborators repository repoListCollaborators
	// ---
	// summary: List a repository's collaborators
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: page
	//   in: query
	//   description: page number of results to return (1-based)
	//   type: integer
	// - name: limit
	//   in: query
	//   description: page size of results
	//   type: integer
	// responses:
	//   "200":
	//     "$ref": "#/responses/UserList"

	collaborators, err := ctx.Repo.Repository.GetCollaborators(utils.GetListOptions(ctx))
	if err != nil {
		ctx.Error(http.StatusInternalServerError, "ListCollaborators", err)
		return
	}
	users := make([]*api.User, len(collaborators))
	for i, collaborator := range collaborators {
		users[i] = convert.ToUser(collaborator.User, ctx.User)
	}
	ctx.JSON(http.StatusOK, users)
}

// IsCollaborator check if a user is a collaborator of a repository
func IsCollaborator(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/collaborators/{collaborator} repository repoCheckCollaborator
	// ---
	// summary: Check if a user is a collaborator of a repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: collaborator
	//   in: path
	//   description: username of the collaborator
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "404":
	//     "$ref": "#/responses/notFound"
	//   "422":
	//     "$ref": "#/responses/validationError"

	user, err := models.GetUserByName(ctx.Params(":collaborator"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Error(http.StatusUnprocessableEntity, "", err)
		} else {
			ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
		}
		return
	}
	isColab, err := ctx.Repo.Repository.IsCollaborator(user.ID)
	if err != nil {
		ctx.Error(http.StatusInternalServerError, "IsCollaborator", err)
		return
	}
	if isColab {
		ctx.Status(http.StatusNoContent)
	} else {
		ctx.NotFound()
	}
}

// AddCollaborator add a collaborator to a repository
func AddCollaborator(ctx *context.APIContext) {
	// swagger:operation PUT /repos/{owner}/{repo}/collaborators/{collaborator} repository repoAddCollaborator
	// ---
	// summary: Add a collaborator to a repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: collaborator
	//   in: path
	//   description: username of the collaborator to add
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/AddCollaboratorOption"
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "422":
	//     "$ref": "#/responses/validationError"

	form := web.GetForm(ctx).(*api.AddCollaboratorOption)

	collaborator, err := models.GetUserByName(ctx.Params(":collaborator"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Error(http.StatusUnprocessableEntity, "", err)
		} else {
			ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
		}
		return
	}

	if !collaborator.IsActive {
		ctx.Error(http.StatusInternalServerError, "InactiveCollaborator", errors.New("collaborator's account is inactive"))
		return
	}

	if err := ctx.Repo.Repository.AddCollaborator(collaborator); err != nil {
		ctx.Error(http.StatusInternalServerError, "AddCollaborator", err)
		return
	}

	if form.Permission != nil {
		if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil {
			ctx.Error(http.StatusInternalServerError, "ChangeCollaborationAccessMode", err)
			return
		}
	}

	ctx.Status(http.StatusNoContent)
}

// DeleteCollaborator delete a collaborator from a repository
func DeleteCollaborator(ctx *context.APIContext) {
	// swagger:operation DELETE /repos/{owner}/{repo}/collaborators/{collaborator} repository repoDeleteCollaborator
	// ---
	// summary: Delete a collaborator from a repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// - name: collaborator
	//   in: path
	//   description: username of the collaborator to delete
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "422":
	//     "$ref": "#/responses/validationError"

	collaborator, err := models.GetUserByName(ctx.Params(":collaborator"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Error(http.StatusUnprocessableEntity, "", err)
		} else {
			ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
		}
		return
	}

	if err := ctx.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil {
		ctx.Error(http.StatusInternalServerError, "DeleteCollaboration", err)
		return
	}
	ctx.Status(http.StatusNoContent)
}


text:
'use strict';

import { Command, normalizeError, createSocket, createUID, logger } from './utils';
import Settings from './settings';
import pluginConfig from './config';
import assign from 'object-assign';
import gutil from 'gulp-util';
import { EventEmitter } from 'events';
import util from 'util';

/**
 * Default configuration options for a sublime object
 * @return {Object}
 */
const defaultSettings = (function () {
	/**
	 * Whether or not to connect with the module is required
	 * @type {Boolean}
	 */
	const deferConnect = false;

	/**
	 * The maximum number of times the socket will try to
	 * reconnect to the server.
	 * @type {Number}
	 */
	const maxTries = 30;

	/**
	 * The default port to connect to the server.
	 * @type {Number}
	 */
	const port = 30048;

	/**
	 * The timeout before the next reconnect occurs.
	 * @type {Number}
	 */
	const reconnectTimeout = 2000;

	/**
	 * Whether or not to automatically reconnect after disconnecting.
	 * Note: Calling .disconnect() will cause the socket to remain
	 * disconnected, even if this option is set to true.
	 * @type {Boolean}
	 */
	const automaticReconnect = true;

	/**
	 * When true, messages will be logged to the console.
	 * @type {Boolean}
	 */
	const disableLogging = false;

	return Object.freeze({
		automaticReconnect,
		disableLogging,
		deferConnect,
		maxTries,
		port,
		reconnectTimeout,
	});
}());

const SublimeProto = {
	_connection: null,
	connected: false,

	/**
	* When set to true, the socket will remain disconnected
	* rather than trying to reconnect.
	* @type {Boolean}
	*/
	_remainDisconnected: false,

	/**
	* The number of times we have tried to reconnect.
	* @type {Number}
	*/
	_reconnectTries: 0,

	/**
	 * Reconnect to sublime server
	 *
	 * @param  {Function} onConnectHandler
	 * @return {void}
	 */
	_reconnect: function _reconnect() {
		this._reconnectTries++;

		if (this._reconnectTries > this.settings.get('maxTries')) {
			this.log('Max reconnect tries exceeded');
			return;
		}

		setTimeout(() => {
			this.connect();
		}, this.settings.get('reconnectTimeout'));
	},

	/**
	 * Creates a connection to the server. The previous socket will
	 * be disconnected.
	 *
	 * When connected, subsequent calls are ignored. The socket
	 * must be manually disconnected by calling .disconnect().
	 * @param  {Function} onConnect
	 * @return {void}
	 */
	connect: function connect(onConnect) {
		// Are we still trying to connect from the previous .connect() call?
		const connecting = (this._connection !== null && this._connection._connecting) ? true : false;
		const connected = (this._connection !== null && this._connection.connected) ? true : false;

		this.emit('connect:before');
		this._remainDisconnected = false;

		/**
		 * Handlers for the socket events.
		 * @type {Object}
		 */
		const socketEventHandlers = {
			/**
			 * Handle socket close event.
			 */
			close: () => {
				this.log('Disconnected');
				this._connection.connected = false;
				this.emit('disconnect');
			},
			/**
			 * Destroy the socket on error
			 */
			error: () => {
				this.log(gutil.colors.yellow('Socket error'));
				this._connection.destroy();
			},
			/**
			 * Sends a handshake on connect.
			 */
			connect: () => {
				this.log('Connected');
				this._connection.send({ id: `gulp#${pluginConfig.get('pluginID')}` }); // Send handshake
				this._connection.connected = true;
				this.emit('connect');

				if (typeof onConnect === 'function') {
					onConnect.call(this);
					onConnect = null;
				}
			},
			/**
			 * Handle when data is received
			 */
			data: (data) => {
				let received;

				try {
					received = JSON.parse(data.toString());
				} catch (err) {
					this.log('Error parsing socket data:', err);
				}

				this.emit('receive', received);
			}
		};

		if ( ! connected && ! connecting) {
			this._connection = createSocket({
				host: 'localhost',
				port: this.settings.get('port'),
				events: socketEventHandlers
			});
			this._connection.connected = false;
		}

		return this;
	},

	/**
	 * Disconnect the socket from the server.
	 * @param  {Function} onDisconnect
	 * @return {void}
	 */
	disconnect: function disconnect(onDisconnect) {
		const socket = this._connection;
		const listenerWrapper = () => {
			if (typeof onDisconnect === 'function') {
				onDisconnect.call(this);
				onDisconnect = null;
			}

			socket.removeListener('close', listenerWrapper);
		};

		this.emit('disconnect:before');
		this._remainDisconnected = true;

		if (this._connection) {
			this._connection.on('close', listenerWrapper);
			this._connection.destroy();
		}

		return this;
	},

	config: function (options={}) {
		const { gulp } = options;
		this.settings.set(options);

		if (util.isObject(gulp)) {
			gulp.removeListener('task_start', this.onGulpTaskStart);
			gulp.on('task_start', this.onGulpTaskStart);
		}

		return this;
	},

	/**
	 * Send a command to the server.
	 * @param  {Object} command
	 * @return {void}
	 */
	run: function run(command) {
		const connected = (this._connection !== null && this._connection.connected) ? true : false;
		const args_id = command.data.args.id;
		this.emit('run:before', assign({}, command));

		if ( ! connected) {
			return;
		}

		// Since the IDs are usually used to identify the regions, icons, etc,
		// IDs are prefixed with the id of the plugin to avoid collisions with
		// with other gulp files running.
		if (typeof args_id === 'string') {
			command.data.args.id = `${args_id}#${pluginConfig.get('pluginID')}`;
		}

		this._connection.send(command);
		this.emit('run', assign({}, command));

		return this;
	},

	/**
	 * Set a status message in Sublime
	 * @param  {String} id     The id of the status message
	 * @param  {String} status The message that will be shown
	 * @return {void}
	 */
	setStatus: function setStatus(id, status) {
		const args = { id, status };
		const init_args = { views: '<all>' };
		const command = Command({ name: 'set_status', args, init_args });
		this.run(command);

		return this;
	},

	/**
	 * Erase a status message in Sublime Text's status bar
	 * @param  {String} id The id of the status message
	 */
	eraseStatus: function eraseStatus(id) {
		const args = { id };
		const init_args = { views: '<all>' };
		const command = Command({ name: 'erase_status', args, init_args });
		this.run(command);

		return this;
	},

	/**
	 * Hide the gutters, highlighted text lines, and error status messages
	 * @param  {String} id The id of the status message to erase
	 * @return {void}
	 */
	eraseErrors: function eraseErrors(id) {
		if (typeof id !== 'string') {
			let err = new Error('The ID passed is not of type String');
			throw err;
		}

		const args = { id };
		const init_args = { views: '<all>' };
		const command = Command({ name: 'erase_errors', args, init_args });
		this.run(command);

		return this;
	},

	/**
	 * Runs the gulp command "show_error". The command will do several things
	 * based on if they have been enabled in the package settings.
	 *
	 * - Show a popup message in a view with the same open file that caused the error
	 * - Show a gutter icon next to the line the caused the error
	 * - Show an error message in the status bar
	 * - Scroll to the line where the error occured
	 *
	 * The base data needed in the error object is a file name and line number
	 *
	 * @param  {String} id   The id to associate with the status message
	 * @param  {Error}  err  The gulp error object
	 * @return {void}
	 */
	showError: function showError(err, id) {
		if (typeof id !== 'string') {
			let err = new Error('The ID passed is not of type String');
			throw err;
		}

		const error = normalizeError(err, id);
		const args = { id, error };
		const init_args = { views: [error.file] };
		const command = Command({ name: 'show_error', args, init_args });
		this.run(command);

		return this;
	},

	/**
	 * Removes the errors associated with the task each time
	 * the task starts.
	 * @param  {Object} task
	 * @return {void}
	 */
	onGulpTaskStart: function (task) {
		this.eraseErrors(task.task);
	},
};

// Turn sublime into an event emitter
assign(SublimeProto, EventEmitter.prototype);

/**
 * Creates a sublime object
 * @return {Object}
 */
function Sublime(options={}) {
	const result = Object.create(SublimeProto);

	const settings = Settings({
		defaults: defaultSettings,
		validations: {
			deferConnect: util.isBoolean,
			disableLogging: util.isBoolean,
			automaticReconnect: util.isBoolean,
			reconnectTimeout: Number.isFinite,
			port: Number.isFinite,
			maxTries: Number.isFinite,
		},
	});

	settings.set(assign({}, options));
	settings.on('change', onSettingsChange);

	EventEmitter.call(result);

	result.on('connect', onSublimeConnect);
	result.on('disconnect', onSublimeDisconnect);
	result.on('receive', onDataReceived);

	result.onGulpTaskStart = result.onGulpTaskStart.bind(result);
	result.settings = settings;
	result.log = logger(pluginConfig.get('pluginName'), settings);

	Object.defineProperty(result, 'constructor', { value: Sublime });

	return result;
}

Sublime.prototype = SublimeProto;

function onSettingsChange(data) {
	var validations = data.validations;
	var failedValidationNames = Object.keys(validations)
		.filter(name => validations[name] === false)
		.map(name => "'" + name + "'" )

	if (failedValidationNames.length) {
		console.log('Invalid settings were specified for', failedValidationNames.join(', '))
	}
}

/**
 * Reset the reconnection tries
 * @return {void}
 */
function onSublimeConnect() {
	this._reconnectTries = 0;
}

/**
 * Determine whether or not to reconnect
 * @return {void}
 */
function onSublimeDisconnect() {
	const automaticReconnect = this.settings.get('automaticReconnect');

	if (automaticReconnect && ! this._remainDisconnected) {
		this._reconnect();
	}
}

const receiveLogger = logger('Sublime');

function onDataReceived(data) {
	if ( ! this.settings.get('disableLogging')) {
		receiveLogger(data);
	}

	if (data.handshake) {
		this._connection.shaken = true;;
	}
}

const sublime = Sublime();

/**
 * Determine whether or not to defer connecting
 */
setTimeout(function () {
	if (sublime.settings.get('deferConnect') === false) {
		sublime.connect();
	}
}, 100);

export default sublime;


text:
/*jslint node:true es5:true nomen:true*/
/* console*/

"use strict";

var gulp = require('gulp'),
  mainBowerFiles = require('main-bower-files'),
  minify = require('gulp-cssnano'),
  uglify = require('gulp-uglify'),

  baseDir = "./",
  images = ['./images/*'],
  main = ['./*.html', './manifest.json'],
  styles = ['./styles/*.css'],
  scripts = ['./js/*.js'],
  dest = "./public";

function onError(err) {
  console.log(err);
}

gulp.task('Copy_Images', function () {
  return gulp.src(images)
    .pipe(gulp.dest(dest));
});

gulp.task('Copy_Styles', function () {
  return gulp.src(styles)
    .pipe(minify())
    .pipe(gulp.dest(dest));
});

gulp.task('Copy_Scripts', function () {
  return gulp.src(scripts)
    .pipe(uglify())
    .pipe(gulp.dest(dest));
});

gulp.task('Copy_Main_Files', function () {
  return gulp.src(main)
    .pipe(gulp.dest(dest));
});

gulp.task('Copy_Bower_Files', function () {
  return gulp.src(mainBowerFiles())
    .pipe(uglify())
    .pipe(gulp.dest(dest));
});

var tasklist = [];
tasklist.push('Copy_Images');
tasklist.push('Copy_Styles');
tasklist.push('Copy_Scripts');
tasklist.push('Copy_Main_Files');
tasklist.push('Copy_Bower_Files');

gulp.task('default', tasklist, function () {
  console.log("Done.");
}).on('error', onError);


text:
(function () {
  'use strict';
  var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  var atob = require('atob');
  const es_host = process.env.REPORTS_ES_HOST;

  function getSync(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, false);
    request.send(null);

    return [request.status, JSON.parse(request.responseText), {}];
  };

  function DownloadService() {
    var pub = {};

    pub.downloadFile = function(id, reply) {

      var file_url = (['http:/',es_host,'reports/document',id]).join('/');

      var data = getSync(file_url)[1];
      var report_content = data._source.report_content;
      //response(data);

      var response = reply(atob(report_content._content)).hold();
      var header = response.header('Content-Type', report_content._content_type).header('Content-Disposition', 'attachment; filename=' + report_content._name);
      response.send();

    };

    return pub;
  }

  module.exports = DownloadService;
})();


text:
% This is another file
\begin{center}
Hello from another file.
\end{center}


text:
package com.hubspot.jackson.datatype.protobuf;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;

import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;

public class FailOnNumbersForEnumsTest {

  @Test(expected = JsonMappingException.class)
  public void testEnabled() throws JsonProcessingException {
    ObjectMapper mapper = objectMapper(true);

    mapper.treeToValue(buildNode(), AllFields.class);
  }

  @Test
  public void testDisabled() throws JsonProcessingException {
    ObjectMapper mapper = objectMapper(false);

    AllFields parsed = mapper.treeToValue(buildNode(), AllFields.class);
    assertThat(parsed.hasEnum()).isTrue();
    assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
  }

  private static JsonNode buildNode() {
    return camelCase().createObjectNode().put("enum", 2);
  }

  private static ObjectMapper objectMapper(boolean enabled) {
    if (enabled) {
      return camelCase().enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
    } else {
      return camelCase().disable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
    }
  }
}


text:
using Newtonsoft.Json;

namespace Auth0.Core
{

    /// <summary>
    ///
    /// </summary>
    public class EncryptionKey
    {

        /// <summary>
        /// Encryption public key
        /// </summary>
        [JsonProperty("pub")]
        public string PublicKey { get; set; }

        /// <summary>
        /// Encryption certificate
        /// </summary>
        [JsonProperty("cert")]
        public string Certificate { get; set; }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datafactory.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.datafactory.fluent.models.HDInsightSparkActivityTypeProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;
import java.util.Map;

/** HDInsight Spark activity. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("HDInsightSpark")
@Fluent
public final class HDInsightSparkActivity extends ExecutionActivity {
    /*
     * HDInsight spark activity properties.
     */
    @JsonProperty(value = "typeProperties", required = true)
    private HDInsightSparkActivityTypeProperties innerTypeProperties = new HDInsightSparkActivityTypeProperties();

    /** Creates an instance of HDInsightSparkActivity class. */
    public HDInsightSparkActivity() {
    }

    /**
     * Get the innerTypeProperties property: HDInsight spark activity properties.
     *
     * @return the innerTypeProperties value.
     */
    private HDInsightSparkActivityTypeProperties innerTypeProperties() {
        return this.innerTypeProperties;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withLinkedServiceName(LinkedServiceReference linkedServiceName) {
        super.withLinkedServiceName(linkedServiceName);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withPolicy(ActivityPolicy policy) {
        super.withPolicy(policy);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withName(String name) {
        super.withName(name);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withDescription(String description) {
        super.withDescription(description);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withDependsOn(List<ActivityDependency> dependsOn) {
        super.withDependsOn(dependsOn);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public HDInsightSparkActivity withUserProperties(List<UserProperty> userProperties) {
        super.withUserProperties(userProperties);
        return this;
    }

    /**
     * Get the rootPath property: The root path in 'sparkJobLinkedService' for all the job's files. Type: string (or
     * Expression with resultType string).
     *
     * @return the rootPath value.
     */
    public Object rootPath() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().rootPath();
    }

    /**
     * Set the rootPath property: The root path in 'sparkJobLinkedService' for all the job's files. Type: string (or
     * Expression with resultType string).
     *
     * @param rootPath the rootPath value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withRootPath(Object rootPath) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withRootPath(rootPath);
        return this;
    }

    /**
     * Get the entryFilePath property: The relative path to the root folder of the code/package to be executed. Type:
     * string (or Expression with resultType string).
     *
     * @return the entryFilePath value.
     */
    public Object entryFilePath() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().entryFilePath();
    }

    /**
     * Set the entryFilePath property: The relative path to the root folder of the code/package to be executed. Type:
     * string (or Expression with resultType string).
     *
     * @param entryFilePath the entryFilePath value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withEntryFilePath(Object entryFilePath) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withEntryFilePath(entryFilePath);
        return this;
    }

    /**
     * Get the arguments property: The user-specified arguments to HDInsightSparkActivity.
     *
     * @return the arguments value.
     */
    public List<Object> arguments() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().arguments();
    }

    /**
     * Set the arguments property: The user-specified arguments to HDInsightSparkActivity.
     *
     * @param arguments the arguments value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withArguments(List<Object> arguments) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withArguments(arguments);
        return this;
    }

    /**
     * Get the getDebugInfo property: Debug info option.
     *
     * @return the getDebugInfo value.
     */
    public HDInsightActivityDebugInfoOption getDebugInfo() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().getDebugInfo();
    }

    /**
     * Set the getDebugInfo property: Debug info option.
     *
     * @param getDebugInfo the getDebugInfo value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withGetDebugInfo(HDInsightActivityDebugInfoOption getDebugInfo) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withGetDebugInfo(getDebugInfo);
        return this;
    }

    /**
     * Get the sparkJobLinkedService property: The storage linked service for uploading the entry file and dependencies,
     * and for receiving logs.
     *
     * @return the sparkJobLinkedService value.
     */
    public LinkedServiceReference sparkJobLinkedService() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().sparkJobLinkedService();
    }

    /**
     * Set the sparkJobLinkedService property: The storage linked service for uploading the entry file and dependencies,
     * and for receiving logs.
     *
     * @param sparkJobLinkedService the sparkJobLinkedService value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withSparkJobLinkedService(LinkedServiceReference sparkJobLinkedService) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withSparkJobLinkedService(sparkJobLinkedService);
        return this;
    }

    /**
     * Get the className property: The application's Java/Spark main class.
     *
     * @return the className value.
     */
    public String className() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().className();
    }

    /**
     * Set the className property: The application's Java/Spark main class.
     *
     * @param className the className value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withClassName(String className) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withClassName(className);
        return this;
    }

    /**
     * Get the proxyUser property: The user to impersonate that will execute the job. Type: string (or Expression with
     * resultType string).
     *
     * @return the proxyUser value.
     */
    public Object proxyUser() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().proxyUser();
    }

    /**
     * Set the proxyUser property: The user to impersonate that will execute the job. Type: string (or Expression with
     * resultType string).
     *
     * @param proxyUser the proxyUser value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withProxyUser(Object proxyUser) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withProxyUser(proxyUser);
        return this;
    }

    /**
     * Get the sparkConfig property: Spark configuration property.
     *
     * @return the sparkConfig value.
     */
    public Map<String, Object> sparkConfig() {
        return this.innerTypeProperties() == null ? null : this.innerTypeProperties().sparkConfig();
    }

    /**
     * Set the sparkConfig property: Spark configuration property.
     *
     * @param sparkConfig the sparkConfig value to set.
     * @return the HDInsightSparkActivity object itself.
     */
    public HDInsightSparkActivity withSparkConfig(Map<String, Object> sparkConfig) {
        if (this.innerTypeProperties() == null) {
            this.innerTypeProperties = new HDInsightSparkActivityTypeProperties();
        }
        this.innerTypeProperties().withSparkConfig(sparkConfig);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (innerTypeProperties() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property innerTypeProperties in model HDInsightSparkActivity"));
        } else {
            innerTypeProperties().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(HDInsightSparkActivity.class);
}


text:
import base64

import ldap
from ldap import filter as ldap_filter

from keystone import config
from keystone import exception
from keystone import identity
from keystone.common import ldap as common_ldap
from keystone.common import sql
from keystone.common import utils
from keystone.common.ldap import fakeldap
from keystone.identity import models
from keystone.identity.backends import sql as backends_sql
from keystone.identity.backends import ldap as backends_ldap

CONF = config.CONF

def _filter_user(user_ref):
    if user_ref:
        user_ref.pop('password', None)
    return user_ref

class LdapUser(models.User):
    optional_keys = models.User.optional_keys + ('fullName', 'memberOf')

class UserApi(common_ldap.BaseLdap):
    LDAP_TYPE_UNKNOWN = 0
    LDAP_TYPE_RFC_2307 = 1
    LDAP_TYPE_ACTIVE_DIRECTORY = 2
    LDAP_CAP_ACTIVE_DIRECTORY_OID = "1.2.840.113556.1.4.800"

    DEFAULT_OU = 'ou=Users'
    DEFAULT_STRUCTURAL_CLASSES = ['person']
    DEFAULT_ID_ATTRIBUTE = 'cn'
    DEFAULT_OBJECTCLASS = 'inetOrgPerson'
    group_tree_dn = None
    options_name = 'user'
    attribute_mapping = {
        'email': 'mail',
        'name': 'cn',
        'fullName': 'cn',
    }
    ldap_type = LDAP_TYPE_UNKNOWN

    # NOTE(ayoung): The RFC based schemas don't have a way to indicate
    # 'enabled' the closest is the nsAccount lock, which is on defined to
    # be part of any objectclass.
    # in the future, we need to provide a way for the end user to
    # indicate the field to use and what it indicates
    # NOTE(aababilov): use userAccountControl field to set enabled = False
    attribute_ignore = ['tenant_id', 'enabled', 'tenants']
    model = LdapUser

    def __init__(self, conf):
        super(UserApi, self).__init__(conf)
        attr_conf = "group_tree_dn"
        attr_val = getattr(conf.ldap, attr_conf, None)
        if attr_val:
            self.group_tree_dn = attr_val
        for attr_name in self.attribute_mapping:
            attr_conf = "%s_%s_attribute" % (self.options_name, attr_name)
            attr_val = getattr(conf.ldap, attr_conf, None)
            if attr_val:
                self.attribute_mapping[attr_name] = attr_val

    def get_connection(self, user=None, password=None):
        conn = super(UserApi, self).get_connection(user, password)
        if self.ldap_type == UserApi.LDAP_TYPE_UNKNOWN:
            root_attrs = conn.search_s(
                "", ldap.SCOPE_BASE, "(objectClass=*)")[0][1]
            self.ldap_type = (UserApi.LDAP_TYPE_ACTIVE_DIRECTORY
                              if (UserApi.LDAP_CAP_ACTIVE_DIRECTORY_OID in
                                  root_attrs.get("supportedCapabilities", []))
                              else
                              UserApi.LDAP_TYPE_RFC_2307)
        return conn

    def get_by_name(self, name, filter=None):
        users = self.get_all("(%s=%s)" %
                             (self.attribute_mapping["name"],
                              ldap_filter.escape_filter_chars(name)))
        try:
            return users[0]
        except IndexError:
            return None

    def _id_to_dn(self, id):
        return "%s=%s,%s" % (
            self.id_attr,
            ldap.dn.escape_dn_chars(
                base64.urlsafe_b64decode(str(id))),
            self.tree_dn)

    @staticmethod
    def _dn_to_id(dn):
        return base64.urlsafe_b64encode(ldap.dn.str2dn(dn)[0][0][1])

    def _ldap_res_to_model(self, res):
        obj = super(UserApi, self)._ldap_res_to_model(res)
        try:
            obj["enabled"] = (res[1]["userAccountControl"][0] & 2) == 0
        except (KeyError, IndexError):
            pass
        # return memberOf only for Active Directory
        # since for RFC 2307 it will be slow
        if self.ldap_type == UserApi.LDAP_TYPE_ACTIVE_DIRECTORY:
            obj["memberOf"] = self._user_groups(res)
        return obj

    def _user_groups(self, user_ldap):
        if self.ldap_type == UserApi.LDAP_TYPE_ACTIVE_DIRECTORY:
            try:
                return [x.split(",", 1)[0][3:]
                        for x in user_ldap[1]["memberOf"]]
            except (IndexError, KeyError):
                return []
        # for RFC 2307 we need a lookup
        if self.group_tree_dn:
            conn = self.get_connection()
            groups = conn.search_s(self.group_tree_dn,
                                   ldap.SCOPE_ONELEVEL,
                                   "(memberUid=%s)" % user_ldap[1]["uid"][0])
            return [g[1]["cn"][0] for g in groups]
        return []

for attr_name in UserApi.attribute_mapping:
    config.register_str(
        "%s_%s_attribute" % (UserApi.options_name, attr_name),
        group="ldap")
# name of systenant
config.register_str("systenant", group="ldap", default="systenant")
# root of the tree containing all group records
config.register_str("group_tree_dn", group="ldap")

class Identity(backends_sql.Identity):
    def __init__(self):
        super(Identity, self).__init__()
        self.LDAP_URL = CONF.ldap.url
        self.LDAP_USER = CONF.ldap.user
        self.LDAP_PASSWORD = CONF.ldap.password
        self.suffix = CONF.ldap.suffix
        self.systenant = getattr(CONF.ldap, "systenant", "systenant")

        self.user = UserApi(CONF)

    def _user_is_in_tenant(self, user_id, user_ldap, tenant_ref):
        users = set(tenant_ref.get("users") or [])
        try:
            if set(user_ldap[1][self.user.attribute_mapping["name"]]) & users:
                return True
        except (KeyError, IndexError):
            pass
        groups = set(tenant_ref.get("groups") or [])
        if set(self.user._user_groups(user_ldap)) & groups:
            return True
        return False

    def _get_metadata_ref(self, tenant_ref):
        return {
            "roles": [
                "Admin" if tenant_ref["name"] == self.systenant else "Member"
            ]
        }

    # Identity interface
    def authenticate(self, user_id=None, tenant_id=None, password=None):
        """Authenticate based on a user, tenant and password.

        Expects the user object to have a password field and the tenant to be
        in the list of tenants on the user.
        """
        user_ldap = self.user._ldap_get(user_id)
        if user_ldap is None:
            raise AssertionError('Invalid user / password')

        user_ref = self.user._ldap_res_to_model(user_ldap)
        try:
            conn = self.user.get_connection(self.user._id_to_dn(user_id),
                                            password)
            if not conn:
                raise AssertionError('Invalid user / password')
        except Exception:
            raise AssertionError('Invalid user / password')

        if tenant_id:
            tenant_ref = self.get_tenant(tenant_id)
            if not tenant_ref:
                raise AssertionError('Invalid tenant')

            if not self._user_is_in_tenant(user_id, user_ldap, tenant_ref):
                raise AssertionError('Invalid tenant')
            metadata_ref = self._get_metadata_ref(tenant_ref)
        else:
            tenant_ref = None
            metadata_ref = {}
        return  (_filter_user(user_ref), tenant_ref, metadata_ref)

    # def get_tenant(self, tenant_id):
    # inherited

    # def get_tenant_by_name(self, tenant_name):
    # inherited

    def _get_user(self, user_id):
        user_ref = self.user.get(user_id)
        if not user_ref:
            return None
        return user_ref

    def get_user(self, user_id):
        user_ref = self._get_user(user_id)
        if (not user_ref):
            return None
        return _filter_user(user_ref)

    def get_user_by_name(self, user_name):
        """Get a user by name.

        Returns: user_ref or None.

        """
        user_ref = self.user.get_by_name(user_name)
        if not user_ref:
            return None
        return _filter_user(user_ref)

    def get_role(self, role_id):
        """Get a role by id.

        Returns: role_ref or None.

        """
        if role_id in ("Admin", "Member"):
            return {"id": role_id, "name": role_id}
        return None

    def list_users(self):
        """List all users in the system.

        NOTE(termie): I'd prefer if this listed only the users for a given
                      tenant.

        Returns: a list of user_refs or an empty list.

        """
        return self.user.get_all()

    def list_roles(self):
        """List all roles in the system.

        Returns: a list of role_refs or an empty list.

        """
        return [{"id": role_id, "name": role_id}
                for role_id in ("Admin", "Member")]

    def add_user_to_tenant(self, tenant_id, user_id):
        raise exception.NotImplemented()

    def remove_user_from_tenant(self, tenant_id, user_id):
        raise exception.NotImplemented()

    def get_all_tenants(self):
        return self.get_tenants()

    def get_tenants_for_user(self, user_id):
        """Get the tenants associated with a given user.

        Returns: a list of tenant ids.

        """
        user_ldap = self.user._ldap_get(user_id)
        if user_ldap is None:
            return []
        return [tenant_ref["id"]
                for tenant_ref in self.get_all_tenants()
                if self._user_is_in_tenant(user_id, user_ldap, tenant_ref)]

    # def get_roles_for_user_and_tenant(self, user_id, tenant_id):
    # inherited (calls our overriden get_metadata)

    def add_role_to_user_and_tenant(self, user_id, tenant_id, role_id):
        """Add a role to a user within given tenant."""
        raise exception.NotImplemented()

    def remove_role_from_user_and_tenant(self, user_id, tenant_id, role_id):
        """Remove a role from a user within given tenant."""
        raise exception.NotImplemented()

    # user crud
    def create_user(self, user_id, user):
        raise exception.NotImplemented()

    def update_user(self, user_id, user):
        raise exception.NotImplemented()

    def delete_user(self, user_id):
        raise exception.NotImplemented()

    # tenant crud
    # def create_tenant(self, tenant_id, tenant):
    # def update_tenant(self, tenant_id, tenant):
    # def delete_tenant(self, tenant_id, tenant):
    # inherited

    # metadata crud

    def get_metadata(self, user_id, tenant_id):
        tenant_ref = self.get_tenant(tenant_id)
        if not tenant_ref:
            return []
        user_ldap = self.user._ldap_get(user_id)
        if user_ldap is None:
            return []
        if not self._user_is_in_tenant(user_id, user_ldap, tenant_ref):
            return []
        return self._get_metadata_ref(tenant_ref)

    def create_metadata(self, user_id, tenant_id, metadata):
        raise exception.NotImplemented()

    def update_metadata(self, user_id, tenant_id, metadata):
        raise exception.NotImplemented()

    def delete_metadata(self, user_id, tenant_id, metadata):
        raise exception.NotImplemented()

    # role crud
    def create_role(self, role_id, role):
        raise exception.NotImplemented()

    def update_role(self, role_id, role):
        raise exception.NotImplemented()

    def delete_role(self, role_id):
        raise exception.NotImplemented()


text:
namespace bond { namespace ext { namespace [[deprecated("Bond-over-gRPC will be removed in the next major version of Bond. See https://github.com/microsoft/bond/issues/1131")]] grpc { namespace reflection {

/// @brief Method description in compile-time schema
template <
    typename Service,
    typename Input,
    typename Result,
    const Metadata* metadata_ptr>
struct MethodTemplate
{
    /// @brief Type of the service
    typedef Service service_type;

    /// @brief Type of the request
    typedef Input input_type;

    /// @brief Type of the response
    typedef Result result_type;

    /// @brief Static data member describing method metadata
    static const Metadata& metadata;
};

template <
    typename Service,
    typename Input,
    typename Result,
    const bond::Metadata* metadata_ptr>
const bond::Metadata&
    MethodTemplate<Service, Input, Result, metadata_ptr>::metadata = *metadata_ptr;

} } } } // namespace bond::ext::grpc::reflection


text:
import Model, { attr } from "@ember-data/model";
import { getOwner } from "@ember/application";
import FieldInformationService from "@getflights/ember-field-components/services/field-information";
// @ts-ignore
import { fragment } from "ember-data-model-fragments/attributes";

export function field(type: string, options?: any) {
  if (type === "address" || type === "geolocation") {
    return fragment(...arguments);
  } else {
    if (type === "currency") {
      if (!options) {
        options = {};
      }

      options.defaultValue = (model: Model) => {
        const fieldInformation: FieldInformationService = getOwner(
          model
        ).lookup("service:field-information");
        return fieldInformation.defaultCurrency;
      };
    }

    return attr(type, options);
  }
}


text:
[Resque](https://github.com/resque/resque) is a Redis-backed library for creating background jobs, placing
those jobs on one or more queues, and processing them later.

This is a PHP fork of the Resque worker and job classes. This makes it compatible with the
resque-web interface, and with other Resque libraries. (You could enqueue jobs from Ruby and dequeue
them in PHP, for instance).

This is a fork of the library [vend/resque](https://github.com/vend/resque) which is a fork of [chrisboulton/php-resque](https://github.com/chrisboulton/php-resque) at around
version 1.3, that has been refactored to remove global state, add namespacing, and improve
decoupling. This makes it easier to use and extend.

## Getting Started

Add `innogames/php-resque` to your application's composer.json.

```json
{
    "require": {
        "innogames/php-resque": "master"
    }
}
```

## Requirements

* PHP 7.3+ (incl. PHP 8)
* A Redis client library (for instance, [Predis](https://github.com/nrk/predis) or [Credis](https://github.com/colinmollenhour/credis))
* The PHP pcntl extension for proper forking is recommended (not available under Windows) but it still runs without it

## Jobs

### Queueing Jobs

Jobs are queued as follows:

```php
use Resque\Resque;
use Predis\Client;

$resque = new Resque(new Client());
$resque->enqueue('default_queue', 'App\Job', array('foo' => 'bar'), true);
```

In order the arguments are: queue, job class, job payload, whether to enable tracking.

### Defining Jobs

Each job should be in its own class, and implement the `Resque\JobInterface`. (This is pretty easy,
and only really requires a single custom method: `perform()`.) Most of the time, you'll want to
use the default implementation of a Job, and extend the `Resque\AbstractJob` instead of implementing
the interface yourself:

```php
namespace App;

use Resque\AbstractJob;

class Job extends AbstractJob
{
    public function perform()
    {
        // work work work
        $this->doSomething($this->payload['foo']);
    }
}
```

Any exception thrown by a job will result in the job failing - be
careful here and make sure you handle the exceptions that shouldn't
result in a job failing.

### Job Status Tracking

vend/resque has the ability to perform basic status tracking of a queued
job. The status information will allow you to check if a job is in the
queue, is currently being run, has finished, or has failed.

To track the status of a job, pass `true` as the fourth argument to
`Resque\Resque::enqueue`. An ID used for tracking the job status will be
returned:

```php
$id = $resque->enqueue('default_queue', 'App\Job', $payload, true);
echo $id; // [0-9a-f]{32}
```

To fetch the status of a job:

```php
$factory = new Resque\Job\StatusFactory($resque);

// Pass the ID returned from enqueue
$status = $factory->getForId($id);

// Alternatively, to get the status for a Job instance:
$status = $factory->getForJob($job);

// Outputs the status as a string: 'waiting', 'running', 'complete', etc.
echo $status->getStatus();
```

The Status object contains methods for adding other attributes to the
tracked status. (For instance, you might use the status object to track
errors, completion information, iterations, etc.)

#### Statuses

Job statuses are defined as constants in the `Resque\Job\Status` class.
Valid statuses include:

* `Resque\Job\Status::STATUS_WAITING` - Job is still queued
* `Resque\Job\Status::STATUS_RUNNING` - Job is currently running
* `Resque\Job\Status::STATUS_FAILED` - Job has failed
* `Resque\Job\Status::STATUS_COMPLETE` - Job is complete

Statuses are available for up to 24 hours after a job has completed
or failed, and are then automatically expired. A status can also
forcefully be expired by calling the `stop()` method on a status
class.

## Console

You are free you implement your own daemonization/worker pool strategy by
subclassing the `Worker` class. For playing around, and low throughput
applications, you might like to use the built-in console commands.

This version of the library uses the Symfony2 Console component. But it
must be configured with the details of your Redis connection. We do this
in much the same way that the Doctrine2 Console component gets details
of your database connection: via a `cli-config.php` file.

There is an example `cli-config.php` in this repository.

If you're running a full-stack web application, you'd generally use your
locator/service container to fill in the Redis client connection in this
file. (The default is to use Predis, and to connect to 127.0.0.1:6379).

### Basic Usage

```
resque <subcommand>

Available commands:
  enqueue       Enqueues a job into a queue
  help          Displays help for a command
  list          Lists commands
  worker        Runs a Resque worker
queue
  queue:clear   Clears a specified queue
  queue:list    Outputs information about queues
```

### Enqueueing

This command will enqueue a `Some\Test\Job` job onto the `default` queue.
Watch out for the single quotes around the class name: when specifying backslashes
on the command line, you'll probably have to avoid your shell escaping them.

```
resque enqueue default 'Some\Test\Job' -t
```

### Worker

This command will run a simple pre-forking worker on two queues:

```
resque worker -Q default -Q some_other_queue
```

(`-q` means quiet, `-Q` specifies queues). You can also specify no queues, or
the special queue `'*'` (watch for shell expansion).

### Queue Information

There are a couple of useful commands for getting information about the queues. This
will show a list of queues and how many jobs are waiting on each:

```
resque queue:list
```

This command will clear a specified queue:

```
resque queue:clear default
```

### Logging

The library now uses PSR3. When running as a console component, you can customise
the logger to use in `cli-config.php`. (For instance, you might like to send your
worker logs to Monolog.)

## Why Fork?

Unfortunately, several things about the existing versions of php-resque made it
a candidate for refactoring:

* php-resque supported the Credis connection library and had hard-coded this
  support by using static accessors. This meant more advanced features such as
  replication and pipelining were unavailable.
  * Now, Resque for PHP supports any client object that implements a suitable
    subset of Redis commands.  No type-checking is done on the passed in connection,
    meaning you're free to use Predis, or whatever you like.
* While the public API of `php-resque` was alright, the protected API was pretty
  much useless. This made it hard to extend worker classes to dispatch jobs differently.
* Important state (the underlying connection) was thrown into the global scope
  by hiding it behind static accessors (`Resque::redis()`). This makes things
  easier for the library author (because he/she need not think about dependencies)
  but also statically ties together the classes in the library: it makes
  testing and extending the library hard.
  * There's no reason to do this: `Resque` instances should simply use DI and
    take a client connection as a required constructor argument.
  * This improvement also allows the connection to be mocked without extending
    the `Resque` class.
  * And it lets you reuse your existing connection to Redis, if you have one.
    No need to open a new connection just to enqueue a job.
* Statistic classes were static for no good reason.
  * To work, statistics need a connection to Redis, a name, and several methods
    (get, set). State and methods to manipulate it? Sounds like a task for
    objects! *Not* just static methods, that don't encapsulate any of the state.
  * Because these were static calls, the `Resque_Stat` class was hard-coded into
    several other classes, and could not be easily extended.
* The library is now fully namespaced and compatible with PSR-0. The top level
    namespace is `Resque`.
* The events system has been removed. There is now little need for it.
  It seems like the events system was just a workaround due to the poor
  extensibility of the Worker class. The library should allow you to extend any
  class you like, and no method should be too long or arduous to move into a
  subclass.

## Contributors ##

see [chrisboulton/php-resque](https://github.com/chrisboulton/php-resque) and [vend/resque](https://github.com/vend/resque) for the original contributor lists.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using AecCloud.BaseCore;
using Microsoft.AspNet.Identity;

namespace DBWorld.AecCloud.Web.Api
{
    public abstract class BaseApiController : ApiController
    {
        /// <summary>
        /// 端口映射可能会有问题
        /// </summary>
        /// <returns></returns>
        protected internal string GetHost()
        {
            return Utility.GetHost(Request.RequestUri);
        }

        protected internal long GetUserId()
        {
            return User.Identity.GetUserId<long>();
        }

        protected internal string GetUserName()
        {
            return User.Identity.GetUserName();
        }
    }
}


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

<title>DOMImplementation (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="org.w3c.dom.DOMImplementation interface">
<meta name="keywords" content="hasFeature()">
<meta name="keywords" content="createDocumentType()">
<meta name="keywords" content="createDocument()">
<meta name="keywords" content="getFeature()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.w3c.dom

Interface DOMImplementation

public interface DOMImplementation

The DOMImplementation interface provides a number of methods
 for performing operations that are independent of any particular instance
 of the document object model.

See also the Document Object Model (DOM) Level 3 Core Specification.

Method Summary

Methods

Modifier and Type
Method and Description

Document
createDocument(String namespaceURI,
              String qualifiedName,
              DocumentType doctype)

Creates a DOM Document object of the specified type with its document
 element.

DocumentType
createDocumentType(String qualifiedName,
                  String publicId,
                  String systemId)

Creates an empty DocumentType node.

Object
getFeature(String feature,
          String version)

This method returns a specialized object which implements the
 specialized APIs of the specified feature and version, as specified
 in DOM Features.

boolean
hasFeature(String feature,
          String version)

Test if the DOM implementation implements a specific feature and
 version, as specified in DOM Features.

Method Detail

hasFeature

boolean hasFeature(String feature,
                 String version)

Test if the DOM implementation implements a specific feature and
 version, as specified in DOM Features.

Parameters:

feature - The name of the feature to test.

version - This is the version number of the feature to test.

Returns:

true if the feature is implemented in the
   specified version, false otherwise.

createDocumentType

DocumentType createDocumentType(String qualifiedName,
                              String publicId,
                              String systemId)
                                throws DOMException

Creates an empty DocumentType node. Entity declarations
 and notations are not made available. Entity reference expansions and
 default attribute additions do not occur..

Parameters:

qualifiedName - The qualified name of the document type to be
   created.

publicId - The external subset public identifier.

systemId - The external subset system identifier.

Returns:

A new DocumentType node with
   Node.ownerDocument set to null.

Throws:

DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name is not
   an XML name according to [XML 1.0].

NAMESPACE_ERR: Raised if the qualifiedName is
   malformed.

NOT_SUPPORTED_ERR: May be raised if the implementation does not
   support the feature "XML" and the language exposed through the
   Document does not support XML Namespaces (such as [HTML 4.01]).

Since:

DOM Level 2

createDocument

Document createDocument(String namespaceURI,
                      String qualifiedName,
                      DocumentType doctype)
                        throws DOMException

Creates a DOM Document object of the specified type with its document
 element.

Note that based on the DocumentType given to create
 the document, the implementation may instantiate specialized
 Document objects that support additional features than
 the "Core", such as "HTML" [DOM Level 2 HTML]
 . On the other hand, setting the DocumentType after the
 document was created makes this very unlikely to happen.
 Alternatively, specialized Document creation methods,
 such as createHTMLDocument [DOM Level 2 HTML]
 , can be used to obtain specific types of Document
 objects.

Parameters:

namespaceURI - The namespace URI of the document element to
   create or null.

qualifiedName - The qualified name of the document element to be
   created or null.

doctype - The type of document to be created or null.
   When doctype is not null, its
   Node.ownerDocument attribute is set to the document
   being created.

Returns:

A new Document object with its document element.
   If the NamespaceURI, qualifiedName, and
   doctype are null, the returned
   Document is empty with no document element.

Throws:

DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name is not
   an XML name according to [XML 1.0].

NAMESPACE_ERR: Raised if the qualifiedName is
   malformed, if the qualifiedName has a prefix and the
   namespaceURI is null, or if the
   qualifiedName is null and the
   namespaceURI is different from null, or
   if the qualifiedName has a prefix that is "xml" and
   the namespaceURI is different from "
   http://www.w3.org/XML/1998/namespace" [XML Namespaces]
   , or if the DOM implementation does not support the
   "XML" feature but a non-null namespace URI was
   provided, since namespaces were defined by XML.

WRONG_DOCUMENT_ERR: Raised if doctype has already
   been used with a different document or was created from a different
   implementation.

NOT_SUPPORTED_ERR: May be raised if the implementation does not
   support the feature "XML" and the language exposed through the
   Document does not support XML Namespaces (such as [HTML 4.01]).

Since:

DOM Level 2

getFeature

Object getFeature(String feature,
                String version)

This method returns a specialized object which implements the
 specialized APIs of the specified feature and version, as specified
 in DOM Features. The specialized object may also be obtained by using
 binding-specific casting methods but is not necessarily expected to,
 as discussed in . This method also allow the implementation to
 provide specialized objects which do not support the
 DOMImplementation interface.

Parameters:

feature - The name of the feature requested. Note that any plus
   sign "+" prepended to the name of the feature will be ignored since
   it is not significant in the context of this method.

version - This is the version number of the feature to test.

Returns:

Returns an object which implements the specialized APIs of
   the specified feature and version, if any, or null if
   there is no object which implements interfaces associated with that
   feature. If the DOMObject returned by this method
   implements the DOMImplementation interface, it must
   delegate to the primary core DOMImplementation and not
   return results inconsistent with the primary core
   DOMImplementation such as hasFeature,
   getFeature, etc.

Since:

DOM Level 3

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
require 'omniauth'
require 'omniauth-twitter'
require 'omniauth-facebook'
module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine
  end
end


text:
"""Indentable rlcompleter

Extend standard rlcompleter module to let tab key can indent
and also completing valid Python identifiers and keywords."""

import readline,rlcompleter

class irlcompleter(rlcompleter.Completer):
        def complete(self, text, state):
                if text == "":
                        readline.insert_text('\t')
                        return None
                else:
                        return rlcompleter.Completer.complete(self,text,state)

#you could change this line to bind another key instead tab.
readline.parse_and_bind("tab: complete")
readline.set_completer(irlcompleter().complete)


text:
using System;
using System.Linq;
using NUnit.Framework;

namespace AGO.WorkQueue.Tests
{
	[TestFixture]
	public abstract class AbstractQueueConsumptionTest
	{
		protected IWorkQueue Queue;

		protected abstract IWorkQueue CreateQueue();

		[SetUp]
		public virtual void SetUp()
		{
			Queue = CreateQueue();
		}

		[TearDown]
		public virtual void TearDown()
		{
			Queue = null;
		}

		[Test]
		public void QueueReturnItemForRequestedProject()
		{
			const string proj1 = "proj1";
			const string proj2 = "proj2";
			var p1Item = new QueueItem("a", Guid.NewGuid(), proj1, "u1");
			var p2Item = new QueueItem("a", Guid.NewGuid(), proj2, "u2");
			Queue.Add(p2Item);
			Queue.Add(p1Item);

			var item = Queue.Get(proj1);

			Assert.AreEqual(p1Item.Project, item.Project);
			Assert.AreEqual(p1Item.TaskType, item.TaskType);
			Assert.AreEqual(p1Item.TaskId, item.TaskId);
		}

		[Test]
		public void QueueReturnNullForNonExistingProject()
		{
			const string proj1 = "proj1";
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, "u"));

			var item = Queue.Get("non existing project");

			Assert.IsNull(item);
		}

		[Test]
		public void QueueReturnTaskForUserWithHigherPriority()
		{
			const string proj = "proj1";
			const string user1 = "u1";
			const string user2 = "u2";
			var i1 = new QueueItem("a", Guid.NewGuid(), proj, user1) { PriorityType = 1, UserPriority = 10 };
			var i2 = new QueueItem("a", Guid.NewGuid(), proj, user2) { PriorityType = 1, UserPriority = 20 };
			Queue.Add(i1);
			Queue.Add(i2);

			var item = Queue.Get(proj);

			Assert.AreEqual(i2.TaskId, item.TaskId);
		}

		[Test]
		public void QueueReturnOldestTaskForUserWhenPrioritiesEquals()
		{
			const string proj = "proj1";
			const string uid = "u";
			var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid) { PriorityType = 1, UserPriority = 10 };
			var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid) { PriorityType = 1, UserPriority = 10 };
			Queue.Add(i1);
			Queue.Add(i2);

			var item = Queue.Get(proj);

			Assert.AreEqual(i1.TaskId, item.TaskId);
		}

		[Test]
		public void QueueReturnOldestTaskWhenPriorityNotUsed()
		{
			const string proj = "proj1";
			const string uid = "u";
			var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid); //PriorityType = 0 by default, so, not used
			var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid);
			Queue.Add(i1);
			Queue.Add(i2);

			var item = Queue.Get(proj);

			Assert.AreEqual(i1.TaskId, item.TaskId);
		}

		[Test]
		public void QueueReturnOldestTaskWhenPriorityNotUsed2()
		{
			const string proj = "proj1";
			const string uid = "u";
			var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid);
			var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid) { UserPriority = 10};
			Queue.Add(i1);
			Queue.Add(i2);

			var item = Queue.Get(proj);

			Assert.AreEqual(i1.TaskId, item.TaskId);
		}

		[Test]
		public void QueueDumpDataAsRawShallowCopyList()
		{
			Queue.Add(new QueueItem("a", Guid.NewGuid(), "p1", "u1"));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), "p2", "u2"));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), "p3", "u3"));

			// ReSharper disable PossibleMultipleEnumeration
			var dump = Queue.Dump(); //special not materialize - test dump is copy, not reference to underlying data

			Assert.AreEqual(3, dump.Count());

			Assert.IsTrue(dump.Any(qi => qi.Project == "p1"));
			Assert.IsTrue(dump.Any(qi => qi.Project == "p2"));
			Assert.IsTrue(dump.Any(qi => qi.Project == "p3"));

			Queue.Clear();

			Assert.AreEqual(3, dump.Count());
			Assert.IsTrue(dump.Any(qi => qi.Project == "p1"));
			Assert.IsTrue(dump.Any(qi => qi.Project == "p2"));
			Assert.IsTrue(dump.Any(qi => qi.Project == "p3"));

			// ReSharper restore PossibleMultipleEnumeration
		}

		[Test]
		public void QueueCalculateOrderForEachUserTaskInProjectWithPriority()
		{
			const string u1 = "u1";
			const string u2 = "u2";
			const string p1 = "proj1";
			const string p2 = "proj2";
			const string p3 = "proj3";
			var i1 = new QueueItem("a", Guid.NewGuid(), p1, u1){ PriorityType = 1, UserPriority = 20};
			var i2 = new QueueItem("a", Guid.NewGuid(), p1, u1) { PriorityType = 1, UserPriority = 20 };
			var i3 = new QueueItem("a", Guid.NewGuid(), p1, u1);
			var i4 = new QueueItem("a", Guid.NewGuid(), p2, u1) {PriorityType = 1, UserPriority = 10};
			var i5 = new QueueItem("a", Guid.NewGuid(), p2, u1);
			var i6 = new QueueItem("a", Guid.NewGuid(), p1, u2) {PriorityType = 1, UserPriority = 40};
			var i7 = new QueueItem("a", Guid.NewGuid(), p2, u2) {PriorityType = 1, UserPriority = 10};
			var i8 = new QueueItem("a", Guid.NewGuid(), p3, u1);
			var i9 = new QueueItem("a", Guid.NewGuid(), p3, u2);

			Queue.Add(i1);
			Queue.Add(i2);
			Queue.Add(i3);
			Queue.Add(i4);
			Queue.Add(i5);
			Queue.Add(i6);
			Queue.Add(i7);
			Queue.Add(i8);
			Queue.Add(i9);

			var snapshot = Queue.Snapshot();

			/*
			 * u1: priority 20 in proj1
			 * u1: priority 10 in proj2
			 * u2: priority 40 in proj1
			 * u2: priority 10 in proj2
			 *
			 *			var	PriorityType	Priority	User
			 * proj1	i6		1				40		u2
			 *			i1		1				20		u1
			 *			i2		1				20		u1
			 *			i3		0				--		u1
			 *
			 * proj2	i4		1				10		u1
			 *			i7		1				10		u2
			 *			i5		0				--		u1
			 *
			 * proj3
			 *			i8		0				--		u1
			 *			i9		0				--		u2
			 *
			 * */
			Assert.IsNotNull(snapshot);
			Assert.AreEqual(2, snapshot.Count);
			//u1 proj1
			Assert.AreEqual(i1.TaskId, snapshot[u1][p1][0].TaskId);
			Assert.AreEqual(i2.TaskId, snapshot[u1][p1][1].TaskId);
			Assert.AreEqual(i3.TaskId, snapshot[u1][p1][2].TaskId);
			Assert.AreEqual(2, snapshot[u1][p1][0].OrderInQueue);
			Assert.AreEqual(3, snapshot[u1][p1][1].OrderInQueue);
			Assert.AreEqual(4, snapshot[u1][p1][2].OrderInQueue);
			//u1 proj2
			Assert.AreEqual(i4.TaskId, snapshot[u1][p2][0].TaskId);
			Assert.AreEqual(i5.TaskId, snapshot[u1][p2][1].TaskId);
			Assert.AreEqual(1, snapshot[u1][p2][0].OrderInQueue);
			Assert.AreEqual(3, snapshot[u1][p2][1].OrderInQueue);
			//u1 proj3
			Assert.AreEqual(i8.TaskId, snapshot[u1][p3][0].TaskId);
			Assert.AreEqual(1, snapshot[u1][p3][0].OrderInQueue);
			//u2 proj1
			Assert.AreEqual(i6.TaskId, snapshot[u2][p1][0].TaskId);
			Assert.AreEqual(1, snapshot[u2][p1][0].OrderInQueue);
			//u2 proj2
			Assert.AreEqual(i7.TaskId, snapshot[u2][p2][0].TaskId);
			Assert.AreEqual(2, snapshot[u2][p2][0].OrderInQueue);
			//u2 proj3
			Assert.AreEqual(i9.TaskId, snapshot[u2][p3][0].TaskId);
			Assert.AreEqual(2, snapshot[u2][p3][0].OrderInQueue);
		}

		[Test]
		public void QueueReturnUniqueProjectCodes()
		{
			const string proj1 = "proj1";
			const string proj2 = "proj2";
			const string proj3 = "proj3";
			const string user = "user";
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj2, user));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj3, user));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj2, user));
			Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user));

			var projects = Queue.UniqueProjects().ToArray();

			Assert.AreEqual(3, projects.Length);
			Assert.IsTrue(projects.Contains(proj1));
			Assert.IsTrue(projects.Contains(proj2));
			Assert.IsTrue(projects.Contains(proj3));
		}

		[Test]
		public void QueueRemoveTaskById()
		{
			var taskId = Guid.NewGuid();
			Queue.Add(new QueueItem("a", taskId, "p", "u"));

			Queue.Remove(taskId);

			Assert.IsFalse(Queue.Dump().Any(qi => qi.TaskId == taskId));
		}

		[Test]
		public void QueueRemoveNotExistingTask()
		{
			//Don't thow exceptions
			Queue.Remove(Guid.NewGuid());
		}
	}
}


text:
package fr.soprasteria.world.persistence;

import java.io.File;
import java.io.IOException;

import fr.soprasteria.world.WorldGrille;

/**
 * Interface pour les classes permettant la sauvegarde et le chargement d'un monde dans un fichier.
 */
public interface WorldFileMapper {

	/**
	 * Charge un monde depuis un fichier.
	 * @param worldFile le fichier contenant le monde.
	 * @return le monde chargé.
	 * @throws IOException en cas de problème avec le fichier
	 */
	public WorldGrille load(File worldFile) throws IOException;

	/**
	 * Sauvegarde un monde dans un fichier.
	 * @param worldFile le fichier dans lequel sauvegardé le monde. Le fichier est écrasé s'il existe déjà.
	 * @param world le monde à sauvegarder.
	 * @throws IOException en cas de problème avec le fichier.
	 */
	public void save(File worldFile, WorldGrille world) throws IOException;
}


text:
package org.fastcatsearch.http.action.management.settings;

import java.io.Writer;

import org.fastcatsearch.db.DBService;
import org.fastcatsearch.db.InternalDBModule.MapperSession;
import org.fastcatsearch.db.mapper.GroupAccountMapper;
import org.fastcatsearch.db.vo.GroupAccountVO;
import org.fastcatsearch.http.ActionAuthority;
import org.fastcatsearch.http.ActionAuthorityLevel;
import org.fastcatsearch.http.ActionMapping;
import org.fastcatsearch.http.action.ActionRequest;
import org.fastcatsearch.http.action.ActionResponse;
import org.fastcatsearch.http.action.AuthAction;
import org.fastcatsearch.util.ResponseWriter;

@ActionMapping (value="/settings/authority/update-group", authority=ActionAuthority.Settings, authorityLevel=ActionAuthorityLevel.WRITABLE)
public class PutGroupAccountAction extends AuthAction {

	@Override
	public void doAuthAction(ActionRequest request, ActionResponse response)
			throws Exception {

		Writer writer = response.getWriter();
		ResponseWriter resultWriter = getDefaultResponseWriter(writer);

		MapperSession<GroupAccountMapper> groupAccountSession = null;

		try {

			groupAccountSession = DBService.getInstance().getMapperSession(GroupAccountMapper.class);

			GroupAccountMapper groupAccountMapper = (GroupAccountMapper)
					groupAccountSession.getMapper();

			if(groupAccountMapper!=null) {

				int groupId = request.getIntParameter("groupId",-1);
				String groupName = request.getParameter("groupName");

				GroupAccountVO vo = null;

				synchronized(groupAccountMapper) {

					if(groupId != -1) {

						vo = groupAccountMapper.getEntry(groupId);
					} else {

						groupId = groupAccountMapper.getMaxId();
						vo = new GroupAccountVO();
						vo.id = groupId;
					}

					vo.groupName = groupName;
				}

				resultWriter.object();
				resultWriter.endObject();
			}
		} finally {
			if(groupAccountSession!=null) try {
				groupAccountSession.closeSession();
			} catch (Exception e) { }
		}
		resultWriter.done();
	}
}


text:
class CGameMenu: public CListener
{
public:
    CGameMenu();
    virtual ~CGameMenu();

    BOOL ProcessState(E_STATE sState, DWORD dwCurrTick);

public:
	void DrawStartMenu();
	void NextMiniLevel();
	void PrevMiniLevel();
	void NextWorld();
	void PrevWorld();
	void DrawStartLevel();
    void DrawFailedLevel();
    void DrawSuccessedLevel();
	void DrawWorldIntroStart(int iWorldId);
	void DrawWorldIntroEnd();
	void DrawWinScreen();
	void FixLevelLabel(BOOL fRusLng);

private:
	void DrawMiniLevel(int iLevel);
	const char* GetMiniElemName(int x, int y);
	void InitLng();

private:
    CPlayLevel* m_pPLBut;
    CRetryLevel* m_pRLBut;
    CNextBut* m_pNLBut;
    CBackToMenu* m_pBTMBut;
    CQuitMenu* m_pQBut;
	CNextMiniLevel* m_pNextLvl;
	CPrevMiniLevel* m_pPrevLvl;
	CNextWorld* m_pNextWorld;
	CPrevWorld* m_pPrevWorld;
	COptionsBut* m_pOptBut;
	CHelpBut* m_pHelpBut;
	COKBut* m_pOKBut;
	char m_szName[100];
	int m_iWorldId;
	int m_iLevelId;
	int m_iLevelValueId;
	int m_iLockedId;
	int m_iTryAgainId;
	int m_iSuccessId;
	int m_iWinId;
	int m_iWorldDesc[NA_WORLD_DESC_NUM_LINES];
};

#endif // LEVEL_H