text:
using System;
using System.Security;
using System.Threading;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace System.Text
{
    public abstract class DecoderFallback
    {
        internal bool bIsMicrosoftBestFitFallback = false;

        private static volatile DecoderFallback replacementFallback; // Default fallback, uses no best fit & "?"
        private static volatile DecoderFallback exceptionFallback;

        // Private object for locking instead of locking on a internal type for SQL reliability work.
        private static Object s_InternalSyncObject;
        private static Object InternalSyncObject
        {
            get
            {
                if (s_InternalSyncObject == null)
                {
                    Object o = new Object();
                    Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
                }
                return s_InternalSyncObject;
            }
        }

        // Get each of our generic fallbacks.

        public static DecoderFallback ReplacementFallback
        {
            get
            {
                if (replacementFallback == null)
                    lock (InternalSyncObject)
                        if (replacementFallback == null)
                            replacementFallback = new DecoderReplacementFallback();

                return replacementFallback;
            }
        }

        public static DecoderFallback ExceptionFallback
        {
            get
            {
                if (exceptionFallback == null)
                    lock (InternalSyncObject)
                        if (exceptionFallback == null)
                            exceptionFallback = new DecoderExceptionFallback();

                return exceptionFallback;
            }
        }

        // Fallback
        //
        // Return the appropriate unicode string alternative to the character that need to fall back.
        // Most implimentations will be:
        //      return new MyCustomDecoderFallbackBuffer(this);

        public abstract DecoderFallbackBuffer CreateFallbackBuffer();

        // Maximum number of characters that this instance of this fallback could return

        public abstract int MaxCharCount { get; }
    }

    public abstract class DecoderFallbackBuffer
    {
        // Most implimentations will probably need an implimenation-specific constructor

        // internal methods that cannot be overriden that let us do our fallback thing
        // These wrap the internal methods so that we can check for people doing stuff that's incorrect

        public abstract bool Fallback(byte[] bytesUnknown, int index);

        // Get next character

        public abstract char GetNextChar();

        // Back up a character

        public abstract bool MovePrevious();

        // How many chars left in this fallback?

        public abstract int Remaining { get; }

        // Clear the buffer

        public virtual void Reset()
        {
            while (GetNextChar() != (char)0) ;
        }

        // Internal items to help us figure out what we're doing as far as error messages, etc.
        // These help us with our performance and messages internally
        internal unsafe byte* byteStart;
        internal unsafe char* charEnd;

        // Internal Reset
        internal unsafe void InternalReset()
        {
            byteStart = null;
            Reset();
        }

        // Set the above values
        // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these.
        internal unsafe void InternalInitialize(byte* byteStart, char* charEnd)
        {
            this.byteStart = byteStart;
            this.charEnd = charEnd;
        }

        // Fallback the current byte by sticking it into the remaining char buffer.
        // This can only be called by our encodings (other have to use the public fallback methods), so
        // we can use our DecoderNLS here too (except we don't).
        // Returns true if we are successful, false if we can't fallback the character (no buffer space)
        // So caller needs to throw buffer space if return false.
        // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
        // array, and we might need the index, hence the byte*
        // Don't touch ref chars unless we succeed
        internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
        {
            // Copy bytes to array (slow, but right now that's what we get to do.
            //  byte[] bytesUnknown = new byte[count];
            //            for (int i = 0; i < count; i++)
            //                bytesUnknown[i] = *(bytes++);

            Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");

            // See if there's a fallback character and we have an output buffer then copy our string.
            if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
            {
                // Copy the chars to our output
                char ch;
                char* charTemp = chars;
                bool bHighSurrogate = false;
                while ((ch = GetNextChar()) != 0)
                {
                    // Make sure no mixed up surrogates
                    if (Char.IsSurrogate(ch))
                    {
                        if (Char.IsHighSurrogate(ch))
                        {
                            // High Surrogate
                            if (bHighSurrogate)
                                throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
                            bHighSurrogate = true;
                        }
                        else
                        {
                            // Low surrogate
                            if (bHighSurrogate == false)
                                throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
                            bHighSurrogate = false;
                        }
                    }

                    if (charTemp >= charEnd)
                    {
                        // No buffer space
                        return false;
                    }

                    *(charTemp++) = ch;
                }

                // Need to make sure that bHighSurrogate isn't true
                if (bHighSurrogate)
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);

                // Now we aren't going to be false, so its OK to update chars
                chars = charTemp;
            }

            return true;
        }

        // This version just counts the fallback and doesn't actually copy anything.
        internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes)
        // Right now this has both bytes and bytes[], since we might have extra bytes, hence the
        // array, and we might need the index, hence the byte*
        {
            // Copy bytes to array (slow, but right now that's what we get to do.
            //            byte[] bytesUnknown = new byte[count];
            //            for (int i = 0; i < count; i++)
            //              bytesUnknown[i] = *(bytes++);

            Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");

            // See if there's a fallback character and we have an output buffer then copy our string.
            if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
            {
                int count = 0;

                char ch;
                bool bHighSurrogate = false;
                while ((ch = GetNextChar()) != 0)
                {
                    // Make sure no mixed up surrogates
                    if (Char.IsSurrogate(ch))
                    {
                        if (Char.IsHighSurrogate(ch))
                        {
                            // High Surrogate
                            if (bHighSurrogate)
                                throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
                            bHighSurrogate = true;
                        }
                        else
                        {
                            // Low surrogate
                            if (bHighSurrogate == false)
                                throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
                            bHighSurrogate = false;
                        }
                    }

                    count++;
                }

                // Need to make sure that bHighSurrogate isn't true
                if (bHighSurrogate)
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);

                return count;
            }

            // If no fallback return 0
            return 0;
        }

        // private helper methods
        internal void ThrowLastBytesRecursive(byte[] bytesUnknown)
        {
            // Create a string representation of our bytes.
            StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3);
            int i;
            for (i = 0; i < bytesUnknown.Length && i < 20; i++)
            {
                if (strBytes.Length > 0)
                    strBytes.Append(" ");
                strBytes.Append(String.Format(CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i]));
            }
            // In case the string's really long
            if (i == 20)
                strBytes.Append(" ...");

            // Throw it, using our complete bytes
            throw new ArgumentException(
                SR.Format(SR.Argument_RecursiveFallbackBytes, strBytes.ToString()), nameof(bytesUnknown));
        }
    }
}


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var notes = require('../../app/controllers/notes.server.controller');

	// Notes Routes
	app.route('/notes')
		.get(users.requiresLogin, notes.list)
		.post(users.requiresLogin, notes.create);

	app.route('/notes/:noteId')
		.get(notes.read)
		.put(users.requiresLogin, notes.hasAuthorization, notes.update)
		.delete(users.requiresLogin, notes.hasAuthorization, notes.delete);

	// Finish by binding the Note middleware
	app.param('noteId', notes.noteByID);
};

redpajama_set_name: RedPajamaGithub


text:
package repository

import (
	"context"
	"database/sql"
	"time"

	"github.com/pkg/errors"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"

	"github.com/hiromaily/go-goa/pkg/encryption"
	models "github.com/hiromaily/go-goa/pkg/model/rdb"
	hyuser "resume/gen/hy_user"
)

// UserRepository interface
type UserRepository interface {
	Login(email, password string) (int, error)
	UserList() ([]*hyuser.User, error)
	GetUser(userID int) (*hyuser.User, error)
	IsUser(userID int) (bool, error)
	InsertUser(name, email, password string) (int, error)
	UpdateUser(userID int, name, email, password string) (int, error)
	DeleteUser(userID int) (int, error)
}

type userRepository struct {
	tableName string
	dbConn    *sql.DB
	hash      encryption.Hasher
}

// NewUserRepository returns UserRepository
func NewUserRepository(dbConn *sql.DB, hash encryption.Hasher) UserRepository {
	return &userRepository{
		dbConn:    dbConn,
		tableName: "t_user",
		hash:      hash,
	}
}

func (u *userRepository) Login(email, password string) (int, error) {
	type LoginUser struct {
		ID       int    `boil:"id"`
		Email    string `boil:"email"`
		Password string `boil:"password"`
	}

	ctx := context.Background()

	var user LoginUser
	// sql := "SELECT id, user_name FROM t_users WHERE delete_flg=? AND email=? AND password=?"
	err := models.TUsers(
		qm.Select("id, email, password"),
		qm.Where("email=?", email),
		qm.And("is_deleted=?", 0),
	).Bind(ctx, u.dbConn, &user)
	if err != nil {
		return 0, errors.Wrap(err, "failed to call models.TUsers().Bind()")
	}

	// check
	// log.Debug().Msg(u.hash.Hash(password))
	if user.Password != u.hash.Hash(password) {
		return 0, errors.Errorf("password is invalid")
	}
	return user.ID, nil
}

func (u *userRepository) UserList() ([]*hyuser.User, error) {
	ctx := context.Background()

	items, err := models.TUsers(
		qm.Select("id, user_name, email"),
		qm.Where("is_deleted=?", 0),
	).All(ctx, u.dbConn)
	if err != nil {
		return nil, errors.Wrap(err, "failed to call models.TUsers().All()")
	}

	converted := make([]*hyuser.User, len(items))
	for i, item := range items {
		converted[i] = &hyuser.User{
			UserID:   &item.ID,
			UserName: &item.UserName,
			Email:    &item.Email.String,
		}
	}
	return converted, nil
}

func (u *userRepository) GetUser(userID int) (*hyuser.User, error) {
	ctx := context.Background()
	q := []qm.QueryMod{
		qm.Select("id, user_name, email"),
		qm.Where("is_deleted=?", 0),
		qm.And("id=?", userID),
	}
	item, err := models.TUsers(q...).One(ctx, u.dbConn)
	if err != nil {
		return nil, errors.Wrap(err, "failed to call models.TUsers().One()")
	}
	return &hyuser.User{
		UserID:   &item.ID,
		UserName: &item.UserName,
		Email:    &item.Email.String,
	}, nil
}

func (u *userRepository) IsUser(userID int) (bool, error) {
	ctx := context.Background()
	q := []qm.QueryMod{
		qm.Select("id"),
		qm.Where("is_deleted=?", 0),
		qm.And("id=?", userID),
	}
	ret, err := models.TUsers(q...).Exists(ctx, u.dbConn)
	if err != nil {
		return false, errors.Wrap(err, "failed to call models.TUsers().One()")
	}
	return ret, nil
}

func (u *userRepository) getUserByEmail(email string) (*models.TUser, error) {
	ctx := context.Background()

	q := []qm.QueryMod{
		qm.Where("is_deleted=?", 0),
		qm.And("email=?", email),
	}
	item, err := models.TUsers(q...).One(ctx, u.dbConn)
	if err != nil {
		return nil, errors.Wrap(err, "failed to call models.TUsers().One()")
	}
	return item, nil
}

func (u *userRepository) InsertUser(name, email, password string) (int, error) {
	item := &models.TUser{
		UserName: name,
		Email:    null.StringFrom(email),
		Password: null.StringFrom(u.hash.Hash(password)),
	}

	ctx := context.Background()
	if err := item.Insert(ctx, u.dbConn, boil.Infer()); err != nil {
		return 0, errors.Wrap(err, "failed to call item.Insert()")
	}
	user, err := u.getUserByEmail(email)
	if err != nil {
		return 0, errors.Wrap(err, "failed to call getUserByEmail()")
	}

	return user.ID, nil
}

func (u *userRepository) UpdateUser(userID int, name, email, password string) (int, error) {
	if userID == 0 {
		return 0, errors.New("userID is invalid")
	}

	ctx := context.Background()

	// Set updating columns
	updCols := map[string]interface{}{}
	if name != "" {
		updCols[models.TUserColumns.UserName] = name
	}
	if email != "" {
		updCols[models.TUserColumns.Email] = email
	}
	if password != "" {
		updCols[models.TUserColumns.Password] = u.hash.Hash(password)
	}
	updCols[models.TUserColumns.UpdatedAt] = null.TimeFrom(time.Now().UTC())

	id, err := models.TUsers(
		qm.Where("id=?", userID),
	).UpdateAll(ctx, u.dbConn, updCols)
	return int(id), err
}

// DeleteUser deletes user
func (u *userRepository) DeleteUser(userID int) (int, error) {
	ctx := context.Background()

	// Set updating columns
	updCols := map[string]interface{}{}
	updCols[models.TUserColumns.IsDeleted] = null.StringFrom("1")
	updCols[models.TUserColumns.UpdatedAt] = null.TimeFrom(time.Now())

	id, err := models.TUsers(
		qm.Where("id=?", userID),
	).UpdateAll(ctx, u.dbConn, updCols)
	return int(id), err
}


text:
title: Video
desc: The QVideo Vue components makes embedding a video like Youtube easy. It also resizes to fit the container by default.
---

Using the QVideo component makes embedding a video like Youtube easy. It also resizes to fit the container by default.

::: tip
You may also want to check our own HTML 5 video player component: [QMediaPlayer](https://github.com/quasarframework/app-extension-qmediaplayer), which is far more advanced than QVideo (which essentially is an iframe pointing to embedded Youtube videos).
:::

## QVideo API
<doc-api file="QVideo" />

## Usage

### Basic
<doc-example title="Basic" file="QVideo/Basic" />

### With aspect ratio <q-badge align="top" color="brand-primary" label="v1.7+" />

<doc-example title="With aspect ratio" file="QVideo/Ratio" />

### Markup equivalent
<doc-example title="HTML markup" file="QVideo/HtmlMarkup" />


text:
/*
 * AccountBean.java
 *
 * Created on May 3, 2004, 11:00 AM
 */

package gold.web.client;

import gold.*;
import org.jdom.*;
import java.util.*;

/**
 *
 * @author  d3l028
 */
public class AccountBean {

    /**
     * Holds value of property accountProject.
     */
    private String accountProject;

    /**
     * Holds value of property accountUser.
     */
    private String accountUser;

    /**
     * Holds value of property accountMachine.
     */
    private String accountMachine;

    /**
     * Holds value of property accountProjectActive.
     */
    private String accountProjectActive;

    /**
     * Holds value of property accountProjectAllowDesc.
     */
    private String accountProjectAllowDesc;

    /**
     * Holds value of property accountUserActive.
     */
    private String accountUserActive;

    /**
     * Holds value of property accountMachineActive.
     */
    private String accountMachineActive;

    /**
     * Holds value of property endTime.
     */
    private String endTime;

    /**
     * Holds value of property activationTime.
     */
    private String activationTime;

    /**
     * Holds value of property type.
     */
    private String type;

    /**
     * Holds value of property creditLimit.
     */
    private String creditLimit;

    /**
     * Holds value of property description.
     */
    private String description;

    /**
     * Holds value of property amount.
     */
    private String amount;

    /**
     * Holds value of property fromIds.
     */
    private String fromIds;

    /**
     * Holds value of property toIds.
     */
    private String toIds;

    /**
     * Holds value of property fromUser.
     */
    private String fromUser;

    /**
     * Holds value of property fromProject.
     */
    private String fromProject;

    /**
     * Holds value of property fromMachine.
     */
    private String fromMachine;

    /**
     * Holds value of property toUser.
     */
    private String toUser;

    /**
     * Holds value of property toProject.
     */
    private String toProject;

    /**
     * Holds value of property toMachine.
     */
    private String toMachine;

    /** Creates a new instance of AccountBean */
    public AccountBean() {
    }

    /**
     * Getter for property accountProject.
     * @return Value of property accountProject.
     */
    public String getAccountProject() {
        return this.accountProject;
    }

    /**
     * Setter for property accountProject.
     * @param accountProject New value of property accountProject.
     */
    public void setAccountProject(String accountProject) {
        this.accountProject = accountProject;
    }

    /**
     * Getter for property accountUser.
     * @return Value of property accountUser.
     */
    public String getAccountUser() {
        return this.accountUser;
    }

    /**
     * Setter for property accountUser.
     * @param accountUser New value of property accountUser.
     */
    public void setAccountUser(String accountUser) {
        this.accountUser = accountUser;
    }

    /**
     * Getter for property accountMachine.
     * @return Value of property accountMachine.
     */
    public String getAccountMachine() {
        return this.accountMachine;
    }

    /**
     * Setter for property accountMachine.
     * @param accountMachine New value of property accountMachine.
     */
    public void setAccountMachine(String accountMachine) {
        this.accountMachine = accountMachine;
    }

    /**
     * Getter for property accountProjectActive.
     * @return Value of property accountProjectActive.
     */
    public String getAccountProjectActive() {
        return this.accountProjectActive;
    }

    /**
     * Setter for property accountProjectActive.
     * @param accountProjectActive New value of property accountProjectActive.
     */
    public void setAccountProjectActive(String accountProjectActive) {
        this.accountProjectActive = accountProjectActive;
    }

    /**
     * Getter for property accountProjectAllowDesc.
     * @return Value of property accountProjectAllowDesc.
     */
    public String getAccountProjectAllowDesc() {
        return this.accountProjectAllowDesc;
    }

    /**
     * Setter for property accountProjectAllowDesc.
     * @param accountProjectAllowDesc New value of property accountProjectAllowDesc.
     */
    public void setAccountProjectAllowDesc(String accountProjectAllowDesc) {
        this.accountProjectAllowDesc = accountProjectAllowDesc;
    }

    /**
     * Getter for property accountUserActive.
     * @return Value of property accountUserActive.
     */
    public String getAccountUserActive() {
        return this.accountUserActive;
    }

    /**
     * Setter for property accountUserActive.
     * @param accountUserActive New value of property accountUserActive.
     */
    public void setAccountUserActive(String accountUserActive) {
        this.accountUserActive = accountUserActive;
    }

    /**
     * Getter for property accountMachineActive.
     * @return Value of property accountMachineActive.
     */
    public String getAccountMachineActive() {
        return this.accountMachineActive;
    }

    /**
     * Setter for property accountMachineActive.
     * @param accountMachineActive New value of property accountMachineActive.
     */
    public void setAccountMachineActive(String accountMachineActive) {
        this.accountMachineActive = accountMachineActive;
    }

    /**
     * Getter for property endTime.
     * @return Value of property endTime.
     */
    public String getEndTime() {
        return this.endTime;
    }

    /**
     * Setter for property endTime.
     * @param endTime New value of property endTime.
     */
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    /**
     * Getter for property activationTime.
     * @return Value of property activationTime.
     */
    public String getActivationTime() {
        return this.activationTime;
    }

    /**
     * Setter for property activationTime.
     * @param activationTime New value of property activationTime.
     */
    public void setActivationTime(String activationTime) {
        this.activationTime = activationTime;
    }

    /**
     * Getter for property type.
     * @return Value of property type.
     */
    public String getType() {
        return this.type;
    }

    /**
     * Setter for property type.
     * @param type New value of property type.
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * Getter for property creditLimit.
     * @return Value of property creditLimit.
     */
    public String getCreditLimit() {
        return this.creditLimit;
    }

    /**
     * Setter for property creditLimit.
     * @param creditLimit New value of property creditLimit.
     */
    public void setCreditLimit(String creditLimit) {
        this.creditLimit = creditLimit;
    }

    /**
     * Getter for property description.
     * @return Value of property description.
     */
    public String getDescription() {
        return this.description;
    }

    /**
     * Setter for property description.
     * @param description New value of property description.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * Getter for property amount.
     * @return Value of property amount.
     */
    public String getAmount() {
        return this.amount;
    }

    /**
     * Setter for property amount.
     * @param amount New value of property amount.
     */
    public void setAmount(String amount) {
        this.amount = amount;
    }

    public String[] getAccountUserAsArray(){
        return accountUser.split(",");
    }

    public String[] getAccountUserActiveAsArray(){
        return accountUserActive.split(",");
    }

    public String[] getAccountProjectAsArray(){
        return accountProject.split(",");
    }

    public String[] getAccountProjectActiveAsArray(){
        return accountProjectActive.split(",");
    }

    public String[] getAccountProjectAllowDescAsArray(){
        return accountProjectAllowDesc.split(",");
    }

    public String[] getAccountMachineAsArray(){
        return accountMachine.split(",");
    }

    public String[] getAccountMachineActiveAsArray(){
        return accountMachineActive.split(",");
    }

    public String[] getFromIdsAsArray(){
        return fromIds.split(",");
    }

    public String[] getToIdsAsArray(){
        return toIds.split(",");
    }
    /*

    public String[] getAccountUserAsArray(){
        if(accountUser != null) return accountUser.split(",");
        return null;
    }

    public String[] getAccountUserActiveAsArray(){
        if(accountUserActive != null) return accountUserActive.split(",");
        return null;
    }

    public String[] getAccountProjectAsArray(){
        if(accountProject != null) return accountProject.split(",");
        return null;
    }

    public String[] getAccountProjectActiveAsArray(){
        if(accountProjectActive != null) return accountProjectActive.split(",");
        return null;
    }

    public String[] getAccountProjectAllowDescAsArray(){
        if(accountProjectAllowDesc != null) return accountProjectAllowDesc.split(",");
        return null;
    }

    public String[] getAccountMachineAsArray(){
        if(accountMachine != null) return accountMachine.split(",");
        return null;
    }

    public String[] getAccountMachineActiveAsArray(){
        if(accountMachineActive != null) return accountMachineActive.split(",");
        return null;
    }

    public String[] getFromIdsAsArray(){
        if(fromIds != null) return fromIds.split(",");
        return null;
    }

    public String[] getToIdsAsArray(){
        if(toIds != null) return toIds.split(",");
        return null;
    }

     */

    /**
     * Getter for property toIds.
     * @return Value of property toIds.
     */
    public String getToIds() {
        return this.toIds;
    }

    /**
     * Setter for property toIds.
     * @param toIds New value of property toIds.
     */
    public void setToIds(String toIds) {
        this.toIds = toIds;
    }

    /**
     * Getter for property fromIds.
     * @return Value of property fromIds.
     */
    public String getFromIds() {
        return this.fromIds;
    }

    /**
     * Setter for property fromIds.
     * @param fromIds New value of property fromIds.
     */
    public void setFromIds(String fromIds) {
        this.fromIds = fromIds;
    }

    /**
     * Getter for property fromUser.
     * @return Value of property fromUser.
     */
    public String getFromUser() {
        return this.fromUser;
    }

    /**
     * Setter for property fromUser.
     * @param fromUser New value of property fromUser.
     */
    public void setFromUser(String fromUser) {
        this.fromUser = fromUser;
    }

    /**
     * Getter for property fromProject.
     * @return Value of property fromProject.
     */
    public String getFromProject() {
        return this.fromProject;
    }

    /**
     * Setter for property fromProject.
     * @param fromProject New value of property fromProject.
     */
    public void setFromProject(String fromProject) {
        this.fromProject = fromProject;
    }

    /**
     * Getter for property fromMachine.
     * @return Value of property fromMachine.
     */
    public String getFromMachine() {
        return this.fromMachine;
    }

    /**
     * Setter for property fromMachine.
     * @param fromMachine New value of property fromMachine.
     */
    public void setFromMachine(String fromMachine) {
        this.fromMachine = fromMachine;
    }

    /**
     * Getter for property toUser.
     * @return Value of property toUser.
     */
    public String getToUser() {
        return this.toUser;
    }

    /**
     * Setter for property toUser.
     * @param toUser New value of property toUser.
     */
    public void setToUser(String toUser) {
        this.toUser = toUser;
    }

    /**
     * Getter for property toProject.
     * @return Value of property toProject.
     */
    public String getToProject() {
        return this.toProject;
    }

    /**
     * Setter for property toProject.
     * @param toProject New value of property toProject.
     */
    public void setToProject(String toProject) {
        this.toProject = toProject;
    }

    /**
     * Getter for property toMachine.
     * @return Value of property toMachine.
     */
    public String getToMachine() {
        return this.toMachine;
    }

    /**
     * Setter for property toMachine.
     * @param toMachine New value of property toMachine.
     */
    public void setToMachine(String toMachine) {
        this.toMachine = toMachine;
    }

    public void createAccount(Request request){
        //request.setAssignment("Type", type);
        //request.setAssignment("Amount", amount);
        request.setAssignment("CreditLimit", creditLimit);
        //request.setAssignment("ActivationTime", activationTime);
        //request.setAssignment("EndTime", endTime);
        if(description != null) request.setAssignment("Description", description);
    }

    public void makeTransfer(Request request){
        request.setAction("Transfer");
        request.setObject("Account");
        request.setOption("Amount", amount);
        String[] ids;
        if(fromIds != null && getFromIdsAsArray().length > 0){
            ids = getFromIdsAsArray();
            for(int i = 0; i < ids.length; i++)
                request.setOption("FromId", ids[i]);
        }else{
            request.setOption("FromProject", fromProject);
            request.setOption("FromUser", fromUser);
            request.setOption("FromMachine", fromMachine);
        }
        if(toIds != null && getToIdsAsArray().length > 0){
            ids = getToIdsAsArray();
            for(int i = 0; i < ids.length; i++)
                request.setOption("ToId", ids[i]);
        }else{
            request.setOption("ToProject", toProject);
            request.setOption("ToUser", toUser);
            request.setOption("ToMachine", toMachine);
        }
    }

    //user defined methods:
    public String toString() {
        return "\ntype: " + type + "\n" +
               "amount: " + amount + "\n"+
               "creditLimit: " + creditLimit  + "\n"+
               "activationTime: " + activationTime + "\n" +
               "endTime: " + endTime  + "\n"+
               "description: " + description  + "\n"+
               "accountUsers: " +accountUser  + "\n"+
               "accountUsersActive: " + accountUserActive  + "\n"+
               "accountProject: " + accountProject  + "\n" +
               "accountProjectActive: " + accountProjectActive  + "\n"+
               "accountProjectAllowDesc: " + accountProjectAllowDesc  + "\n"+
               "accountMachine: " + accountMachine  + "\n"+
               "accountMachineActive: " + accountMachineActive  + "\n\n"+
               "fromIds: " + fromIds + "\n"+
               "fromMachine: " + fromMachine + "\n"+
               "fromProject: " + fromProject + "\n"+
               "fromUser: " + fromUser + "\n"+
               "toIds: " + toIds + "\n"+
               "toMachine: " + toMachine + "\n"+
               "toProject: " + toProject + "\n"+
               "toUser: " + toUser + "\n";
    }

}


text:
<?php
namespace PhpAmqpLib\Connection;

use PhpAmqpLib\Wire\IO\StreamIO;

class AMQPStreamConnection extends AbstractConnection
{
    /**
     * @param string $host
     * @param string $port
     * @param string $user
     * @param string $password
     * @param string $vhost
     * @param bool $insist
     * @param string $login_method
     * @param null $login_response
     * @param string $locale
     * @param float $connection_timeout
     * @param float $read_write_timeout
     * @param null $context
     * @param bool $keepalive
     * @param int $heartbeat
     */
    public function __construct(
        $host,
        $port,
        $user,
        $password,
        $vhost = '/',
        $insist = false,
        $login_method = 'AMQPLAIN',
        $login_response = null,
        $locale = 'en_US',
        $connection_timeout = 3.0,
        $read_write_timeout = 3.0,
        $context = null,
        $keepalive = false,
        $heartbeat = 0
    ) {
        $io = new StreamIO(
            $host,
            $port,
            $connection_timeout,
            $read_write_timeout,
            $context,
            $keepalive,
            $heartbeat
        );

        parent::__construct(
            $user,
            $password,
            $vhost,
            $insist,
            $login_method,
            $login_response,
            $locale,
            $io,
            $heartbeat
        );

        // save the params for the use of __clone, this will overwrite the parent
        $this->construct_params = func_get_args();
    }
}


text:
<!DOCTYPE html>

<TITLE>Manpage of SIGRETURN</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

SIGRETURN

Section: Linux Programmer's Manual (2)
Updated: 2008-06-26
Index
Return to Main Contents

NAME

sigreturn - return from signal handler and cleanup stack frame

SYNOPSIS

int sigreturn(unsigned long __unused);

DESCRIPTION

When the Linux kernel creates the stack frame for a signal handler, a
call to
sigreturn()

is inserted into the stack frame so that upon
return from the signal handler,
sigreturn()

will be called.

This
sigreturn()

call undoes everything that was
done---changing the process's signal mask, switching stacks (see
sigaltstack(2))---in

order to invoke the signal handler:
it restores the process's signal mask, switches stacks,
and restores the process's context (registers, processor flags),
so that the process directly resumes execution
at the point where it was interrupted by the signal.

RETURN VALUE

sigreturn()

never returns.

FILES

/usr/src/linux/arch/i386/kernel/signal.c

/usr/src/linux/arch/alpha/kernel/entry.S

CONFORMING TO

sigreturn()

is specific to Linux and should not be used in programs intended to be
portable.

NOTES

The
sigreturn()

call is used by the kernel to implement signal handlers.
It should
never

be called directly.
Better yet, the specific use of the
__unused

argument varies depending on the architecture.

SEE ALSO

kill(2),

sigaltstack(2),

signal(2),

signal(7)

COLOPHON

This page is part of release 3.22 of the Linux
man-pages

project.
A description of the project,
and information about reporting bugs,
can be found at
http://www.kernel.org/doc/man-pages/.

Index

NAME

SYNOPSIS

DESCRIPTION

RETURN VALUE

FILES

CONFORMING TO

NOTES

SEE ALSO

COLOPHON

This document was created by
man2html,
using the manual pages.

Time: 05:33:05 GMT, December 24, 2015


text:
"""
Tests for uu module.
Nick Mathewson
"""

import unittest
from test import test_support

import sys, os, uu, cStringIO
import uu

plaintext = "The smooth-scaled python crept over the sleeping dog\n"

encodedtext = """\
M5&AE('-M;V]T:\"US8V%L960@<'ET:&]N(&-R97!T(&]V97(@=&AE('-L965P
(:6YG(&1O9PH """

encodedtextwrapped = "begin %03o %s\n" + encodedtext.replace("%", "%%") + "\n \nend\n"

class UUTest(unittest.TestCase):

    def test_encode(self):
        inp = cStringIO.StringIO(plaintext)
        out = cStringIO.StringIO()
        uu.encode(inp, out, "t1")
        self.assertEqual(out.getvalue(), encodedtextwrapped % (0666, "t1"))
        inp = cStringIO.StringIO(plaintext)
        out = cStringIO.StringIO()
        uu.encode(inp, out, "t1", 0644)
        self.assertEqual(out.getvalue(), encodedtextwrapped % (0644, "t1"))

    def test_decode(self):
        inp = cStringIO.StringIO(encodedtextwrapped % (0666, "t1"))
        out = cStringIO.StringIO()
        uu.decode(inp, out)
        self.assertEqual(out.getvalue(), plaintext)
        inp = cStringIO.StringIO(
            "UUencoded files may contain many lines,\n" +
            "even some that have 'begin' in them.\n" +
            encodedtextwrapped % (0666, "t1")
        )
        out = cStringIO.StringIO()
        uu.decode(inp, out)
        self.assertEqual(out.getvalue(), plaintext)

    def test_truncatedinput(self):
        inp = cStringIO.StringIO("begin 644 t1\n" + encodedtext)
        out = cStringIO.StringIO()
        try:
            uu.decode(inp, out)
            self.fail("No exception thrown")
        except uu.Error, e:
            self.assertEqual(str(e), "Truncated input file")

    def test_missingbegin(self):
        inp = cStringIO.StringIO("")
        out = cStringIO.StringIO()
        try:
            uu.decode(inp, out)
            self.fail("No exception thrown")
        except uu.Error, e:
            self.assertEqual(str(e), "No valid begin line found in input file")

class UUStdIOTest(unittest.TestCase):

    def setUp(self):
        self.stdin = sys.stdin
        self.stdout = sys.stdout

    def tearDown(self):
        sys.stdin = self.stdin
        sys.stdout = self.stdout

    def test_encode(self):
        sys.stdin = cStringIO.StringIO(plaintext)
        sys.stdout = cStringIO.StringIO()
        uu.encode("-", "-", "t1", 0666)
        self.assertEqual(
            sys.stdout.getvalue(),
            encodedtextwrapped % (0666, "t1")
        )

    def test_decode(self):
        sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0666, "t1"))
        sys.stdout = cStringIO.StringIO()
        uu.decode("-", "-")
        self.assertEqual(sys.stdout.getvalue(), plaintext)

class UUFileTest(unittest.TestCase):

    def _kill(self, f):
        # close and remove file
        try:
            f.close()
        except (SystemExit, KeyboardInterrupt):
            raise
        except:
            pass
        try:
            os.unlink(f.name)
        except (SystemExit, KeyboardInterrupt):
            raise
        except:
            pass

    def setUp(self):
        self.tmpin  = test_support.TESTFN + "i"
        self.tmpout = test_support.TESTFN + "o"

    def tearDown(self):
        del self.tmpin
        del self.tmpout

    def test_encode(self):
        fin = fout = None
        try:
            test_support.unlink(self.tmpin)
            fin = open(self.tmpin, 'wb')
            fin.write(plaintext)
            fin.close()

            fin = open(self.tmpin, 'rb')
            fout = open(self.tmpout, 'w')
            uu.encode(fin, fout, self.tmpin, mode=0644)
            fin.close()
            fout.close()

            fout = open(self.tmpout, 'r')
            s = fout.read()
            fout.close()
            self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin))

            # in_file and out_file as filenames
            uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644)
            fout = open(self.tmpout, 'r')
            s = fout.read()
            fout.close()
            self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin))

        finally:
            self._kill(fin)
            self._kill(fout)

    def test_decode(self):
        f = None
        try:
            test_support.unlink(self.tmpin)
            f = open(self.tmpin, 'w')
            f.write(encodedtextwrapped % (0644, self.tmpout))
            f.close()

            f = open(self.tmpin, 'r')
            uu.decode(f)
            f.close()

            f = open(self.tmpout, 'r')
            s = f.read()
            f.close()
            self.assertEqual(s, plaintext)
            # XXX is there an xp way to verify the mode?
        finally:
            self._kill(f)

    def test_decode_filename(self):
        f = None
        try:
            test_support.unlink(self.tmpin)
            f = open(self.tmpin, 'w')
            f.write(encodedtextwrapped % (0644, self.tmpout))
            f.close()

            uu.decode(self.tmpin)

            f = open(self.tmpout, 'r')
            s = f.read()
            f.close()
            self.assertEqual(s, plaintext)
        finally:
            self._kill(f)

    def test_decodetwice(self):
        # Verify that decode() will refuse to overwrite an existing file
        f = None
        try:
            f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))

            f = open(self.tmpin, 'r')
            uu.decode(f)
            f.close()

            f = open(self.tmpin, 'r')
            self.assertRaises(uu.Error, uu.decode, f)
            f.close()
        finally:
            self._kill(f)

def test_main():
    test_support.run_unittest(UUTest, UUStdIOTest, UUFileTest)

if __name__=="__main__":
    test_main()


text:
package version

import (
	"fmt"
	"os"
)

var (
	// These are bound by the -X key value ldflags option of the go compiler
	gitRepo          string
	gitBranch        string
	gitTag           string
	gitCommitHash    string
	gitCommitMessage string
	buildTimestamp   string
	buildNumber      string
)

var (
	build_info = &Build{
		Timestamp:  buildTimestamp,
		BuildLabel: buildNumber,
		RepoUrl:    gitRepo,
		Tag:        gitTag,
		Branch:     gitBranch,
		Commit:     gitCommitHash,
		Message:    gitCommitMessage,
	}
)

type Build struct {
	RepoUrl    string
	Branch     string
	Tag        string
	Commit     string
	Message    string
	BuildLabel string
	Timestamp  string
	Number     string
}

func BuildInfo() *Build {
	return build_info
}

func SetBuildInfo(b *Build) {
	build_info = b
}

func (buildInfo *Build) Notice() string {
	line1 := fmt.Sprintf("%s: Version %s, Build %s, Built on %s. ", os.Args[0], buildInfo.Tag, buildInfo.BuildLabel, buildInfo.Timestamp)
	line2 := fmt.Sprintf("Git repo=%s branch=%s commit=%s message=%s", buildInfo.RepoUrl, buildInfo.Branch, buildInfo.Commit, buildInfo.Message)
	return line1 + line2
}

func (buildInfo *Build) GetRepoUrl() string {
	return buildInfo.RepoUrl
}

func (buildInfo *Build) GetBranch() string {
	return buildInfo.Branch
}

func (buildInfo *Build) GetTag() string {
	return buildInfo.Tag
}

func (buildInfo *Build) GetCommitHash() string {
	return buildInfo.Commit
}

func (buildInfo *Build) GetBuildTimestamp() string {
	return buildInfo.Timestamp
}

func (buildInfo *Build) GetBuildNumber() string {
	return buildInfo.Number
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTimeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // 书写日期表结构
        Schema::create('time', function (Blueprint $table) {
            $table -> increments('id'); // 自增
            $table -> string('time_name');
            $table -> integer('tid'); // 整型
            $table -> string('path');
            $table -> smallInteger('status');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::dropIfExists('time');
    }
}


text:
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;

namespace Ds3.Calls
{
    public class ImportPoolSpectraS3Request : Ds3Request
    {

        public string Pool { get; private set; }

        private ImportConflictResolutionMode? _conflictResolutionMode;
        public ImportConflictResolutionMode? ConflictResolutionMode
        {
            get { return _conflictResolutionMode; }
            set { WithConflictResolutionMode(value); }
        }

        private string _dataPolicyId;
        public string DataPolicyId
        {
            get { return _dataPolicyId; }
            set { WithDataPolicyId(value); }
        }

        private Priority? _priority;
        public Priority? Priority
        {
            get { return _priority; }
            set { WithPriority(value); }
        }

        private string _storageDomainId;
        public string StorageDomainId
        {
            get { return _storageDomainId; }
            set { WithStorageDomainId(value); }
        }

        private string _userId;
        public string UserId
        {
            get { return _userId; }
            set { WithUserId(value); }
        }

        private Priority? _verifyDataAfterImport;
        public Priority? VerifyDataAfterImport
        {
            get { return _verifyDataAfterImport; }
            set { WithVerifyDataAfterImport(value); }
        }

        private bool? _verifyDataPriorToImport;
        public bool? VerifyDataPriorToImport
        {
            get { return _verifyDataPriorToImport; }
            set { WithVerifyDataPriorToImport(value); }
        }

        public ImportPoolSpectraS3Request WithConflictResolutionMode(ImportConflictResolutionMode? conflictResolutionMode)
        {
            this._conflictResolutionMode = conflictResolutionMode;
            if (conflictResolutionMode != null)
            {
                this.QueryParams.Add("conflict_resolution_mode", conflictResolutionMode.ToString());
            }
            else
            {
                this.QueryParams.Remove("conflict_resolution_mode");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
        {
            this._dataPolicyId = dataPolicyId.ToString();
            if (dataPolicyId != null)
            {
                this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
            }
            else
            {
                this.QueryParams.Remove("data_policy_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithDataPolicyId(string dataPolicyId)
        {
            this._dataPolicyId = dataPolicyId;
            if (dataPolicyId != null)
            {
                this.QueryParams.Add("data_policy_id", dataPolicyId);
            }
            else
            {
                this.QueryParams.Remove("data_policy_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithPriority(Priority? priority)
        {
            this._priority = priority;
            if (priority != null)
            {
                this.QueryParams.Add("priority", priority.ToString());
            }
            else
            {
                this.QueryParams.Remove("priority");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
        {
            this._storageDomainId = storageDomainId.ToString();
            if (storageDomainId != null)
            {
                this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
            }
            else
            {
                this.QueryParams.Remove("storage_domain_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithStorageDomainId(string storageDomainId)
        {
            this._storageDomainId = storageDomainId;
            if (storageDomainId != null)
            {
                this.QueryParams.Add("storage_domain_id", storageDomainId);
            }
            else
            {
                this.QueryParams.Remove("storage_domain_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithUserId(Guid? userId)
        {
            this._userId = userId.ToString();
            if (userId != null)
            {
                this.QueryParams.Add("user_id", userId.ToString());
            }
            else
            {
                this.QueryParams.Remove("user_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithUserId(string userId)
        {
            this._userId = userId;
            if (userId != null)
            {
                this.QueryParams.Add("user_id", userId);
            }
            else
            {
                this.QueryParams.Remove("user_id");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport)
        {
            this._verifyDataAfterImport = verifyDataAfterImport;
            if (verifyDataAfterImport != null)
            {
                this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString());
            }
            else
            {
                this.QueryParams.Remove("verify_data_after_import");
            }
            return this;
        }

        public ImportPoolSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport)
        {
            this._verifyDataPriorToImport = verifyDataPriorToImport;
            if (verifyDataPriorToImport != null)
            {
                this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString());
            }
            else
            {
                this.QueryParams.Remove("verify_data_prior_to_import");
            }
            return this;
        }

        public ImportPoolSpectraS3Request(string pool)
        {
            this.Pool = pool;
            this.QueryParams.Add("operation", "import");

        }

        internal override HttpVerb Verb
        {
            get
            {
                return HttpVerb.PUT;
            }
        }

        internal override string Path
        {
            get
            {
                return "/_rest_/pool/" + Pool;
            }
        }
    }
}


text:
package com.msopentech.odatajclient.engine.data.metadata.edm;

import com.msopentech.odatajclient.engine.data.metadata.edm.v3.ValueTerm;
import com.msopentech.odatajclient.engine.data.metadata.edm.v3.Association;
import com.msopentech.odatajclient.engine.data.metadata.edm.v3.Using;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.msopentech.odatajclient.engine.data.metadata.edm.v4.Action;
import com.msopentech.odatajclient.engine.data.metadata.edm.v4.Annotation;
import com.msopentech.odatajclient.engine.data.metadata.edm.v4.Function;
import com.msopentech.odatajclient.engine.data.metadata.edm.v4.TypeDefinition;
import com.msopentech.odatajclient.engine.utils.ODataVersion;
import java.io.IOException;

@SuppressWarnings("rawtypes")
public class SchemaDeserializer extends AbstractEdmDeserializer<AbstractSchema> {

    @Override
    protected AbstractSchema doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        final AbstractSchema schema = ODataVersion.V3 == client.getWorkingVersion()
                ? new com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema()
                : new com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema();

        for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
            final JsonToken token = jp.getCurrentToken();
            if (token == JsonToken.FIELD_NAME) {
                if ("Namespace".equals(jp.getCurrentName())) {
                    schema.setNamespace(jp.nextTextValue());
                } else if ("Alias".equals(jp.getCurrentName())) {
                    schema.setAlias(jp.nextTextValue());
                } else if ("Using".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                            getUsings().add(jp.getCodec().readValue(jp, Using.class));
                } else if ("Association".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                            getAssociations().add(jp.getCodec().readValue(jp, Association.class));
                } else if ("ComplexType".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    if (schema instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                                getComplexTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v3.ComplexType.class));
                    } else {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).
                                getComplexTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v4.ComplexType.class));
                    }
                } else if ("EntityType".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    if (schema instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                                getEntityTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v3.EntityType.class));
                    } else {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).
                                getEntityTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v4.EntityType.class));
                    }
                } else if ("EnumType".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    if (schema instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                                getEnumTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v3.EnumType.class));
                    } else {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).
                                getEnumTypes().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v4.EnumType.class));
                    }
                } else if ("ValueTerm".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                            getValueTerms().add(jp.getCodec().readValue(jp, ValueTerm.class));
                } else if ("EntityContainer".equals(jp.getCurrentName())) {
                    jp.nextToken();

                    if (schema instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).
                                getEntityContainers().add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v3.EntityContainer.class));
                    } else {
                        com.msopentech.odatajclient.engine.data.metadata.edm.v4.EntityContainer entityContainer =
                                jp.getCodec().readValue(jp,
                                        com.msopentech.odatajclient.engine.data.metadata.edm.v4.EntityContainer.class);
                        entityContainer.setDefaultEntityContainer(true);
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).
                                setEntityContainer(entityContainer);
                    }
                } else if ("Annotations".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    if (schema instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Schema) schema).getAnnotationsList().
                                add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v3.Annotations.class));
                    } else {
                        ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).getAnnotationsList().
                                add(jp.getCodec().readValue(jp,
                                                com.msopentech.odatajclient.engine.data.metadata.edm.v4.Annotations.class));
                    }
                } else if ("Action".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).getActions().
                            add(jp.getCodec().readValue(jp, Action.class));
                } else if ("Annotation".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).getAnnotations().
                            add(jp.getCodec().readValue(jp, Annotation.class));
                } else if ("Function".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).getFunctions().
                            add(jp.getCodec().readValue(jp, Function.class));
                } else if ("TypeDefinition".equals(jp.getCurrentName())) {
                    jp.nextToken();
                    ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Schema) schema).
                            getTypeDefinitions().add(jp.getCodec().readValue(jp, TypeDefinition.class));
                }
            }
        }

        return schema;
    }
}


text:
function [indices,type_id,groups] = getTypeIndices(obj,types_to_get)
%getTypeIndices
%
%    [indices,type_id,groups] = getTypeIndices(obj,types_to_get)
%
%    The simplest way to understand this function may be to examine
%    the example.
%
%    INPUTS
%    ======================================================================
%    types_to_get : (cellstr), types for which we want
%                    information about
%
%    OUTPUTS
%    ======================================================================
%    indices  : ([1 x n]) original indices containing one of the types
%                (sorted)
%    type_ids : ([1 x n]), for each entry, which of the
%                requested types it matches, 1 indicates it matches the
%                first type entry, 2, the second entry, etc.
%    groups   : ({1 x n_unique}), for each unique type, this indexes
%                into the two above properties, specifying which belong
%                to the specified type. It does NOT index into the original
%                set of entries, that would be done via indices(groups{#})
%
%
%   EXAMPLE
%   =======================================================================
%   getTypeIndices(obj,{'<NAME>' '<INT>' 'FOR'})
%
%     1 2  3  4  5  6
%     ---------------------------------------------------------------
%     1 10 20 30 51 70 <= indices
%     1 2  1  3  1  2  <= type_ids -  1 => <NAME>, 2 => <INT> 3 => 'FOR'
%
%     groups:
%     {1 3 5}          <= for each request, which are of this type ...
%     {2 6}
%     {4}

if ischar(types_to_get)
    types_to_get = {types_to_get};
end

n_types_get = length(types_to_get);

myMap       = obj.unique_types_map;
is_key_mask = myMap.isKey(types_to_get);
n_found     = sum(is_key_mask);

if n_found == 0
    indices = [];
    type_id = [];
    groups  = cell(1,n_types_get);
    return
end

indices_of_entries_of_type_ca = myMap.values(types_to_get(is_key_mask));

if n_found == 1
   indices = indices_of_entries_of_type_ca{1};
   type_id = ones(1,length(indices));
   groups  = cell(1,n_types_get);
   groups{is_key_mask} = 1:length(indices);
   return
end

n_entries           = length(obj.line_numbers);
untruncated_type_id = zeros(1,n_entries);

cur_value_index = 0;
for iTypeGet = find(is_key_mask)

    %NOTE: The values are aligned only to those present
    %not to all requested values, thus we need to loop index variables
    cur_value_index = cur_value_index + 1;

    type_indices_in_original = indices_of_entries_of_type_ca{cur_value_index};
    untruncated_type_id(type_indices_in_original) = iTypeGet;
end

valid_indices_mask = untruncated_type_id ~= 0;
indices            = find(valid_indices_mask);
type_id            = untruncated_type_id(valid_indices_mask);

%NOTE: final_indices is only used at the places where the
%valid_indices_mask is true. Importantly though, the indexing
%order is the same as the original entries, so we can now go
%back and translate from indices that are relevant for all
%entries to indices that are relevant only for the truncated
%subset of entries.
%
%The values of final_indices are only relevant for the
%truncated subset. Indexes into final_indices exist for all values, not
%just truncated values.
final_indices = cumsum(valid_indices_mask);

cur_value_index = 0;
groups = cell(1,n_types_get);
for iTypeGet = find(is_key_mask)
    cur_value_index = cur_value_index + 1;

    type_indices_in_original = indices_of_entries_of_type_ca{cur_value_index};
    groups{iTypeGet} = final_indices(type_indices_in_original);
end

end


text:
def whyrun_supported?
  true
end

use_inline_resources

# Chef 11 backwards compability for OpsWorks
if respond_to?(:provides)
  provides :rbenv_rehash
end

include Chef::Rbenv::ScriptHelpers

action :run do
  set_updated { run_script }
end

def run_script
  command = %(rbenv rehash)

  rbenv_script "#{command} #{which_rbenv}" do
    code command
    user new_resource.user if new_resource.user
    root_path new_resource.root_path if new_resource.root_path
    action :run
  end
end


text:
package ca.ontario.ecorr.controller;

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

import javax.inject.Inject;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import ca.ontario.ecorr.payloads.ECorrTask;
import ca.ontario.ecorr.payloads.IncomingCorrespondence;
import ca.ontario.ecorr.payloads.ResponseCorrespondence;
import ca.ontario.ecorr.payloads.TaskQueryFilter;
import ca.ontario.ecorr.service.CorrespondenceService;

@Controller
@RequestMapping("correspondence")
public class CorrespondenceController {
	@Inject
	private CorrespondenceService service;

	@RequestMapping(value = "/incoming", method = RequestMethod.PUT, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Map<String, Object> receiveIncoming(@RequestBody IncomingCorrespondence incoming) {
		return service.receiveIncoming(incoming);
	}

	@RequestMapping(value = "/tasks/{id}/complete", method = RequestMethod.POST, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public void completeTask(@PathVariable String id) {
		service.completeTask(id);
	}

	@RequestMapping(value = "/tasks/{id}/completeResponse", method = RequestMethod.POST, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public void completeRespondTask(@PathVariable String id) {
		throw new UnsupportedOperationException("completeResponse method is no longer implemented");
	}

	@RequestMapping(value = "/tasks/{id}", method = RequestMethod.GET, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public ECorrTask getTaskById(@PathVariable String id) {
		return service.getTaskById(id);
	}

	@RequestMapping(value = "/tasks/searches", method = RequestMethod.POST, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public List<ECorrTask> searchTasks(@RequestBody TaskQueryFilter tqf) {
		return service.searchTasks(tqf);
	}

	@RequestMapping(value = "/tasks/{id}/response", method = RequestMethod.POST, produces = "application/json")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public String taskUpdatResponse(@PathVariable String id,
									@RequestBody ResponseCorrespondence rc) {
		return service.updateResponse(id, rc);
	}

}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* FulltextReference.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System.Xml.Serialization;

using AM;

using JetBrains.Annotations;

using ManagedIrbis.Mapping;

using MoonSharp.Interpreter;

using Newtonsoft.Json;

#endregion

namespace ManagedIrbis.Fulltext
{
    //
    // Ссылка на объект полнотекстового поиска в общем случае
    // содержит следующие структурные элементы:
    //
    // * URL
    // * Путь к текстовому файлу
    // * Номер страницы
    // * Путь к файлу архива
    // * Путь к файлу внутри архива
    // * Имя файла с текстом-подложкой
    // * Полный путь для относительной ссылки (является избыточным
    // и поддерживается по историческим причинам)
    //
    // В зависимости от вида ссылка содержит те или иные элементы.
    //

    //
    // Структура, используемая для хранения ссылки в базе данных
    // представляет собой совокупность подполей ^B^C^I^T^U:
    //
    // B - в зависимости от вида ссылки это относительный, полный
    // или виртуальный путь к файлу полного текста, или же некоторые данные,
    // дополняющие гиперссылку. Относительный путь используется
    // для полнотекстовых документов, хранящихся в папке базы данных
    // (относительный путь начинается с точки). Полные пути используются
    // для ссылок на полнотекстовые документы, находящиеся вне папки
    // базы данных. Виртуальные пути к текстовым документам используются
    // для ссылок на полнотекстовые документы, хранящиеся
    // в архивах .zip и .rar, а также в случае ссылок на отдельные
    // страницы многостраничных документов .pdf и .djvu.
    // Виртуальная ссылка, хранящаяся в этом подполе, позволяет узнать
    // имя файла внутри архива или номер страницы многостраничного документа,
    // но не имя файла архива или многостраничного документа.
    // C - полный путь к файлу zip/rar/pdf/djvu. Данное подполе используется
    // для ссылок на полнотекстовые документы в архиве или отдельные
    // страницы многостраничного документа.
    // I - URL текста, перенесённого из электронного каталога.
    // T - ссылка на файл подложки. Представляет собой имя текстового файла,
    // подразумевается, что местонахождение файла подложки соответствует
    // местонахождению полнотекстового документа.
    // U – введено для технологических целей в версии 2010.1.
    // Подполе ^U было задумано как универсальная замена подполям ^B^C^I
    // с возможностью расширения, однако было признано неудобным
    // с точки зрения его разбора средствами языка форматирования.
    // Как следствие, подполе ^U остаётся вспомогательным,
    // и используется наряду с другими подполями.
    //

    /// <summary>
    /// Ссылка на объект полнотекстового поиска.
    /// Поле 952.
    /// </summary>
    [PublicAPI]
    [MoonSharpUserData]
    public class FullTextReference
    {
        #region Constants

        /// <summary>
        /// Field tag.
        /// </summary>
        public const int Tag = 952;

        #endregion

        #region Properties

        /// <summary>
        /// Имя файла полного текста. Данное подполе используется
        /// только для хранения ссылок на полнотекстовые документов
        /// в архиве с именем базы данных и расширением .izp,
        /// находящемся в папке базы данных.
        /// Начиная с версии 2010.1 данный вид ссылок не поддерживается.
        /// Подполе a.
        /// </summary>
        [CanBeNull]
        [SubField('a')]
        [XmlAttribute("fileName")]
        [JsonProperty("fileName", NullValueHandling = NullValueHandling.Ignore)]
        public string FileName { get; set; }

        /// <summary>
        /// Дополнительная информация.
        /// Подполе b.
        /// </summary>
        /// <remarks>
        /// Подполе ^B конструируется следующим образом:
        /// [путь к файлу (без имени файла)] + [имя файла (без расширения)]
        /// + [суффикс] + [номер страницы] + [расширение файла]
        /// </remarks>
        [CanBeNull]
        [SubField('b')]
        [XmlAttribute("info")]
        [JsonProperty("info", NullValueHandling = NullValueHandling.Ignore)]
        public string Info { get; set; }

        /// <summary>
        /// Отдельная страница многостраничного документа (путь к файлу).
        /// Подполе c.
        /// </summary>
        [CanBeNull]
        [SubField('c')]
        [XmlAttribute("separatePage")]
        [JsonProperty("separatePage", NullValueHandling = NullValueHandling.Ignore)]
        public string SeparatePage { get; set; }

        /// <summary>
        /// URL.
        /// Подполе i.
        /// </summary>
        [CanBeNull]
        [SubField('i')]
        [XmlAttribute("url")]
        [JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)]
        public string Url { get; set; }

        /// <summary>
        /// Имя файла с текстом-подложкой.
        /// Местонахождение файла подложки соответствует местонахождению
        /// основного файла.
        /// Подполе t.
        /// </summary>
        [CanBeNull]
        [SubField('t')]
        [XmlAttribute("substrate")]
        [JsonProperty("substrate", NullValueHandling = NullValueHandling.Ignore)]
        public string Substrate { get; set; }

        /// <summary>
        /// Введено для технологических целей в версии 2010.1.
        /// Подполе ^U было задумано как универсальная замена
        /// подполям ^B^C^I с возможностью расширения, однако было
        /// признано неудобным с точки зрения его разбора средствами
        /// языка форматирования. Как следствие, подполе ^U остаётся
        /// вспомогательным, и используется наряду с другими подполями.
        /// Подполе ^U всегда начинается с префикса
        /// uri:irbis:
        /// Дальнейшее содержимое зависит от объекта полнотекстового поиска.
        /// </summary>
        [CanBeNull]
        [SubField('u')]
        [XmlAttribute("additional")]
        [JsonProperty("additional", NullValueHandling = NullValueHandling.Ignore)]
        public string Additional { get; set; }

        /// <summary>
        /// Associated <see cref="RecordField"/>.
        /// </summary>
        [CanBeNull]
        [XmlIgnore]
        [JsonIgnore]
        public RecordField Field { get; set; }

        /// <summary>
        /// Arbitrary user data.
        /// </summary>
        [CanBeNull]
        [XmlIgnore]
        [JsonIgnore]
        public object UserData { get; set; }

        #endregion

        #region Public methods

        /// <summary>
        /// Parse the field.
        /// </summary>
        [CanBeNull]
        public static FullTextReference Parse
            (
                [CanBeNull] RecordField field
            )
        {
            if (ReferenceEquals(field, null))
            {
                return null;
            }

            FullTextReference result = new FullTextReference
            {
                FileName = field.GetFirstSubFieldValue('a'),
                Info = field.GetFirstSubFieldValue('b'),
                SeparatePage = field.GetFirstSubFieldValue('c'),
                Url = field.GetFirstSubFieldValue('i'),
                Substrate = field.GetFirstSubFieldValue('t'),
                Additional = field.GetFirstSubFieldValue('u'),
                Field = field
            };

            return result;
        }

        #endregion

        #region Object members

        /// <inheritdoc cref="object.ToString" />
        public override string ToString()
        {
            return Info.ToVisibleString();
        }

        #endregion
    }
}


text:
With Broccoli 1.0, the Broccoli plugin API is changing.

If you are a Broccoli user wishing to upgrade to Broccoli 1.0, or if you are a
plugin author wishing to make your plugin compatible with Broccoli 1.0, then
this document is for you.

## Overview

The old API requires that a plugin implement a `.read` or `.rebuild` method.

The new API requires that a plugin be a subclass of
[broccoli-plugin](https://github.com/broccolijs/broccoli-plugin).

Broccoli 0.x can run plugins that use either the old or the new API.

Broccoli 1.x can only run plugins that use the new API. In return, we get new
features, such as improved error reporting and being able to control the
location of temporary directories, as well as future extensibility.

### Cosmetic changes

Along with the API change, we are making two stylistic changes in convention:
We used to call plugin instances "trees", but we now prefer calling them
"nodes" (as in "nodes in the build graph"). We also prefer using explicit
`new` to instantiate plugins.

```js
// Old convention:
var outputTree = jshintTree(inputTree);
// New convention:
var outputNode = new JSHinter(inputNode);
```

Both styles will continue to work, but we'll gradually change code and
documentation to follow the new convention.

## For Broccoli users: Upgrading to Broccoli 1.x

### Making sure all your plugins are compatible

If you are using Broccoli 0.16.5 or newer right now, set the
`BROCCOLI_WARN_READ_API` environment variable to find out whether all your
plugins are compatible with Broccoli 1.0:

```bash
BROCCOLI_WARN_READ_API=y broccoli serve
# Or, for Ember CLI users:
BROCCOLI_WARN_READ_API=y ember server
```

If you get warnings about a plugin using the deprecated `.read/.rebuild` API,
try upgrading that plugin to the latest version. If the latest version of a
plugin still isn't compatible, consider opening an issue on its GitHub repo,
or better yet, send a pull request.

### Upgrading to Broccoli 1.0

If you depend on the "broccoli" package directly, then bump the version spec
in your `package.json` like so:

```json
"broccoli": "^1.0.0-beta.2"
```

The command-line interface (`broccoli serve` and `broccoli build`) is still
the same. However, the programmatic API (`require('broccoli')`) has changed a
bit. If you are using Broccoli programmatically, refer to
[CHANGELOG.md](https://github.com/broccolijs/broccoli/blob/master/CHANGELOG.md)
to see what has changed.

Ember CLI users: Due to the changes in Broccoli's programmatic API, you cannot
use Broccoli 1.0 through the `ember` tool until Ember CLI is updated. However,
if you still want to give Broccoli 1.0 a spin right now, try using the
following hack:

```bash
npm install broccoli@^1.0.0-beta.2
echo "module.exports = require('./ember-cli-build')();" > Brocfile.js
broccoli serve
```

## For plugin authors: Updating your plugin to use the new API

Updating your plugin will make it ready for Broccoli 1.x without breaking
backwards compatibility with Broccoli 0.x.

### broccoli-filter

If your plugin subclasses
[broccoli-filter](https://github.com/broccolijs/broccoli-filter), upgrade to
broccoli-filter 1.0.0 or newer. Be sure to call the base class constructor as
detailed [in the README](https://github.com/broccolijs/broccoli-filter/blob/master/README.md#upgrading-from-01x-to-1x);
other than that, no changes are needed.

### broccoli-caching-writer

If your plugin subclasses
[broccoli-caching-writer](https://github.com/ember-cli/broccoli-caching-writer),
upgrade to broccoli-caching-writer 2.0.0.

With version 2.0.0, broccoli-caching-writer's API is a drop-in replacement for
broccoli-plugin. As a result, its API is completely different from
broccoli-caching-writer 0.x/1.x, and your plugin's code will need to be
updated. To do so, it's best to read the
[broccoli-plugin README](https://github.com/broccolijs/broccoli-plugin) to
familiarize yourself with the new API, while replacing all instances of
`Plugin` with `CachingWriter` in your plugin code.

As a guide, where you previously implemented

```js
MyPlugin.prototype.updateCache = function(sourcePaths, destPath) {
  // Compile from sourcePaths into destPath
}
```

you'll now want to implement

```js
MyPlugin.prototype.build = function() {
  // Compile from this.inputPaths into this.outputPath
}
```

If you always have exactly one input node, use `this.inputPaths[0]`.

### broccoli-writer or no baseclass

If your plugin subclasses
[broccoli-writer](https://github.com/broccolijs/broccoli-writer) or implements
`.read` or `.rebuild` directly without using a baseclass, subclass
[broccoli-plugin](https://github.com/broccolijs/broccoli-plugin) instead.

If you were using broccoli-writer, your implementation might have looked
something like this:

```js
var Writer = require('broccoli-writer');

MyPlugin.prototype = Object.create(Writer.prototype);
MyPlugin.prototype.constructor = MyPlugin;
function MyPlugin(inputTree) {
  this.inputTree = inputTree;
}

MyPlugin.prototype.write = function(readTree, destDir) {
  readTree(this.inputTree).then(function(srcDir) {
    // Build from srcDir to destDir
  });
};
```

With broccoli-plugin, the same plugin might be implemented like this:

```js
var Plugin = require('broccoli-plugin');

MyPlugin.prototype = Object.create(Plugin.prototype);
MyPlugin.prototype.constructor = MyPlugin;
function MyPlugin(inputNode) {
  Plugin.call(this, [inputNode]);
}

MyPlugin.prototype.build = function() {
  // Build from this.inputPaths[0] to this.outputPath
};
```

See the [broccoli-plugin](https://github.com/broccolijs/broccoli-plugin)
README for details.


text:
var spawn = require('child_process').spawn, fs = require('fs');

var Compiler = function (coffee, fileEncoding) {
	if (!(this instanceof Compiler))
		return new Compiler(coffee);
	this.coffee = coffee == null ? 'coffee' : coffee;
	this.fileEncoding = fileEncoding == null ? 'utf-8' : fileEncoding;
};

Compiler.prototype.compile = function () {
	var
		args = ['-c', '-p', '-s'],
		config = arguments.length === 3 ? arguments[1] : {},
		callback = arguments[arguments.length - 1],
		that = this;

	var doCompile = function (input) {
		var out, child = spawn(that.coffee, args);
		child.stdout.setEncoding('utf-8');
		child.stdout.on('data', function (data) {
			out = data;
		});
		child.on('exit', function (status) {
			if (config.writeFile) {
				fs.writeFile(config.writeFile, out, that.fileEncoding, function (err) {
					if (err) throw err;
					callback(status, out);
				});
			} else {
				callback(status, out);
			}
		});
		child.stdin.write(input);
		child.stdin.end();
	};

	if (config.bare)
		args.push('-b');

	if (config.asFileName) {
		fs.readFile(arguments[0], this.fileEncoding, function (err, data) {
			if (err) throw err;
			doCompile(data);
		});
	} else {
		doCompile(arguments[0]);
	}

};

module.exports = Compiler;