text:
namespace baidu {
namespace galaxy {

struct AgentInfoExtend {
    Resource free;
    Resource unassigned;
    AgentInfo* agent_info;
    boost::unordered_set<std::string> labels_set;
    boost::unordered_set<int32_t> used_port_set;

    AgentInfoExtend(AgentInfo* p_agent_info):free(),
                                           unassigned(){
        if (p_agent_info != NULL) {
            agent_info = p_agent_info;
        }else {
            assert(false);
        }
    }

    void CalcExtend();
    ~AgentInfoExtend(){
        delete agent_info;
    }
};

struct PodScaleUpCell {
    PodDescriptor* pod;
    JobInfo* job;
    uint32_t schedule_count;
    uint32_t feasible_limit;
    std::vector<std::string> pod_ids;
    std::vector<AgentInfoExtend*> feasible;
    std::vector<std::pair<double, AgentInfo*> > sorted;

    PodScaleUpCell();

    bool FeasibilityCheck(const AgentInfoExtend* agent_info);

    int32_t Score();

    double ScoreAgent(const AgentInfo* agent_info,
                       const PodDescriptor* desc);

    int32_t Propose(std::vector<ScheduleInfo*>* propose);

    bool VolumeFit(std::vector<Volume>& unassigned,
                   std::vector<Volume>& required);

};

struct PodScaleDownCell {
    PodDescriptor* pod;
    JobInfo* job;
    uint32_t scale_down_count;
    std::map<std::string, AgentInfo*> pod_agent_map;
    std::vector<std::pair<double, std::string> > sorted_pods;
    PodScaleDownCell();
    int32_t Score();

    double ScoreAgent(const AgentInfo* agent_info,
                       const PodDescriptor* desc);

    int32_t Propose(std::vector<ScheduleInfo*>* propose);
};

class Scheduler {

public:
    static double CalcLoad(const AgentInfo* agent);

    Scheduler() : schedule_turns_(0){}
    ~Scheduler() {}

    // @brief 调度算入口: scale u
    // @note 调用者负责销毁 propose
    int32_t ScheduleScaleUp(std::vector<JobInfo*>& pending_jobs,
                     std::vector<ScheduleInfo*>* propose);

    // 调度算入口: scale down
    // @note 调用者负责销毁 propose
    int32_t ScheduleScaleDown(std::vector<JobInfo*>& reducing_jobs,
                     std::vector<ScheduleInfo*>* propose);

    int32_t ScheduleUpdate(std::vector<JobInfo*>& update_jobs,
                           std::vector<ScheduleInfo*>* propose);
    // 从master同步资源数据
    int32_t SyncResources(const GetResourceSnapshotResponse* response);

    // master通知AgentInfo信息过期,需要更新
    int32_t UpdateAgent(const AgentInfo* agent_info);

    void BuildSyncRequest(GetResourceSnapshotRequest* request);

private:

    int32_t ChoosePods(std::vector<JobInfo*>& pending_jobs,
                       std::vector<PodScaleUpCell*>* pending_pods);

    int32_t ChooseReducingPod(std::vector<JobInfo*>& reducing_jobs,
                std::vector<PodScaleDownCell*>* reducing_pods);

    int32_t ChooseResourse(std::vector<AgentInfoExtend*>* resources_to_alloc);

    void HandleJobUpdate(JobInfo* job_info,
                        std::vector<ScheduleInfo*>* propose);
    template<class T>
    void Shuffle(std::vector<T>& list) {
        for (size_t i = list.size(); i > 1; i--) {
            T tmp = list[i-1];
            size_t target_index = ::rand() % i ;
            list[i-1] = list[target_index];
            list[target_index] = tmp;
        }
    }

private:
    boost::unordered_map<std::string, AgentInfoExtend*> resources_;
    int64_t schedule_turns_;    // 当前调度轮数
};

} // galaxy
}// baidu
#endif


text:
package co.jasonwyatt.squeaky;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import co.jasonwyatt.squeaky.util.Logger;

/**
 *

 * Database is the central class in Squeaky.  Instances of {@link Database} are responsible for
 * managing SQLite tables assigned to them as instances of {@link Table} using
 * {@link Database#addTable(Table)}.
 *

 *
 *

 * Once all required Tables have been added to the database, a call to {@link Database#prepare()}
 * will trigger any necessary migrations and will place the Database instance in to a state where
 * it is ready to accept queries.
 *

 */
public class Database {
    private static final String DEFAULT_VERSIONS_TABLE_NAME = "versions";
    private final Class<? extends DatabaseHelper> mHelperClass;
    private static final int SQLITE_DB_VERSION = 1;
    private HashMap<String, Table> mTables = new HashMap<>();

    private final VersionsTable mVersionsTable;
    private final String mName;
    private final Context mContext;
    private DatabaseHelper mHelper;
    private SQLiteDatabase mWritableDB;
    private SQLiteDatabase mReadableDB;
    private boolean mPrepared;

    /**
     * Creates a new instance of {@link Database} using the default {@link DatabaseHelper} class.
     * @param context Android context.
     * @param name Name of the database.
     */
    public Database(Context context, String name) {
        this(context, name, DatabaseHelper.class);
    }

    /**
     * Creates a new instance of {@link Database}, allowing for a customized {@link DatabaseHelper}
     * class to be provided.
     * @param context Android context.
     * @param name Name of the database.
     * @param helper Helper used to listen to requests from Android's SQLiteDatabase system for
     *               creation/migration and passes those requests on to {@link Database}
     */
    public Database(Context context, String name, Class<? extends DatabaseHelper> helper) {
        this(context, name, DEFAULT_VERSIONS_TABLE_NAME, helper);
    }

    /**
     * Creates a new instance of {@link Database}, allowing for a customized name of the table used
     * to track {@link Table} versions.
     * @param context Android context.
     * @param name Name of the database.
     * @param versionsTableName Name of the versions table.
     */
    public Database(Context context, String name, String versionsTableName) {
        this(context, name, versionsTableName, DatabaseHelper.class);
    }

    /**
     * Creates a new instance of {@link Database}, allowing for a customized {@link DatabaseHelper}
     * class and a custom version table to be provided.
     * @param context Android context.
     * @param name Name of the database.
     * @param versionsTableName Name of the versions table.
     * @param helper Helper used to listen to requests from Android's SQLiteDatabase system for
     *               creation/migration and passes those requests on to {@link Database}
     */
    public Database(Context context, String name, String versionsTableName, Class<? extends DatabaseHelper> helper) {
        mHelperClass = helper;
        mName = name;
        mContext = context;
        mVersionsTable = new VersionsTable(this, versionsTableName);
    }

    /**
     * Get the name of the database.
     * @return Name of the database.
     */
    public String getName() {
        return mName;
    }

    /**
     * Add a {@link Table} to the Database definition.
     * @param t Table to add.
     */
    public void addTable(Table t) {
        if (!mTables.containsKey(t.getName())) {
            mTables.put(t.getName(), t);
        }
    }

    /**
     * Prepare the database by instantiating a {@link DatabaseHelper} and establishing connections
     * to the database.  Calling {@link #prepare()} again after the Database is already prepared
     * will throw a {@link DatabaseException}.  If you need to re-prepare a database (to add or
     * migrate a {@link Table} definition), call {@link #close()} first, add your tables, then
     * re-call {@link #prepare()}.
     * @see #isPrepared()
     */
    public void prepare() {
        if (mPrepared) {
            throw new DatabaseException("Cannot re-prepare a prepared database!");
        }
        try {
            Constructor<? extends DatabaseHelper> c = mHelperClass.getDeclaredConstructor(Context.class, String.class, int.class);
            mHelper = c.newInstance(mContext, mName, SQLITE_DB_VERSION);
            mWritableDB = mHelper.getWritableDatabase();
            mReadableDB = mHelper.getReadableDatabase();
            doMigrations(mWritableDB);
            mPrepared = true;
        } catch (NoSuchMethodException e) {
            throw new DatabaseException("Provided database helper class does not expose a constructor of the form (Context, String, int)", e);
        } catch (InvocationTargetException e) {
            throw new DatabaseException("Error instantiating database helper.", e);
        } catch (InstantiationException e) {
            throw new DatabaseException("Error instantiating database helper.", e);
        } catch (IllegalAccessException e) {
            throw new DatabaseException("Error instantiating database helper.", e);
        }
    }

    /**
     * Close the helper and database connections.
     */
    @SuppressWarnings("WeakerAccess")
    public void close() {
        mHelper.close();
        mWritableDB.close();
        mReadableDB.close();
        mPrepared = false;
    }

    /**
     * Returns whether or not the {@link Database} instance is prepared.
     * @return Whether or not the Database is prepared.
     */
    @SuppressWarnings("WeakerAccess")
    public boolean isPrepared() {
        return mPrepared;
    }

    /**
     * Query the database.
     * @param stmt SQL Query
     * @param bindArgs Parameters mapping to '?'s in the stmt.
     * @return An instance of {@link android.database.Cursor} giving you access to the results of
     *          the query.
     */
    public synchronized Cursor query(String stmt, Object... bindArgs) {
        if (!mPrepared) {
            throw new DatabaseException("Database "+getName()+" not prepared yet.");
        }
        String[] args = null;
        if (bindArgs != null) {
            args = new String[bindArgs.length];
            for (int i = 0; i < bindArgs.length; i++) {
                Object arg = bindArgs[i];
                args[i] = arg.toString();
            }
        }

        Cursor result = getReadableDB().rawQuery(stmt, args);
        Logger.i(stmt+";", args);
        return result;
    }

    // Used before mReadableDB is available.
    private Cursor querySimple(SQLiteDatabase db, String stmt, Object... bindArgs) {
        String[] args = null;
        if (bindArgs != null) {
            args = new String[bindArgs.length];
            for (int i = 0; i < bindArgs.length; i++) {
                Object arg = bindArgs[i];
                if (arg instanceof String) {
                    args[i] = DatabaseUtils.sqlEscapeString((String) arg);
                } else {
                    args[i] = arg.toString();
                }
            }
        }

        Cursor result = db.rawQuery(stmt, args);
        Logger.i(stmt+";", args);
        return result;
    }

    /**
     * Insert a record in to the database and receive its rowid or _id
     * value as a result.
     * @param stmt Insert query. (not enforced, but encouraged)
     * @param bindArgs Arguments to bind to '?'s in the query.
     * @return Value of the new record's rowid/_id column.
     */
    @SuppressWarnings("WeakerAccess")
    public synchronized long insert(String stmt, Object... bindArgs) {
        SQLiteStatement statement = getWritableDB().compileStatement(stmt);
        bindArgs(statement, bindArgs);
        Logger.i(stmt+";", bindArgs);
        return statement.executeInsert();
    }

    /**
     * Run an update/delete query on the database
     * @param stmt Query to execute.
     * @param bindArgs Arguments to bind to '?'s in the query.
     * @return Number of affected rows.
     */
    public synchronized int update(String stmt, Object... bindArgs) {
        if (bindArgs == null) {
            return updateBatch(new String[] {stmt}, null, false);
        }
        return updateBatch(new String[] {stmt}, new Object[][] {bindArgs}, false);
    }

    /**
     * Run a bunch of updates/deletes/inserts on the database at once, optionally within a
     * transaction.
     * @param stmts Array of statements to execute.
     * @param bindArgs Arguments to bind to '?'s in the queries. (Optional, if not needed, pass
     *                 null)  Condition: bindArgs.length == stmts.length if not null.
     * @param withTransaction Whether or not to execute the updates within a transaction.
     * @return Number of updated records.
     */
    public synchronized int updateBatch(String[] stmts, Object[][] bindArgs, boolean withTransaction) {
        boolean hasArgs = bindArgs != null;
        if (hasArgs && bindArgs.length != stmts.length) {
            throw new DatabaseException("bindArgs.length != stmts.length");
        }

        if (withTransaction) {
            getWritableDB().beginTransaction();
        }

        int rows = 0;
        for (int i = 0; i < stmts.length; i++) {
            SQLiteStatement statement = getWritableDB().compileStatement(stmts[i]);
            if (hasArgs) {
                bindArgs(statement, bindArgs[i]);
            }
            try {
                rows += statement.executeUpdateDelete();
            } finally {
                statement.close();
            }
            Logger.i(stmts[i]+";", bindArgs[i]);
        }

        if (withTransaction) {
            getWritableDB().endTransaction();
        }

        return rows;
    }

    private void updateSimple(SQLiteDatabase db, String stmt, Object... bindArgs) {
        if (bindArgs != null) {
            updateBatchSimple(db, new String[]{stmt}, new Object[][]{bindArgs});
        } else {
            updateBatchSimple(db, new String[]{stmt}, null);
        }
    }

    private void updateBatchSimple(SQLiteDatabase db, String[] stmts, Object[][] bindArgs) {
        boolean hasArgs = bindArgs != null;
        if (hasArgs && bindArgs.length != stmts.length) {
            throw new DatabaseException("bindArgs.length != stmts.length");
        }

        for (int i = 0; i < stmts.length; i++) {
            if (!stmts[i].endsWith(";")) {
                stmts[i] += ";";
            }
            if (hasArgs && bindArgs[i] != null) {
                Logger.i(stmts[i], bindArgs[i]);
                db.execSQL(stmts[i], bindArgs[i]);
            } else {
                Logger.i(stmts[i]);
                db.execSQL(stmts[i]);
            }
        }
    }

    private void bindArgs(SQLiteStatement statement, Object[] args) {
        if (args == null) {
            return;
        }
        for (int i = 0; i < args.length; i++) {
            Object o = args[i];
            if (o instanceof String) {
                statement.bindString(i + 1, (String) o);
            } else if (o instanceof byte[]) {
                statement.bindBlob(i + 1, (byte[]) o);
            } else if (o instanceof Integer) {
                statement.bindLong(i+1, (Integer) o);
            } else if (o instanceof Long) {
                statement.bindLong(i + 1, (Long) o);
            } else if (o instanceof Double) {
                statement.bindDouble(i+1, (Double) o);
            } else if (o instanceof Float) {
                statement.bindDouble(i+1, (double) (Float) o);
            } else if (o == null) {
                statement.bindNull(i+1);
            } else if (o instanceof BlobValue) {
                statement.bindBlob(i+1, ((BlobValue) o).getBytes());
            } else if (o instanceof Boolean) {
                statement.bindLong(i+1, (Boolean)o ? 1 : 0);
            } else {
                statement.bindString(i+1, o.toString());
            }
        }
    }

    private void doMigrations(SQLiteDatabase db) {
        Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
        boolean needVersionsTable = true;
        while ( c.moveToNext() ) {
            if (c.getString(0).equals(mVersionsTable.getName())) {
                needVersionsTable = false;
                break;
            }
        }
        c.close();

        if (needVersionsTable) {
            updateBatchSimple(db, mVersionsTable.getCreateTable(), null);
        }

        Map<String, Integer> versions = mVersionsTable.getTableVersions(db);

        for (Table t : mTables.values()) {
            if (versions.containsKey(t.getName())) {
                // have a version, need to upgrade?
                if (t.getVersion() == Table.DROP_TABLE) {
                    updateSimple(db, "DELETE FROM "+mVersionsTable.getName()+" WHERE table_name = ?", t.getName());
                    updateSimple(db, "DROP TABLE "+t.getName());
                } else {
                    boolean changed = false;
                    for (int currentVersion = versions.get(t.getName()); currentVersion < t.getVersion(); currentVersion++) {
                        changed = true;
                        Logger.d("Upgrading", t.getName(), "from", "v" + currentVersion, "to", "v" + (currentVersion + 1));
                        String[] migrateStmts = t.getMigration(currentVersion + 1);
                        updateBatchSimple(db, migrateStmts, null);
                    }
                    if (changed) {
                        updateSimple(db, "UPDATE " + mVersionsTable.getName() + " SET version = ? WHERE table_name = ?", t.getVersion(), t.getName());
                    }
                }
            } else {
                // need to create.
                Logger.d("Creating new table:", t.getName(), "at version", t.getVersion());
                String[] createStmts = t.getCreateTable();
                updateBatchSimple(db, createStmts, null);
                updateSimple(db, "INSERT INTO "+mVersionsTable.getName()+" (table_name, version) VALUES (?, ?)", t.getName(), t.getVersion());
            }
        }
    }

    /**
     * Get the {@link android.content.Context} associated with the Database.
     * @return {@link android.content.Context} associated with the Database.
     */
    public Context getContext() {
        return mContext;
    }

    /**
     * Get the instance of {@link Database.VersionsTable} used by this Database.
     * @return The {@link Database.VersionsTable} used by the Database.
     */
    public Table getVersionsTable() {
        return mVersionsTable;
    }

    /**
     * Get the {@link Table} instances associated with this Database.
     * @return {@link Table} instances associated with the Database.
     */
    public Collection
 getTables() {
        return mTables.values();
    }

    /**
     * Get a raw SQLiteDatabase connection for writing.
     * @return Raw SQLite Database connection.
     */
    @SuppressWarnings("WeakerAccess")
    public SQLiteDatabase getWritableDB() {
        if (mWritableDB == null) {
            mWritableDB = mHelper.getWritableDatabase();
        }
        return mWritableDB;
    }

    /**
     * Get a raw SQLiteDatabase connection for reading.
     * @return Raw SQLite Database connection.
     */
    @SuppressWarnings("WeakerAccess")
    public SQLiteDatabase getReadableDB() {
        if (mReadableDB == null) {
            mReadableDB = mHelper.getReadableDatabase();
        }
        return mReadableDB;
    }

    public void setLogLevel(@Logger.LogLevel int level) {
        Logger.setLevel(level);
    }

    /**
     * {@link Table} definition used to define the SQLite table which tracks the current versions of
     * all other {@link Table}s in the database.
     */
    private static final class VersionsTable extends Table {
        private final Database mDb;
        private final String mName;

        VersionsTable(Database db, String name) {
            mDb = db;
            mName = name;
        }

        @Override
        public String getName() {
            return mName;
        }

        @Override
        public int getVersion() {
            return 1;
        }

        @Override
        public String[] getCreateTable() {
            return new String[] {
                    "CREATE TABLE "+getName()+" (\n" +
                    "    `table_name` TEXT NOT NULL,\n"+
                    "    `version` INTEGER NOT NULL\n"+
                    ")"
            };
        }

        @Override
        public String[] getMigration(int nextVersion) {
            return new String[0];
        }

        /**
         * Get the current version of a particular table in the {@link Database}.
         * @param sqldb SQLiteDatabase connection.
         * @param tableName Name of the table for which to retrieve the version.
         * @return Version of the table with name {@param tableName}
         */
        int getTableVersion(SQLiteDatabase sqldb, String tableName) {
            Cursor c = mDb.querySimple(sqldb, "SELECT version FROM "+getName()+" WHERE table_name = ?", tableName);
            int version = -1;
            while (c.moveToNext()) {
                version = c.getInt(0);
            }
            c.close();
            return version;
        }

        /**
         * Get all current versions of tables in the {@link Database}
         * @param sqldb SQLiteDatabase connection.
         * @return Mapping from {@link Table#getName()} to its current version
         *         in the database.
         */
        Map<String, Integer> getTableVersions(SQLiteDatabase sqldb) {
            Cursor c = mDb.querySimple(sqldb, "SELECT table_name, version FROM "+getName());
            HashMap<String, Integer> result = new HashMap<>();

            int modelIndex = c.getColumnIndex("table_name");
            int versionIndex = c.getColumnIndex("version");

            while (c.moveToNext()) {
                result.put(c.getString(modelIndex), c.getInt(versionIndex));
            }

            c.close();
            return result;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _FLEX_LEXER_DECLARE_H
#define _FLEX_LEXER_DECLARE_H

#include <string>
void scan_for_action( std::string command );

#endif  /*  _FLEX_LEXER_DECLARE_H  */


text:
#ifndef __TOOLKIT_H
#define __TOOLKIT_H

/* required headers */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "myxlib.h"

/* function externs */
extern int CreateToolWindow();
extern Display *ToolGetDisplay();
extern Window ToolGetWindow();
extern void ToolSetBackground();
extern void ToolSetForeground();
extern void ToolSetGC();
extern void ToolSetFont();
extern int ToolGetGroup();
extern void ToolSetGroup();
extern int ToolGetState();
extern void ToolSetState();
extern void ToolGetName();
extern void ToolSetName();
extern void ToolCenterText();
extern void ToolDrawName();
extern void ToolSetFunctions();
extern void ToolSetUserFunc();
extern void ToolExec();
extern void NullDrawFunc();
extern void NullUserFunc();
extern void NullEventFunc();
extern void ToolHighlightGroup();
extern void ToolHighlight();
extern void ToolDrawLine();
extern void ToolClear();
extern void ToolRedraw();
extern void ToolResize();
extern int ToolEvent();
extern int DispatchEvent();
extern void TextEntryEvent();
extern void TextEntryDraw();
extern int CreateTextLabel();
extern void PushButtonEvent();
extern void PushButtonDraw();
extern void UnhighlightPushButton();
extern int CreatePushButton();
extern void LabelDraw();
extern int CreateTextLabel();
extern Window CreateDialog();
extern void PopDownDialog();
extern void PopUpDialog();
extern void GetDialogData();
extern void SetDialogCallback();
extern void SetDialogCancelCallback();
extern void SetDialogData();
extern void SetDialogPrompt();
extern void QueryPointer();
extern int CreateTransientWindow();

#endif


text:
package toml

import (
	"encoding"
	"fmt"
	"io"
	"io/ioutil"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/naoina/toml/ast"
)

const (
	tableSeparator = '.'
)

var (
	escapeReplacer = strings.NewReplacer(
		"\b", "\\n",
		"\f", "\\f",
		"\n", "\\n",
		"\r", "\\r",
		"\t", "\\t",
	)
	underscoreReplacer = strings.NewReplacer(
		"_", "",
	)
)

var timeType = reflect.TypeOf(time.Time{})

// Unmarshal parses the TOML data and stores the result in the value pointed to by v.
//
// Unmarshal will mapped to v that according to following rules:
//
//	TOML strings to string
//	TOML integers to any int type
//	TOML floats to float32 or float64
//	TOML booleans to bool
//	TOML datetimes to time.Time
//	TOML arrays to any type of slice
//	TOML tables to struct or map
//	TOML array tables to slice of struct or map
func (cfg *Config) Unmarshal(data []byte, v interface{}) error {
	table, err := Parse(data)
	if err != nil {
		return err
	}
	if err := cfg.UnmarshalTable(table, v); err != nil {
		return err
	}
	return nil
}

// A Decoder reads and decodes TOML from an input stream.
type Decoder struct {
	r   io.Reader
	cfg *Config
}

// NewDecoder returns a new Decoder that reads from r.
// Note that it reads all from r before parsing it.
func (cfg *Config) NewDecoder(r io.Reader) *Decoder {
	return &Decoder{r, cfg}
}

// Decode parses the TOML data from its input and stores it in the value pointed to by v.
// See the documentation for Unmarshal for details about the conversion of TOML into a Go value.
func (d *Decoder) Decode(v interface{}) error {
	b, err := ioutil.ReadAll(d.r)
	if err != nil {
		return err
	}
	return d.cfg.Unmarshal(b, v)
}

// UnmarshalerRec may be implemented by types to customize their behavior when being
// unmarshaled from TOML. You can use it to implement custom validation or to set
// unexported fields.
//
// UnmarshalTOML receives a function that can be called to unmarshal the original TOML
// value into a field or variable. It is safe to call the function more than once if
// necessary.
type UnmarshalerRec interface {
	UnmarshalTOML(fn func(interface{}) error) error
}

// Unmarshaler can be used to capture and process raw TOML source of a table or value.
// UnmarshalTOML must copy the input if it wishes to retain it after returning.
//
// Note: this interface is retained for backwards compatibility. You probably want
// to implement encoding.TextUnmarshaler or UnmarshalerRec instead.
type Unmarshaler interface {
	UnmarshalTOML(input []byte) error
}

// UnmarshalTable applies the contents of an ast.Table to the value pointed at by v.
//
// UnmarshalTable will mapped to v that according to following rules:
//
//	TOML strings to string
//	TOML integers to any int type
//	TOML floats to float32 or float64
//	TOML booleans to bool
//	TOML datetimes to time.Time
//	TOML arrays to any type of slice
//	TOML tables to struct or map
//	TOML array tables to slice of struct or map
func (cfg *Config) UnmarshalTable(t *ast.Table, v interface{}) error {
	rv := reflect.ValueOf(v)
	toplevelMap := rv.Kind() == reflect.Map
	if (!toplevelMap && rv.Kind() != reflect.Ptr) || rv.IsNil() {
		return &invalidUnmarshalError{reflect.TypeOf(v)}
	}
	return unmarshalTable(cfg, rv, t, toplevelMap)
}

// used for UnmarshalerRec.
func unmarshalTableOrValue(cfg *Config, rv reflect.Value, av interface{}) error {
	if (rv.Kind() != reflect.Ptr && rv.Kind() != reflect.Map) || rv.IsNil() {
		return &invalidUnmarshalError{rv.Type()}
	}
	rv = indirect(rv)

	switch av.(type) {
	case *ast.KeyValue, *ast.Table, []*ast.Table:
		if err := unmarshalField(cfg, rv, av); err != nil {
			return lineError(fieldLineNumber(av), err)
		}
		return nil
	case ast.Value:
		return setValue(cfg, rv, av.(ast.Value))
	default:
		panic(fmt.Sprintf("BUG: unhandled AST node type %T", av))
	}
}

// unmarshalTable unmarshals the fields of a table into a struct or map.
//
// toplevelMap is true when rv is an (unadressable) map given to UnmarshalTable. In this
// (special) case, the map is used as-is instead of creating a new map.
func unmarshalTable(cfg *Config, rv reflect.Value, t *ast.Table, toplevelMap bool) error {
	rv = indirect(rv)
	if err, ok := setUnmarshaler(cfg, rv, t); ok {
		return lineError(t.Line, err)
	}
	switch {
	case rv.Kind() == reflect.Struct:
		fc := makeFieldCache(cfg, rv.Type())
		for key, fieldAst := range t.Fields {
			fv, fieldName, err := fc.findField(cfg, rv, key)
			if err != nil {
				return lineError(fieldLineNumber(fieldAst), err)
			}
			if fv.IsValid() {
				if err := unmarshalField(cfg, fv, fieldAst); err != nil {
					return lineErrorField(fieldLineNumber(fieldAst), rv.Type().String()+"."+fieldName, err)
				}
			}
		}
	case rv.Kind() == reflect.Map || isEface(rv):
		m := rv
		if !toplevelMap {
			if rv.Kind() == reflect.Interface {
				m = reflect.ValueOf(make(map[string]interface{}))
			} else {
				m = reflect.MakeMap(rv.Type())
			}
		}
		elemtyp := m.Type().Elem()
		for key, fieldAst := range t.Fields {
			kv, err := unmarshalMapKey(m.Type().Key(), key)
			if err != nil {
				return lineError(fieldLineNumber(fieldAst), err)
			}
			fv := reflect.New(elemtyp).Elem()
			if err := unmarshalField(cfg, fv, fieldAst); err != nil {
				return lineError(fieldLineNumber(fieldAst), err)
			}
			m.SetMapIndex(kv, fv)
		}
		if !toplevelMap {
			rv.Set(m)
		}
	default:
		return lineError(t.Line, &unmarshalTypeError{"table", "struct or map", rv.Type()})
	}
	return nil
}

func fieldLineNumber(fieldAst interface{}) int {
	switch av := fieldAst.(type) {
	case *ast.KeyValue:
		return av.Line
	case *ast.Table:
		return av.Line
	case []*ast.Table:
		return av[0].Line
	default:
		panic(fmt.Sprintf("BUG: unhandled node type %T", fieldAst))
	}
}

func unmarshalField(cfg *Config, rv reflect.Value, fieldAst interface{}) error {
	switch av := fieldAst.(type) {
	case *ast.KeyValue:
		return setValue(cfg, rv, av.Value)
	case *ast.Table:
		return unmarshalTable(cfg, rv, av, false)
	case []*ast.Table:
		rv = indirect(rv)
		if err, ok := setUnmarshaler(cfg, rv, fieldAst); ok {
			return err
		}
		var slice reflect.Value
		switch {
		case rv.Kind() == reflect.Slice:
			slice = reflect.MakeSlice(rv.Type(), len(av), len(av))
		case isEface(rv):
			slice = reflect.ValueOf(make([]interface{}, len(av)))
		default:
			return &unmarshalTypeError{"array table", "slice", rv.Type()}
		}
		for i, tbl := range av {
			vv := reflect.New(slice.Type().Elem()).Elem()
			if err := unmarshalTable(cfg, vv, tbl, false); err != nil {
				return err
			}
			slice.Index(i).Set(vv)
		}
		rv.Set(slice)
	default:
		panic(fmt.Sprintf("BUG: unhandled AST node type %T", av))
	}
	return nil
}

func unmarshalMapKey(typ reflect.Type, key string) (reflect.Value, error) {
	rv := reflect.New(typ).Elem()
	if u, ok := rv.Addr().Interface().(encoding.TextUnmarshaler); ok {
		return rv, u.UnmarshalText([]byte(key))
	}
	switch typ.Kind() {
	case reflect.String:
		rv.SetString(key)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i, err := strconv.ParseInt(key, 10, int(typ.Size()*8))
		if err != nil {
			return rv, convertNumError(typ.Kind(), err)
		}
		rv.SetInt(i)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		i, err := strconv.ParseUint(key, 10, int(typ.Size()*8))
		if err != nil {
			return rv, convertNumError(typ.Kind(), err)
		}
		rv.SetUint(i)
	default:
		return rv, fmt.Errorf("invalid map key type %s", typ)
	}
	return rv, nil
}

func setValue(cfg *Config, lhs reflect.Value, val ast.Value) error {
	lhs = indirect(lhs)
	if err, ok := setUnmarshaler(cfg, lhs, val); ok {
		return err
	}
	if err, ok := setTextUnmarshaler(lhs, val); ok {
		return err
	}
	switch v := val.(type) {
	case *ast.Integer:
		return setInt(lhs, v)
	case *ast.Float:
		return setFloat(lhs, v)
	case *ast.String:
		return setString(lhs, v)
	case *ast.Boolean:
		return setBoolean(lhs, v)
	case *ast.Datetime:
		return setDatetime(lhs, v)
	case *ast.Array:
		return setArray(cfg, lhs, v)
	default:
		panic(fmt.Sprintf("BUG: unhandled node type %T", v))
	}
}

func indirect(rv reflect.Value) reflect.Value {
	for rv.Kind() == reflect.Ptr {
		if rv.IsNil() {
			rv.Set(reflect.New(rv.Type().Elem()))
		}
		rv = rv.Elem()
	}
	return rv
}

func setUnmarshaler(cfg *Config, lhs reflect.Value, av interface{}) (error, bool) {
	if lhs.CanAddr() {
		if u, ok := lhs.Addr().Interface().(UnmarshalerRec); ok {
			err := u.UnmarshalTOML(func(v interface{}) error {
				return unmarshalTableOrValue(cfg, reflect.ValueOf(v), av)
			})
			return err, true
		}
		if u, ok := lhs.Addr().Interface().(Unmarshaler); ok {
			return u.UnmarshalTOML(unmarshalerSource(av)), true
		}
	}
	return nil, false
}

func unmarshalerSource(av interface{}) []byte {
	var source []byte
	switch av := av.(type) {
	case []*ast.Table:
		for i, tab := range av {
			source = append(source, tab.Source()...)
			if i != len(av)-1 {
				source = append(source, '\n')
			}
		}
	case ast.Value:
		source = []byte(av.Source())
	default:
		panic(fmt.Sprintf("BUG: unhandled node type %T", av))
	}
	return source
}

func setTextUnmarshaler(lhs reflect.Value, val ast.Value) (error, bool) {
	if !lhs.CanAddr() {
		return nil, false
	}
	u, ok := lhs.Addr().Interface().(encoding.TextUnmarshaler)
	if !ok || lhs.Type() == timeType {
		return nil, false
	}
	var data string
	switch val := val.(type) {
	case *ast.Array:
		return &unmarshalTypeError{"array", "", lhs.Type()}, true
	case *ast.String:
		data = val.Value
	default:
		data = val.Source()
	}
	return u.UnmarshalText([]byte(data)), true
}

func setInt(fv reflect.Value, v *ast.Integer) error {
	k := fv.Kind()
	switch {
	case k >= reflect.Int && k <= reflect.Int64:
		i, err := strconv.ParseInt(v.Value, 10, int(fv.Type().Size()*8))
		if err != nil {
			return convertNumError(fv.Kind(), err)
		}
		fv.SetInt(i)
	case k >= reflect.Uint && k <= reflect.Uintptr:
		i, err := strconv.ParseUint(v.Value, 10, int(fv.Type().Size()*8))
		if err != nil {
			return convertNumError(fv.Kind(), err)
		}
		fv.SetUint(i)
	case isEface(fv):
		i, err := strconv.ParseInt(v.Value, 10, 64)
		if err != nil {
			return convertNumError(reflect.Int64, err)
		}
		fv.Set(reflect.ValueOf(i))
	default:
		return &unmarshalTypeError{"integer", "", fv.Type()}
	}
	return nil
}

func setFloat(fv reflect.Value, v *ast.Float) error {
	f, err := v.Float()
	if err != nil {
		return err
	}
	switch {
	case fv.Kind() == reflect.Float32 || fv.Kind() == reflect.Float64:
		if fv.OverflowFloat(f) {
			return &overflowError{fv.Kind(), v.Value}
		}
		fv.SetFloat(f)
	case isEface(fv):
		fv.Set(reflect.ValueOf(f))
	default:
		return &unmarshalTypeError{"float", "", fv.Type()}
	}
	return nil
}

func setString(fv reflect.Value, v *ast.String) error {
	switch {
	case fv.Kind() == reflect.String:
		fv.SetString(v.Value)
	case isEface(fv):
		fv.Set(reflect.ValueOf(v.Value))
	default:
		return &unmarshalTypeError{"string", "", fv.Type()}
	}
	return nil
}

func setBoolean(fv reflect.Value, v *ast.Boolean) error {
	b, _ := v.Boolean()
	switch {
	case fv.Kind() == reflect.Bool:
		fv.SetBool(b)
	case isEface(fv):
		fv.Set(reflect.ValueOf(b))
	default:
		return &unmarshalTypeError{"boolean", "", fv.Type()}
	}
	return nil
}

func setDatetime(rv reflect.Value, v *ast.Datetime) error {
	t, err := v.Time()
	if err != nil {
		return err
	}
	if !timeType.AssignableTo(rv.Type()) {
		return &unmarshalTypeError{"datetime", "", rv.Type()}
	}
	rv.Set(reflect.ValueOf(t))
	return nil
}

func setArray(cfg *Config, rv reflect.Value, v *ast.Array) error {
	var slicetyp reflect.Type
	switch {
	case rv.Kind() == reflect.Slice:
		slicetyp = rv.Type()
	case isEface(rv):
		slicetyp = reflect.SliceOf(rv.Type())
	default:
		return &unmarshalTypeError{"array", "slice", rv.Type()}
	}

	if len(v.Value) == 0 {
		// Ensure defined slices are always set to a non-nil value.
		rv.Set(reflect.MakeSlice(slicetyp, 0, 0))
		return nil
	}

	tomltyp := reflect.TypeOf(v.Value[0])
	slice := reflect.MakeSlice(slicetyp, len(v.Value), len(v.Value))
	typ := slicetyp.Elem()
	for i, vv := range v.Value {
		if i > 0 && tomltyp != reflect.TypeOf(vv) {
			return errArrayMultiType
		}
		tmp := reflect.New(typ).Elem()
		if err := setValue(cfg, tmp, vv); err != nil {
			return err
		}
		slice.Index(i).Set(tmp)
	}
	rv.Set(slice)
	return nil
}

func isEface(rv reflect.Value) bool {
	return rv.Kind() == reflect.Interface && rv.Type().NumMethod() == 0
}


text:
<?php

namespace SerendipityHQ\Bundle\StripeBundle\Event;

/**
 * Dispatched when a ping.* event has been received by the webhook endpoint.
 *
 * @author Adamo Crespi <hello@aerendir.me>
 */
class StripeWebhookPingEventEvent extends AbstractStripeWebhookEventEvent
{
    /**
     * May be sent by Stripe at any time to see if a provided webhook URL is working.
     *
     * @var string
     *
     * @see https://stripe.com/docs/api#event_types-ping
     */
    const PING = 'stripe.webhook.ping';
}


text:
package cz.auderis.tools.resource;

import cz.auderis.tools.config.ConfigurationData;
import cz.auderis.tools.config.StandardJavaTranslator;

import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * {@code ExtResourceBundle}
 *
 * @author Boleslav Bobcik <bbobcik@gmail.com>
 * @version 1.0
 */
public class ExtResourceBundle extends ResourceBundle implements ResourceAccessor {

	public ExtResourceBundle(ResourceBundle decoratedBundle) {
		super();
		if (null == decoratedBundle) {
			throw new NullPointerException();
		}
		setParent(decoratedBundle);
	}

	@Override
	public Enumeration<String> getKeys() {
		// This class is only a decorator, no extra keys are provided
		return parent.getKeys();
	}

	@Override
	protected Object handleGetObject(String key) {
		// Delegate all object retrievals to parent bundle
		return null;
	}

	@Override
	public Locale getLocale() {
		return parent.getLocale();
	}

	@Override
	public Object getRawObject(String key) {
		if (!containsKey(key)) {
			return null;
		}
		return getObject(key);
	}

	public String getString(String key, String defaultString) {
		if (!containsKey(key)) {
			return defaultString;
		}
		return getString(key);
	}

	public int getInt(String key, int defaultValue) {
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (object instanceof Integer) {
				return (Integer) object;
			} else if (object instanceof String) {
				try {
					return Integer.parseInt((String) object);
				} catch (NumberFormatException e) {
					// exception ignored
				}
			}
		}
		return defaultValue;
	}

	public long getLong(String key, long defaultValue) {
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (object instanceof Long) {
				return (Long) object;
			} else if (object instanceof String) {
				try {
					return Long.parseLong((String) object);
				} catch (NumberFormatException e) {
					// exception ignored
				}
			}
		}
		return defaultValue;
	}

	public boolean getBoolean(String key, boolean defaultValue) {
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (object instanceof Boolean) {
				return (Boolean) object;
			} else if (object instanceof String) {
				return Boolean.parseBoolean((String) object);
			}
		}
		return defaultValue;
	}

	public <T extends Enum<T>> T getEnum(String key, Class<T> enumClass, T defaultValue) {
		if ((null == key) || (null == enumClass)) {
			throw new NullPointerException();
		} else if (!enumClass.isEnum()) {
			throw new IllegalArgumentException("class is not an enum");
		}
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (enumClass.isAssignableFrom(object.getClass())) {
				return enumClass.cast(object);
			} else if (object instanceof String) {
				final String enumName = (String) object;
				final T[] items = enumClass.getEnumConstants();
				for (T item : items) {
					if (item.name().equals(enumName)) {
						return item;
					}
				}
			}
		}
		return defaultValue;
	}

	public BigInteger getBigInteger(String key, BigInteger defaultValue) {
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (object instanceof BigInteger) {
				return (BigInteger) object;
			} else if (object instanceof Long) {
				return BigInteger.valueOf((Long) object);
			} else if (object instanceof Integer) {
				return BigInteger.valueOf((long) (Integer) object);
			} else if (object instanceof String) {
				try {
					return new BigInteger((String) object);
				} catch (NumberFormatException e) {
					// Exception ignored
				}
			}
		}
		return defaultValue;
	}

	public BigDecimal getBigDecimal(String key, BigDecimal defaultValue) {
		if (containsKey(key)) {
			final Object object = getObject(key);
			if (object instanceof BigDecimal) {
				return (BigDecimal) object;
			} else if (object instanceof Long) {
				return BigDecimal.valueOf((Long) object);
			} else if (object instanceof Integer) {
				return BigDecimal.valueOf((long) (Integer) object);
			} else if (object instanceof String) {
				try {
					return new BigDecimal((String) object);
				} catch (NumberFormatException e) {
					// Exception ignored
				}
			}
		}
		return defaultValue;
	}

	public <T> T getObject(String key, Class<T> targetClass, T defaultValue) {
		if ((null == key) || (null == targetClass)) {
			throw new NullPointerException();
		}
		if (containsKey(key)) {
			final Object object = getObject(key);
			final Class<?> objectClass = object.getClass();
			if (targetClass.isAssignableFrom(objectClass)) {
				return targetClass.cast(object);
			}
			// Try to use an appropriate constructor
			try {
				final Constructor<T> constructor = targetClass.getConstructor(objectClass);
				final T result = constructor.newInstance(object);
				return result;
			} catch (Exception e) {
				// Exceptions ignored
			}
			final Class<?> altObjectClass = StandardJavaTranslator.instance().switchPrimitiveAndBoxedType(objectClass);
			if (null != altObjectClass) {
				try {
					final Constructor<T> constructor = targetClass.getConstructor(altObjectClass);
					final T result = constructor.newInstance(object);
					return result;
				} catch (Exception e) {
					// Exceptions ignored
				}
			}
		}
		return defaultValue;
	}

	@Override
	public <T> T getObjectWithTextDefault(String key, Class<T> targetClass, String defaultTextValue) {
		if ((null == key) || (null == targetClass)) {
			throw new NullPointerException();
		}
		if (containsKey(key)) {
			final Object object = getObject(key);
			final Class<?> objectClass = object.getClass();
			if (targetClass.isAssignableFrom(objectClass)) {
				return targetClass.cast(object);
			}
			// Try to use an appropriate constructor
			try {
				final Constructor<T> constructor = targetClass.getConstructor(objectClass);
				final T result = constructor.newInstance(object);
				return result;
			} catch (Exception e) {
				// Exceptions ignored
			}
		}
		if ((null == defaultTextValue) || defaultTextValue.isEmpty()) {
			return null;
		}
		try {
			final Constructor<T> constructor = targetClass.getConstructor(String.class);
			final T defaultResult = constructor.newInstance(defaultTextValue);
			return defaultResult;
		} catch (Exception e) {
			final String msg = String.format("Resource (class %s) cannot be constructed from default text value %s: %s",
					targetClass.getName(), defaultTextValue, e.getMessage());
			throw new IllegalArgumentException(msg, e);
		}
	}

	public <T> T getConfigurationObject(Class<T> configObjectClass, ClassLoader clsLoader) {
		final T result = ConfigurationData.createConfigurationObject(this, configObjectClass, clsLoader);
		return result;
	}

	public <T> T getConfigurationObject(Class<T> configObjectClass) {
		final T result = ConfigurationData.createConfigurationObject(this, configObjectClass);
		return result;
	}

}


text:
package cz.nalezen.diffator.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import cz.nalezen.diffator.Content;

/**
 * Data for HashImpl.
 * @author Jaroslav Kubos
 *
 */
public class ContentsComparatorHashImplContext implements ContentsComparatorContext {

	ArrayList<LinkedHashMap<Integer, Integer>> buffer;

	@Override
	public void initialize(Content a, Content b) {
		buffer = new ArrayList<>(a.length());

		//define all rows
		for (int i=0;i<a.length()+1;++i) {
			buffer.add(new LinkedHashMap<Integer, Integer>());
		}

		//build matrix
		calculateSubstringsLength(a, b);
	}

	public ArrayList<LinkedHashMap<Integer, Integer>> getBuffer() {
		return buffer;
	}

	/**
	 * http://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Strings/Longest_common_substring&stable=1
	 * only non-zero values stored
	 */
	private void calculateSubstringsLength(Content a, Content b) {
		for (int i=1;i<=a.length();i++) {
		    for (int j=1;j<=b.length();j++) {
		        if (a.getItem(i-1).equals(b.getItem(j-1))) {

		        	LinkedHashMap<Integer, Integer> row = buffer.get(i);

		            if (i==1 || j==1) {
		            	row.put(j, 1);
		            }
		            else {
		            	LinkedHashMap<Integer, Integer> rowBef = buffer.get(i-1);

		            	Integer v = rowBef.get(j-1);

		            	if (v==null) {
		            		v = 0;
		            	}

		            	row.put(j, v+1);
		            }
		        }
		    }
		}
	}

}


text:
<!DOCTYPE html>

    <title>Three.js - postprocessing - 3DLUT w/loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

Adobe LUT to PNG converter

Drag and drop a LUT file here

size:<input id="size" type="number" value="8" min="2" max="64"/>

<button type="button">Save...</button>

<canvas id="c"></canvas>


text:
if(!dojo._hasResource["dojox.analytics._base"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.analytics._base"] = true;
dojo.provide("dojox.analytics._base");

dojox.analytics = function(){
	// summary: TODOC
	//		where we store data until we're ready to send it off.
	//
	//the data queue;
	this._data = [];

	//id of messages for this session/page
	this._id = 1;

	//some default values
	this.sendInterval = dojo.config["sendInterval"] || 5000;
	this.inTransitRetry = dojo.config["inTransitRetry"] || 200;
	this.dataUrl = dojo.config["analyticsUrl"] || dojo.moduleUrl("dojox.analytics.logger", "dojoxAnalytics.php");
	this.sendMethod = dojo.config["sendMethod"] || "xhrPost";
	this.maxRequestSize = dojo.isIE ? 2000 : dojo.config["maxRequestSize"] || 4000;

	//while we can go ahead and being logging as soon as this constructor is completed
	//we're not going to schedule pushing data to the server until after the page
	//has completed loading
	dojo.addOnLoad(this, "schedulePusher");
	dojo.addOnUnload(this, "pushData", true);
};

dojo.extend(dojox.analytics, {
	schedulePusher: function(/* Int */interval){
		// summary: Schedule the data pushing routines to happen in interval ms
		setTimeout(dojo.hitch(this, "checkData"), interval || this.sendInterval);
	},

	addData: function(dataType, data){
		// summary:
		//	add data to the queue. Will be pusshed to the server on the next
		//	data push

		if(arguments.length > 2){
			// FIXME: var c = dojo._toArray(arguments) ?
			var c = [];
			for(var i = 1; i < arguments.length; i++){
				c.push(arguments[i]);
			}
			data = c;
		}

		this._data.push({ plugin: dataType, data: data });
	},

	checkData: function(){
		// summary: TODOC?
		if(this._inTransit){
			this.schedulePusher(this.inTransitRetry);
			return;
		}

		if(this.pushData()){ return; }
		this.schedulePusher();
	},

	pushData: function(){
		// summary:
		//	pushes data to the server if any exists.  If a push is done, return
		//	the deferred after hooking up completion callbacks.  If there is no data
		//	to be pushed, return false;
		if(this._data.length){
			//clear the queue
			this._inTransit = this._data;
			this._data = [];
			var def;
			switch(this.sendMethod){
				case "script":
					def = dojo.io.script.get({
						url: this.getQueryPacket(),
						preventCache: 1,
						callbackParamName: "callback"
					});
					break;
				case "xhrPost":
				default:
					def = dojo.xhrPost({
						url:this.dataUrl,
						content:{
							id: this._id++,
							data: dojo.toJson(this._inTransit)
						}
					});
					break;
			}
			def.addCallback(this, "onPushComplete");
			return def;
		}
		return false;
	},

	getQueryPacket: function(){
		// summary: TODOC
		while(true){
			var content = {
				id: this._id++,
				data: dojo.toJson(this._inTransit)
			};

			//FIXME would like a much better way to get the query down to lenght
			var query = this.dataUrl + '?' + dojo.objectToQuery(content);
			if(query.length > this.maxRequestSize){
				this._data.unshift(this._inTransit.pop());
				this._split = 1;
			}else{
				return query;
			}
		}
	},

	onPushComplete: function(results){
		// summary:
		//	If our data push was successfully, remove the _inTransit data and schedule the next
		//	parser run.
		if(this._inTransit){
			delete this._inTransit;
		}

		if(this._data.length > 0){
			this.schedulePusher(this.inTransitRetry);
		}else{
			this.schedulePusher();
		}
	}
});

//create the analytics  singleton
dojox.analytics = new dojox.analytics();

}


text:
<configuration>

  <conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel"/>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home}/logs/application.log</file>
    <encoder>
      <pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
    </encoder>
  </appender>

  <logger name="play" level="INFO"/>
  <logger name="application" level="INFO"/>

  <root level="ERROR">
    <appender-ref ref="STDOUT"/>
    <appender-ref ref="FILE"/>
  </root>

  <logger name="Global" level="DEBUG"/>

</configuration>


text:
package com.chargebee.models.enums;

public enum EcheckType {
    WEB,
    PPD,
    CCD,
    _UNKNOWN; /*Indicates unexpected value for this enum. You can get this when there is a
    java-client version incompatibility. We suggest you to upgrade to the latest version */
}


text:
int main(int argc, char** argv) {
  base::CommandLine::Init(argc, argv);
  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();

  base::AtExitManager at_exit;
  mojo::runner::InitializeLogging();
  mojo::runner::WaitForDebuggerIfNecessary();

  if (command_line.HasSwitch(switches::kChildProcess))
    return mojo::runner::ChildProcessMain();

  return mandoline::LauncherProcessMain(argc, argv);
}


text:
const { expect } = require('chai')
const { getScope, mockApi } = require('../util')

const noticePayload = {
  asnId: '2343689643',
  version: '1',
  issueDate: '2019-06-19T16:39:57-08:00',
  transportation: 'Expedited Freight',
  parties: [
    {
      id: 'gs1:414:01251',
      type: 'ship-from'
    },
    {
      name: 'The Landmark, Shop No. G14',
      type: 'ship-to',
      address: {
        street: '113-114, Central',
        city: 'Hong Kong'
      }
    }
  ],
  tags: ['ongoing']
}

module.exports = (scopeType, url) => {
  describe('Shipment Notices', () => {
    let scope, api

    before(() => {
      scope = getScope(scopeType)
      api = mockApi(url)
    })

    it('should create a shipment notice', async () => {
      api.post('/shipmentNotices', noticePayload).reply(201, noticePayload)

      const res = await scope.shipmentNotice().create(noticePayload)

      expect(res).to.be.an('object')
      expect(res.asnId).to.equal(noticePayload.asnId)
    })

    it('should read a shipment notice', async () => {
      api.get('/shipmentNotices/shipmentNoticeId').reply(200, noticePayload)

      const res = await scope.shipmentNotice('shipmentNoticeId').read()

      expect(res).to.be.an('object')
      expect(res.asnId).to.equal(noticePayload.asnId)
    })

    it('should update a shipment notice', async () => {
      api.put('/shipmentNotices/shipmentNoticeId').reply(200, noticePayload)

      const res = await scope.shipmentNotice('shipmentNoticeId').update(noticePayload)

      expect(res).to.be.an('object')
      expect(res.tags).to.deep.equal(noticePayload.tags)
    })

    it('should delete a shipment notice', async () => {
      api.delete('/shipmentNotices/shipmentNoticeId').reply(204)

      const res = await scope.shipmentNotice('shipmentNoticeId').delete()

      expect(res).to.not.exist
    })
  })
}


text:
> This function is still unstable and in the developmental stage. It takes about `computation time for sin + computation time for cos` milliseconds to compute tan θ° (which is about  for tan 90°).

`tan()` returns the tangent of an angle (given in degrees). This has only a static method function.

#### Syntax
##### method function
```javascript
BigArith.tan(n);
```

### Parameters
#### static method function
##### n - Required - {string|number|BigArith}
The angle (given in degrees). This could be a string of digits, a number, or a BigArith object.

### Return value
#### static method function - {BigArith}
A BigArith object with its value equals to the tangent of the given angle.

### Description
There is no method function for `tan()` so it should ALWAYS be used as a static member function `BigArith.tan()`.

The returned result is the tangent of the angle (given in degrees) to 200 decimal places.

### Examples
> In the server-side, always remember to add the line `var BigArith = require('bigarith.js');` however every other thing remains the same in both server-side and client-side code.

#### Using static method function
```javascript
var ba = BigArith.tan("90"); //throws RangeError division by zero
ba = BigArith.tan("45"); //BigArith object with value "1"
ba = BigArith.tan("75.786"); //BigArith object with value "3.94790489515350670109117542623163534465501513035850512311134005400587295700520957954415702735900414306649942878453329557667461916716391291200669582397421401273759999395237647345675059387564486523393406"
ba = BigArith.tan("0"); //BigArith object with value "0"
```

#### Method chaining
Since the method returns a BigArith object, [method chaining](method_chaining.html) is possible.
```javascript
var ba = new BigArith("-17031986");
ba = ba.divide("+17031986").add("24011985").multiply("456785564").subtract("2"); //BigArith object with value "10968327654198974"
```

More examples [here](https://github.com/osofem/bigarith.js/tree/master/examples/). Full documentation [here](https://github.com/osofem/bigarith.js/tree/master/documentation)

### See also
* [sin()](https://osofem.github.io/bigarith.js/documentation/sin.html)
* [cos()](https://osofem.github.io/bigarith.js/documentation/cos.html)


text:
.class public Lcom/xiaomi/account/openauth/AuthorizeApi;
.super Ljava/lang/Object;

# static fields
.field private static final a:Ljava/lang/String; = "UTF-8"

.field private static b:Ljava/lang/String;

.field private static c:Ljava/lang/String;

.field private static d:Ljava/lang/String;

.field private static e:Ljava/lang/String;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    const-string v0, "GET"

    sput-object v0, Lcom/xiaomi/account/openauth/AuthorizeApi;->b:Ljava/lang/String;

    const-string v0, "POST"

    sput-object v0, Lcom/xiaomi/account/openauth/AuthorizeApi;->c:Ljava/lang/String;

    const-string v0, "open.account.xiaomi.com"

    sput-object v0, Lcom/xiaomi/account/openauth/AuthorizeApi;->d:Ljava/lang/String;

    const-string v0, "https://"

    sput-object v0, Lcom/xiaomi/account/openauth/AuthorizeApi;->e:Ljava/lang/String;

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static doHttpGet(Landroid/content/Context;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
    .locals 8

    new-instance v7, Ljava/util/ArrayList;

    invoke-direct {v7}, Ljava/util/ArrayList;-><init>()V

    new-instance v0, Lorg/apache/http/message/BasicNameValuePair;

    const-string v1, "clientId"

    invoke-static {p2, p3}, Ljava/lang/String;->valueOf(J)Ljava/lang/String;

    move-result-object v2

    invoke-direct {v0, v1, v2}, Lorg/apache/http/message/BasicNameValuePair;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    invoke-interface {v7, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    new-instance v0, Lorg/apache/http/message/BasicNameValuePair;

    const-string v1, "token"

    invoke-direct {v0, v1, p4}, Lorg/apache/http/message/BasicNameValuePair;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    invoke-interface {v7, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    invoke-static {}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->generateNonce()Ljava/lang/String;

    move-result-object v0

    :try_start_0
    sget-object v1, Lcom/xiaomi/account/openauth/AuthorizeApi;->b:Ljava/lang/String;

    sget-object v2, Lcom/xiaomi/account/openauth/AuthorizeApi;->d:Ljava/lang/String;

    const-string v3, "UTF-8"

    invoke-static {v7, v3}, Lorg/apache/http/client/utils/URLEncodedUtils;->format(Ljava/util/List;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v4

    move-object v3, p1

    move-object v5, p5

    move-object v6, p6

    invoke-static/range {v0 .. v6}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->getMacAccessTokenSignatureString(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v4

    new-instance v1, Ljava/net/URL;

    new-instance v2, Ljava/lang/StringBuilder;

    sget-object v3, Lcom/xiaomi/account/openauth/AuthorizeApi;->e:Ljava/lang/String;

    invoke-static {v3}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v3

    invoke-direct {v2, v3}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    sget-object v3, Lcom/xiaomi/account/openauth/AuthorizeApi;->d:Ljava/lang/String;

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v2, v7}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->generateUrl(Ljava/lang/String;Ljava/util/List;)Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/net/URL;-><init>(Ljava/lang/String;)V

    const/4 v2, 0x0

    const/4 v3, 0x0

    invoke-static {p4, v0, v4}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->buildMacRequestHead(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/HashMap;

    move-result-object v4

    const/4 v5, 0x0

    move-object v0, p0

    invoke-static/range {v0 .. v5}, Lcom/xiaomi/account/openauth/utils/Network;->downloadXml(Landroid/content/Context;Ljava/net/URL;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Lcom/xiaomi/account/openauth/utils/Network$HttpHeaderInfo;)Ljava/lang/String;
    :try_end_0
    .catch Ljava/security/InvalidKeyException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/security/NoSuchAlgorithmException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/io/UnsupportedEncodingException; {:try_start_0 .. :try_end_0} :catch_2
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_3

    move-result-object v0

    return-object v0

    :catch_0
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_1
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_2
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_3
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1
.end method

.method public static doHttpPost(Landroid/content/Context;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
    .locals 8

    new-instance v7, Ljava/util/ArrayList;

    invoke-direct {v7}, Ljava/util/ArrayList;-><init>()V

    new-instance v0, Lorg/apache/http/message/BasicNameValuePair;

    const-string v1, "clientId"

    invoke-static {p2, p3}, Ljava/lang/String;->valueOf(J)Ljava/lang/String;

    move-result-object v2

    invoke-direct {v0, v1, v2}, Lorg/apache/http/message/BasicNameValuePair;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    invoke-interface {v7, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    new-instance v0, Lorg/apache/http/message/BasicNameValuePair;

    const-string v1, "token"

    invoke-direct {v0, v1, p4}, Lorg/apache/http/message/BasicNameValuePair;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    invoke-interface {v7, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    invoke-static {}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->generateNonce()Ljava/lang/String;

    move-result-object v0

    :try_start_0
    sget-object v1, Lcom/xiaomi/account/openauth/AuthorizeApi;->c:Ljava/lang/String;

    sget-object v2, Lcom/xiaomi/account/openauth/AuthorizeApi;->d:Ljava/lang/String;

    const-string v3, "UTF-8"

    invoke-static {v7, v3}, Lorg/apache/http/client/utils/URLEncodedUtils;->format(Ljava/util/List;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v4

    move-object v3, p1

    move-object v5, p5

    move-object v6, p6

    invoke-static/range {v0 .. v6}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->getMacAccessTokenSignatureString(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    new-instance v1, Ljava/lang/StringBuilder;

    sget-object v3, Lcom/xiaomi/account/openauth/AuthorizeApi;->e:Ljava/lang/String;

    invoke-static {v3}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v3

    invoke-direct {v1, v3}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    sget-object v3, Lcom/xiaomi/account/openauth/AuthorizeApi;->d:Ljava/lang/String;

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {p4, v0, v2}, Lcom/xiaomi/account/openauth/AuthorizeHelper;->buildMacRequestHead(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/HashMap;

    move-result-object v3

    const/4 v4, 0x0

    const/4 v5, 0x0

    const/4 v6, 0x0

    move-object v0, p0

    move-object v2, v7

    invoke-static/range {v0 .. v6}, Lcom/xiaomi/account/openauth/utils/Network;->doHttpPost(Landroid/content/Context;Ljava/lang/String;Ljava/util/List;Ljava/util/Map;Lcom/xiaomi/account/openauth/utils/Network$HttpHeaderInfo;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
    :try_end_0
    .catch Ljava/security/InvalidKeyException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/security/NoSuchAlgorithmException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/io/UnsupportedEncodingException; {:try_start_0 .. :try_end_0} :catch_2
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_3

    move-result-object v0

    return-object v0

    :catch_0
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_1
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_2
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1

    :catch_3
    move-exception v0

    new-instance v1, Lcom/xiaomi/account/openauth/XMAuthericationException;

    invoke-direct {v1, v0}, Lcom/xiaomi/account/openauth/XMAuthericationException;-><init>(Ljava/lang/Throwable;)V

    throw v1
.end method


text:
import Prism from 'prismjs';

export default function () {
	return text => {
		if (text) {
			return Prism.highlight(text, Prism.languages.html);
		}
		return text;
	};
}


text: ead remainder of "Scheduling"; read remainder of proc.c and sys_wait, sys_exit, sys_kill


text:
                        <fieldset>

                                <button class="btn btn-small active" data-field="showBusinessLogButton"></button>
                                <button class="btn btn-small" data-field="showTechnicalLogButton"></button>

                                <button class="btn btn-small active" data-field="showAscLogButton"></button>
                                <button class="btn btn-small" data-field="showDescLogButton"></button>

                        </fieldset>


text:
require 'net/http/persistent'

module Selenium
  module WebDriver
    module Remote
      module Http
        # @api private
        class Persistent < Default
          def close
            @http&.shutdown
          end

          private

          def start(*)
            # no need to explicitly start connection
          end

          def new_http_client
            proxy = nil

            if @proxy
              unless @proxy.respond_to?(:http)
                url = @proxy.http
                raise Error::WebDriverError, "expected HTTP proxy, got #{@proxy.inspect}" unless url
              end
              proxy = URI.parse(url)
            end

            Net::HTTP::Persistent.new name: 'webdriver', proxy: proxy
          end

          def response_for(request)
            http.request server_url, request
          end
        end # Persistent
      end # Http
    end # Remote
  end # WebDriver
end # Selenium


text:
'use strict';

/**
 * hobbs
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

const assert = require('assert');
const knex = require('knex');
const SuperCache = require('super-cache');
const coroutine = require('lei-coroutine');

module.exports = function initMySQL() {

  $.mysql = knex({
    client: 'mysql',
    connection: $.config.get('mysql.connection'),
    pool: $.config.get('mysql.pool'),
  });

  $.cache = new SuperCache({
    store: $.config.get('mysql.cache.store'),
    storeConfig: $.config.get('mysql.cache.connection'),
    ttl: $.config.get('mysql.cache.ttl'),
  });

  $.cache.define(/^db_item ([a-zA-Z0-9_]+) (.+)$/, (name, callback) => {
    const s = name.match(/^db_item ([a-zA-Z0-9_]+) (.+)$/);
    if (!s) return callback(new Error(`cannot get cache ${ name }`));
    const modelName = s[1];
    const query = JSON.parse(s[2]);
    const model = $.modelTables[modelName];
    if (!model) return callback(new Error(`invalid model ${ modelName } in cache key ${ name }`));
    model.table().first('*').where(query)
      .then(ret => callback(null, ret))
      .catch(err => callback(err));
  });

  function getDataItemCacheKey(model, query) {
    const newQuery = {};
    const keys = Object.keys(query).sort().forEach(k => {
      newQuery[k] = query[k];
    });
    return `db_item ${ model } ${ JSON.stringify(newQuery) }`;
  }

  function getCache(key) {
    return new Promise((resolve, reject) => {
      $.cache.get(key, (err, ret) => {
        if (err) {
          reject(err);
        } else {
          resolve(ret);
        }
      });
    });
  }

  function deleteCache(key) {
    return new Promise((resolve, reject) => {
      $.cache.delete(key, (err, ret) => {
        if (err) {
          reject(err);
        } else {
          resolve(ret);
        }
      });
    });
  }

  $.model = {};
  $.modelTables = {};

  $.model.create = function (tableName) {
    assert(tableName && typeof tableName === 'string', 'tableName must be string');

    const superModel = {
      tableName,
    };
    const model = {
      super: superModel,
    };

    process.nextTick(() => {
      for (const name in $.model) {
        if ($.model[name].tableName === tableName) {
          $.model[name].name = superModel.name = name;
          $.modelTables[tableName] = $.model[name];
        }
      }
    });

    superModel.table = function () {
      return $.mysql.table(superModel.tableName);
    };

    superModel.merge = function (...args) {
      return Object.assign({}, ...args);
    };

    superModel.get = function (query, disableCache = false) {
      $.utils.checkNotEmpty(query, 'query');
      $.utils.checkNotEmpty(Object.keys(query), 'query');
      if (disableCache) {
        return model.table().first('*').where(query);
      }
      return getCache(getDataItemCacheKey(superModel.tableName, query));
    };

    superModel.getById = function (id) {
      $.utils.checkNotEmpty(id, 'id');
      return superModel.get({ id });
    };

    superModel.add = coroutine.wrap(function* modelAdd(data) {
      $.utils.checkNotEmpty(data, 'data');
      const newData = superModel.merge(data);
      newData.created_at = new Date();
      newData.updated_at = new Date();
      if (data.created_at === false) delete newData.created_at;
      if (data.updated_at === false) delete newData.updated_at;
      const [ id ] = yield model.table().insert(newData, 'id');
      return id;
    });

    superModel.update = coroutine.wrap(function* modelUpdate(query, data) {
      $.utils.checkNotEmpty(query, 'query');
      $.utils.checkNotEmpty(Object.keys(query), 'query');
      $.utils.checkNotEmpty(data, 'data');
      $.utils.checkNotEmpty(Object.keys(data), 'data');
      const newData = superModel.merge(data);
      newData.updated_at = new Date();
      if (data.created_at === false) delete newData.created_at;
      if (data.updated_at === false) delete newData.updated_at;
      yield deleteCache(getDataItemCacheKey(superModel.tableName, query));
      return model.table().update(newData).where(query);
    });

    superModel.updateById = function (id, data) {
      $.utils.checkNotEmpty(id, 'id');
      return superModel.update({ id }, data);
    };

    superModel.addOrUpdate = coroutine.wrap(function* modelAddOrUpdate(query, data) {
      const ret = yield superModel.get(query, true);
      if (ret) return superModel.update(query, data);
      return superModel.add(superModel.merge(query, data));
    });

    superModel.addOrUpdateById = function (id, data) {
      $.utils.checkNotEmpty(id, 'id');
      return superModel.addOrUpdate({ id }, data);
    };

    superModel.remove = coroutine.wrap(function* modelRemove(query, all = false) {
      $.utils.checkNotEmpty(query, 'query');
      $.utils.checkNotEmpty(Object.keys(query), 'query');
      const data = {
        is_removed: 1,
        removed_at: new Date(),
      };
      yield deleteCache(getDataItemCacheKey(superModel.tableName, query));
      const p = model.table().update(data).where(query);
      if (!all) p.limit(1);
      return p;
    });

    superModel.removeAll = function (query) {
      return superModel.remove(query, true);
    };

    superModel.removeById = function (id) {
      $.utils.checkNotEmpty(id, 'id');
      return superModel.remove({ id });
    };

    superModel.delete = coroutine.wrap(function* modelDelete(query, all = false) {
      $.utils.checkNotEmpty(query, 'query');
      $.utils.checkNotEmpty(Object.keys(query), 'query');
      yield deleteCache(getDataItemCacheKey(superModel.tableName, query));
      const p = model.table().delete().where(query);
      if (!all) p.limit(1);
      return p;
    });

    superModel.deleteAll = function (query) {
      return superModel.delete(query, true);
    };

    superModel.deleteById = function (id) {
      $.utils.checkNotEmpty(id, 'id');
      return superModel.delete({ id });
    };

    superModel.count = function (query) {
      $.utils.checkNotEmpty(query, 'query');
      return superModel.countAdv(model.table().where(query));
    };

    superModel.countAdv = coroutine.wrap(function* modelCountAdv(table) {
      const ret = yield table.count('*');
      return ret && ret[0] && ret[0]['count(*)'] || 0;
    });

    superModel.list = function (query, options) {
      $.utils.checkNotEmpty(query, 'query');
      return superModel.listAdv(model.table().where(query), options);
    };

    superModel.listAdv = function (table, {
      columns = '*',
      skip = 0,
      limit = 0,
      order_by = [],
    } = {}) {
      for (const item of order_by) {
        table.orderBy(item.column, item.direction);
      }
      return table.select(columns).offset(skip).limit(limit);
    };

    Object.assign(model, superModel);

    return model;
  };

};


text:
class AddBirthplaceToUsers < ActiveRecord::Migration
  def change

  	change_table :users do |t|
    	t.string :birthplace
    end
  end
end


text:
package org.apache.spark.streaming.kafka

import com.stratio.crossdata.streaming.kafka.KafkaInput
import com.stratio.crossdata.streaming.test.{BaseSparkStreamingXDTest, CommonValues}
import org.apache.spark.sql.crossdata.models.ConnectionModel
import org.apache.spark.streaming.{Milliseconds, StreamingContext}
import org.apache.spark.{SparkContext, SparkConf}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import scala.collection.mutable
import scala.concurrent.duration._
import scala.language.postfixOps

@RunWith(classOf[JUnitRunner])
class KafkaStreamIT extends BaseSparkStreamingXDTest with CommonValues {

  val sparkConf = new SparkConf().setMaster("local[2]").setAppName(this.getClass.getSimpleName)
  val sc = SparkContext.getOrCreate(sparkConf)
  var ssc: StreamingContext = _
  val kafkaTestUtils: KafkaTestUtils =  new KafkaTestUtils
  kafkaTestUtils.setup()

  after {
    if (ssc != null) {
      ssc.stop(stopSparkContext = false, stopGracefully = false)
      ssc.awaitTerminationOrTimeout(3000)
      ssc = null
    }
  }

  override def afterAll : Unit = {
    kafkaTestUtils.teardown()
  }

  test("Kafka input stream with kafkaOptionsModel from Map of values") {
    ssc = new StreamingContext(sc, Milliseconds(1000))
    val valuesToSent = Map("a" -> 5, "b" -> 3, "c" -> 10)
    kafkaTestUtils.createTopic(TopicTest)
    kafkaTestUtils.sendMessages(TopicTest, valuesToSent)

    val consumerHostZK = connectionHostModel.zkConnection.head.host
    val consumerPortZK = kafkaTestUtils.zkAddress.split(":").last.toInt

    val producerHostKafka = connectionHostModel.kafkaConnection.head.host
    val producerPortKafka = kafkaTestUtils.brokerAddress.split(":").last

    val kafkaStreamModelZk = kafkaStreamModel.copy(
      connection = connectionHostModel.copy(
        zkConnection = Seq(ConnectionModel(consumerHostZK, consumerPortZK)),
        kafkaConnection = Seq(ConnectionModel(producerHostKafka, producerPortKafka.toInt))))

    val input = new KafkaInput(kafkaStreamModelZk)
    val stream = input.createStream(ssc)
    val result = new mutable.HashMap[String, Long]() with mutable.SynchronizedMap[String, Long]

    stream.map(_._2).countByValue().foreachRDD { rdd =>
      val ret = rdd.collect()
      ret.toMap.foreach { case (key, value) =>
        val count = result.getOrElseUpdate(key, 0) + value
        result.put(key, count)
      }
    }

    ssc.start()

    eventually(timeout(10000 milliseconds), interval(1000 milliseconds)) {
      assert(valuesToSent === result)
    }
  }

  test("Kafka input stream with kafkaOptionsModel from list of Strings") {
    ssc = new StreamingContext(sc, Milliseconds(500))
    val valuesToSent = Array("a", "b", "c")
    kafkaTestUtils.createTopic(TopicTestProject)
    kafkaTestUtils.sendMessages(TopicTestProject, valuesToSent)

    val consumerHostZK = connectionHostModel.zkConnection.head.host
    val consumerPortZK = kafkaTestUtils.zkAddress.split(":").last.toInt

    val producerHostKafka = connectionHostModel.kafkaConnection.head.host
    val producerPortKafka = kafkaTestUtils.brokerAddress.split(":").last

    val kafkaStreamModelZk = kafkaStreamModelProject.copy(
      connection = connectionHostModel.copy(
        zkConnection = Seq(ConnectionModel(consumerHostZK, consumerPortZK)),
        kafkaConnection = Seq(ConnectionModel(producerHostKafka, producerPortKafka.toInt))))

    val input = new KafkaInput(kafkaStreamModelZk)
    val stream = input.createStream(ssc)
    val result = new mutable.MutableList[String]()

    stream.map(_._2).foreachRDD { rdd =>
      val ret = rdd.collect()
      ret.foreach(value => result.+=(value))
    }

    ssc.start()

    eventually(timeout(10000 milliseconds), interval(1000 milliseconds)) {
      assert(valuesToSent === result)
    }
  }

}


text:
package edu.kit.dama.mdm.content.impl;

import edu.kit.dama.mdm.content.impl.exceptions.MetaDataExtractionException;
import edu.kit.dama.mdm.base.UserData;
import edu.kit.dama.rest.staging.types.TransferTaskContainer;
import edu.kit.dama.commons.exceptions.PropertyValidationException;
import edu.kit.dama.staging.exceptions.StagingProcessorException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Element;

/**
 * Implementation of DC metadata extractor. This implementation maps attributes
 * of KIT Data Manager base metadata to the Dublin Core schema according to the
 * recommendations (see http://www.ietf.org/rfc/rfc5013.txt).
 *
 * @author mf6319
 */
public class DublinCoreMetadataExtractor extends AbstractMetadataExtractor {

    /**
     * ISO 8601 [W3CDTF] date format
     */
    public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

    /**
     * Default constructor.
     *
     * @param pUniqueIdentifier The unique identifier of the extractor.
     */
    public DublinCoreMetadataExtractor(String pUniqueIdentifier) {
        super(pUniqueIdentifier);
    }

    @Override
    protected void validateExtractorProperties(Properties pProperties) throws PropertyValidationException {
        //no properties needed
    }

    @Override
    protected String[] getExtractorPropertyKeys() {
        //no extra properties available
        return null;
    }

    @Override
    protected String getExtractorPropertyDescription(String pProperty) {
        return null;
    }

    @Override
    protected void configureExtractor(Properties pProperties) {
    }

    @Override
    protected void performPreTransferExtraction(TransferTaskContainer pContainer) throws StagingProcessorException {
    }

    @Override
    public String createMetadataDocument(TransferTaskContainer pContainer) throws StagingProcessorException {
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<oai_dc:dc \n"
                + "     xmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\" \n"
                + "     xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
                + "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
                + "     xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai_dc/ \n"
                + "     http://www.openarchives.org/OAI/2.0/oai_dc.xsd\">");

        xmlBuilder.append("<dc:title>").append(StringEscapeUtils.escapeXml11(getDigitalObject().getLabel())).append("</dc:title>");
        UserData uploader = getDigitalObject().getUploader();
        if (uploader != null) {
            xmlBuilder.append("<dc:creator>").append(StringEscapeUtils.escapeXml11(uploader.getFullname())).append("</dc:creator>");
            xmlBuilder.append("<dc:publisher>").append(StringEscapeUtils.escapeXml11(uploader.getFullname())).append("</dc:publisher>");
        }

        for (UserData experimenter : getDigitalObject().getExperimenters()) {
            //don't list uploader a second time here
            if (uploader == null || !experimenter.equals(uploader)) {
                xmlBuilder.append("<dc:contributor>").append(StringEscapeUtils.escapeXml11(experimenter.getFullname())).append("</dc:contributor>");
            }
        }

        if (getDigitalObject().getInvestigation() != null) {
            xmlBuilder.append("<dc:subject>").append(StringEscapeUtils.escapeXml11(getDigitalObject().getInvestigation().getTopic())).append("</dc:subject>");
            String description = getDigitalObject().getInvestigation().getDescription();
            if (description != null) {
                xmlBuilder.append("<dc:description>").append(StringEscapeUtils.escapeXml11(description)).append("</dc:description>");
            }
            if (getDigitalObject().getInvestigation().getStudy() != null) {
                String legalNotes = getDigitalObject().getInvestigation().getStudy().getLegalNote();
                if (legalNotes != null) {
                    xmlBuilder.append("<dc:rights>").append(StringEscapeUtils.escapeXml11(legalNotes)).append("</dc:rights>");
                }
            }
        }
        if (getDigitalObject().getStartDate() != null) {
            xmlBuilder.append("<dc:date>").append(new SimpleDateFormat(ISO_8601_DATE_FORMAT).format(getDigitalObject().getStartDate())).append("</dc:date>");
        }
        //not possible in our case - use binary type 'application/octet-stream'
        xmlBuilder.append("<dc:format>").append("application/octet-stream").append("</dc:format>");

        //see http://dublincore.org/documents/2012/06/14/dcmi-terms/?v=dcmitype
        xmlBuilder.append("<dc:type>").append("Dataset").append("</dc:type>");
        xmlBuilder.append("<dc:identifier>").append(StringEscapeUtils.escapeXml11(getDigitalObject().getDigitalObjectId().getStringRepresentation())).append("</dc:identifier>");

        //>>>not possible, yet -> later: getDigitalObject().getPredecessor() for processing results!?
        //xmlBuilder.append("<dc:source>").append(----).append("</dc:source>");
        //xmlBuilder.append("<dc:relation>").append(----).append("</dc:relation>");
        //>>>not relevant!? Otherwise refer to RFC 4646
        //xmlBuilder.append("<dc:language>").append("").append("</dc:language>");
        //Not relevant?!
        //xmlBuilder.append("<dc:coverage>").append("").append("</dc:coverage>");
        xmlBuilder.append("</oai_dc:dc>");

        return xmlBuilder.toString();
    }

    @Override
    protected Element createCommunitySpecificElement(TransferTaskContainer pContainer) throws MetaDataExtractionException {
        //not needed here
        return null;
    }

    @Override
    public String getName() {
        return "DublinCoreMetadataExtractor";
    }

//  public static void main(String[] args) throws Exception {
//    DigitalObject dob = DigitalObject.factoryNewDigitalObject("1234567890");
//    dob.setLabel("Test");
//    dob.setStartDate(new Date(100));
//    ExtractDCMetadata ex = new ExtractDCMetadata("12345");
//    ex.setDigitalObject(dob);
//    String result = ex.createMetadataDocument(null);
//
//    String expectedResult = "<oai_dc:dc \n"
//            + "     xmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\" \n"
//            + "     xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \n"
//            + "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
//            + "     xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai_dc/ \n"
//            + "     http://www.openarchives.org/OAI/2.0/oai_dc.xsd\"><dc:title>Test</dc:title><dc:date>1970-01-01T01:00:00+0100</dc:date><dc:format>application/octet-stream</dc:format><dc:type>Dataset</dc:type><dc:identifier>1234567890</dc:identifier></oai_dc:dc>";
//
//    System.out.println(result);
//    System.out.println("Everything is as expected: " + expectedResult.equals(result));
//  }
}


text:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>

#include <linux/configfs.h>

/*
 * 01-childless
 *
 * This first example is a childless subsystem.  It cannot create
 * any config_items.  It just has attributes.
 *
 * Note that we are enclosing the configfs_subsystem inside a container.
 * This is not necessary if a subsystem has no attributes directly
 * on the subsystem.  See the next example, 02-simple-children, for
 * such a subsystem.
 */

struct childless {
	struct configfs_subsystem subsys;
	int showme;
	int storeme;
};

struct childless_attribute {
	struct configfs_attribute attr;
	ssize_t (*show)(struct childless *, char *);
	ssize_t (*store)(struct childless *, const char *, size_t);
};

static inline struct childless *to_childless(struct config_item *item)
{
	return item ? container_of(to_configfs_subsystem(to_config_group(item)), struct childless, subsys) : NULL;
}

static ssize_t childless_showme_read(struct childless *childless,
				     char *page)
{
	ssize_t pos;

	pos = sprintf(page, "%d\n", childless->showme);
	childless->showme++;

	return pos;
}

static ssize_t childless_storeme_read(struct childless *childless,
				      char *page)
{
	return sprintf(page, "%d\n", childless->storeme);
}

static ssize_t childless_storeme_write(struct childless *childless,
				       const char *page,
				       size_t count)
{
	unsigned long tmp;
	char *p = (char *) page;

	tmp = simple_strtoul(p, &p, 10);
	if (!p || (*p && (*p != '\n')))
		return -EINVAL;

	if (tmp > INT_MAX)
		return -ERANGE;

	childless->storeme = tmp;

	return count;
}

static ssize_t childless_description_read(struct childless *childless,
					  char *page)
{
	return sprintf(page,
"[01-childless]\n"
"\n"
"The childless subsystem is the simplest possible subsystem in\n"
"configfs.  It does not support the creation of child config_items.\n"
"It only has a few attributes.  In fact, it isn't much different\n"
"than a directory in /proc.\n");
}

static struct childless_attribute childless_attr_showme = {
	.attr	= { .ca_owner = THIS_MODULE, .ca_name = "showme", .ca_mode = S_IRUGO },
	.show	= childless_showme_read,
};
static struct childless_attribute childless_attr_storeme = {
	.attr	= { .ca_owner = THIS_MODULE, .ca_name = "storeme", .ca_mode = S_IRUGO | S_IWUSR },
	.show	= childless_storeme_read,
	.store	= childless_storeme_write,
};
static struct childless_attribute childless_attr_description = {
	.attr = { .ca_owner = THIS_MODULE, .ca_name = "description", .ca_mode = S_IRUGO },
	.show = childless_description_read,
};

static struct configfs_attribute *childless_attrs[] = {
	&childless_attr_showme.attr,
	&childless_attr_storeme.attr,
	&childless_attr_description.attr,
	NULL,
};

static ssize_t childless_attr_show(struct config_item *item,
				   struct configfs_attribute *attr,
				   char *page)
{
	struct childless *childless = to_childless(item);
	struct childless_attribute *childless_attr =
		container_of(attr, struct childless_attribute, attr);
	ssize_t ret = 0;

	if (childless_attr->show)
		ret = childless_attr->show(childless, page);
	return ret;
}

static ssize_t childless_attr_store(struct config_item *item,
				    struct configfs_attribute *attr,
				    const char *page, size_t count)
{
	struct childless *childless = to_childless(item);
	struct childless_attribute *childless_attr =
		container_of(attr, struct childless_attribute, attr);
	ssize_t ret = -EINVAL;

	if (childless_attr->store)
		ret = childless_attr->store(childless, page, count);
	return ret;
}

static struct configfs_item_operations childless_item_ops = {
	.show_attribute		= childless_attr_show,
	.store_attribute	= childless_attr_store,
};

static struct config_item_type childless_type = {
	.ct_item_ops	= &childless_item_ops,
	.ct_attrs	= childless_attrs,
	.ct_owner	= THIS_MODULE,
};

static struct childless childless_subsys = {
	.subsys = {
		.su_group = {
			.cg_item = {
				.ci_namebuf = "01-childless",
				.ci_type = &childless_type,
			},
		},
	},
};

/* ----------------------------------------------------------------- */

/*
 * 02-simple-children
 *
 * This example merely has a simple one-attribute child.  Note that
 * there is no extra attribute structure, as the child's attribute is
 * known from the get-go.  Also, there is no container for the
 * subsystem, as it has no attributes of its own.
 */

struct simple_child {
	struct config_item item;
	int storeme;
};

static inline struct simple_child *to_simple_child(struct config_item *item)
{
	return item ? container_of(item, struct simple_child, item) : NULL;
}

static struct configfs_attribute simple_child_attr_storeme = {
	.ca_owner = THIS_MODULE,
	.ca_name = "storeme",
	.ca_mode = S_IRUGO | S_IWUSR,
};

static struct configfs_attribute *simple_child_attrs[] = {
	&simple_child_attr_storeme,
	NULL,
};

static ssize_t simple_child_attr_show(struct config_item *item,
				      struct configfs_attribute *attr,
				      char *page)
{
	ssize_t count;
	struct simple_child *simple_child = to_simple_child(item);

	count = sprintf(page, "%d\n", simple_child->storeme);

	return count;
}

static ssize_t simple_child_attr_store(struct config_item *item,
				       struct configfs_attribute *attr,
				       const char *page, size_t count)
{
	struct simple_child *simple_child = to_simple_child(item);
	unsigned long tmp;
	char *p = (char *) page;

	tmp = simple_strtoul(p, &p, 10);
	if (!p || (*p && (*p != '\n')))
		return -EINVAL;

	if (tmp > INT_MAX)
		return -ERANGE;

	simple_child->storeme = tmp;

	return count;
}

static void simple_child_release(struct config_item *item)
{
	kfree(to_simple_child(item));
}

static struct configfs_item_operations simple_child_item_ops = {
	.release		= simple_child_release,
	.show_attribute		= simple_child_attr_show,
	.store_attribute	= simple_child_attr_store,
};

static struct config_item_type simple_child_type = {
	.ct_item_ops	= &simple_child_item_ops,
	.ct_attrs	= simple_child_attrs,
	.ct_owner	= THIS_MODULE,
};

struct simple_children {
	struct config_group group;
};

static inline struct simple_children *to_simple_children(struct config_item *item)
{
	return item ? container_of(to_config_group(item), struct simple_children, group) : NULL;
}

static struct config_item *simple_children_make_item(struct config_group *group, const char *name)
{
	struct simple_child *simple_child;

	simple_child = kzalloc(sizeof(struct simple_child), GFP_KERNEL);
	if (!simple_child)
		return ERR_PTR(-ENOMEM);

	config_item_init_type_name(&simple_child->item, name,
				   &simple_child_type);

	simple_child->storeme = 0;

	return &simple_child->item;
}

static struct configfs_attribute simple_children_attr_description = {
	.ca_owner = THIS_MODULE,
	.ca_name = "description",
	.ca_mode = S_IRUGO,
};

static struct configfs_attribute *simple_children_attrs[] = {
	&simple_children_attr_description,
	NULL,
};

static ssize_t simple_children_attr_show(struct config_item *item,
					 struct configfs_attribute *attr,
					 char *page)
{
	return sprintf(page,
"[02-simple-children]\n"
"\n"
"This subsystem allows the creation of child config_items.  These\n"
"items have only one attribute that is readable and writeable.\n");
}

static void simple_children_release(struct config_item *item)
{
	kfree(to_simple_children(item));
}

static struct configfs_item_operations simple_children_item_ops = {
	.release	= simple_children_release,
	.show_attribute	= simple_children_attr_show,
};

/*
 * Note that, since no extra work is required on ->drop_item(),
 * no ->drop_item() is provided.
 */
static struct configfs_group_operations simple_children_group_ops = {
	.make_item	= simple_children_make_item,
};

static struct config_item_type simple_children_type = {
	.ct_item_ops	= &simple_children_item_ops,
	.ct_group_ops	= &simple_children_group_ops,
	.ct_attrs	= simple_children_attrs,
	.ct_owner	= THIS_MODULE,
};

static struct configfs_subsystem simple_children_subsys = {
	.su_group = {
		.cg_item = {
			.ci_namebuf = "02-simple-children",
			.ci_type = &simple_children_type,
		},
	},
};

/* ----------------------------------------------------------------- */

/*
 * 03-group-children
 *
 * This example reuses the simple_children group from above.  However,
 * the simple_children group is not the subsystem itself, it is a
 * child of the subsystem.  Creation of a group in the subsystem creates
 * a new simple_children group.  That group can then have simple_child
 * children of its own.
 */

static struct config_group *group_children_make_group(struct config_group *group, const char *name)
{
	struct simple_children *simple_children;

	simple_children = kzalloc(sizeof(struct simple_children),
				  GFP_KERNEL);
	if (!simple_children)
		return ERR_PTR(-ENOMEM);

	config_group_init_type_name(&simple_children->group, name,
				    &simple_children_type);

	return &simple_children->group;
}

static struct configfs_attribute group_children_attr_description = {
	.ca_owner = THIS_MODULE,
	.ca_name = "description",
	.ca_mode = S_IRUGO,
};

static struct configfs_attribute *group_children_attrs[] = {
	&group_children_attr_description,
	NULL,
};

static ssize_t group_children_attr_show(struct config_item *item,
					struct configfs_attribute *attr,
					char *page)
{
	return sprintf(page,
"[03-group-children]\n"
"\n"
"This subsystem allows the creation of child config_groups.  These\n"
"groups are like the subsystem simple-children.\n");
}

static struct configfs_item_operations group_children_item_ops = {
	.show_attribute	= group_children_attr_show,
};

/*
 * Note that, since no extra work is required on ->drop_item(),
 * no ->drop_item() is provided.
 */
static struct configfs_group_operations group_children_group_ops = {
	.make_group	= group_children_make_group,
};

static struct config_item_type group_children_type = {
	.ct_item_ops	= &group_children_item_ops,
	.ct_group_ops	= &group_children_group_ops,
	.ct_attrs	= group_children_attrs,
	.ct_owner	= THIS_MODULE,
};

static struct configfs_subsystem group_children_subsys = {
	.su_group = {
		.cg_item = {
			.ci_namebuf = "03-group-children",
			.ci_type = &group_children_type,
		},
	},
};

/* ----------------------------------------------------------------- */

/*
 * We're now done with our subsystem definitions.
 * For convenience in this module, here's a list of them all.  It
 * allows the init function to easily register them.  Most modules
 * will only have one subsystem, and will only call register_subsystem
 * on it directly.
 */
static struct configfs_subsystem *example_subsys[] = {
	&childless_subsys.subsys,
	&simple_children_subsys,
	&group_children_subsys,
	NULL,
};

static int __init configfs_example_init(void)
{
	int ret;
	int i;
	struct configfs_subsystem *subsys;

	for (i = 0; example_subsys[i]; i++) {
		subsys = example_subsys[i];

		config_group_init(&subsys->su_group);
		mutex_init(&subsys->su_mutex);
		ret = configfs_register_subsystem(subsys);
		if (ret) {
			printk(KERN_ERR "Error %d while registering subsystem %s\n",
			       ret,
			       subsys->su_group.cg_item.ci_namebuf);
			goto out_unregister;
		}
	}

	return 0;

out_unregister:
	for (; i >= 0; i--) {
		configfs_unregister_subsystem(example_subsys[i]);
	}

	return ret;
}

static void __exit configfs_example_exit(void)
{
	int i;

	for (i = 0; example_subsys[i]; i++) {
		configfs_unregister_subsystem(example_subsys[i]);
	}
}

module_init(configfs_example_init);
module_exit(configfs_example_exit);
MODULE_LICENSE("GPL");


text:
package com.example.stitcher;

// [START videostitcher_get_vod_stitch_detail]

import com.google.cloud.video.stitcher.v1.GetVodStitchDetailRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodStitchDetail;
import com.google.cloud.video.stitcher.v1.VodStitchDetailName;
import java.io.IOException;

public class GetVodStitchDetail {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String sessionId = "my-session-id";
    String stitchDetailId = "my-stitch-id";

    getVodStitchDetail(projectId, location, sessionId, stitchDetailId);
  }

  public static void getVodStitchDetail(
      String projectId, String location, String sessionId, String stitchDetailId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      GetVodStitchDetailRequest getVodStitchDetailRequest =
          GetVodStitchDetailRequest.newBuilder()
              .setName(
                  VodStitchDetailName.of(projectId, location, sessionId, stitchDetailId).toString())
              .build();

      VodStitchDetail response =
          videoStitcherServiceClient.getVodStitchDetail(getVodStitchDetailRequest);
      System.out.println("VOD stitch detail: " + response.getName());
    }
  }
}
// [END videostitcher_get_vod_stitch_detail]