text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
  <extension point="org.eclipse.debug.ui.launchConfigurationTypeImages">
    <launchConfigurationTypeImage
      icon="$nl$/icons/weaving_launcher.gif"
      configTypeID="org.scala-ide.ew.launcher.RuntimeWorkbench"
      id="org.scala-ide.ew.launcher.runtimeWorkbenchLaunchImage">
    </launchConfigurationTypeImage>
    <launchConfigurationTypeImage
      icon="$nl$/icons/weaving_launcher.gif"
      configTypeID="org.scala-ide.ew.launcher.JunitLaunchConfig"
      id="org.scala-ide.ew.launcher.JunitLaunchImage">
    </launchConfigurationTypeImage>
  </extension>

	<extension point="org.eclipse.debug.ui.launchConfigurationTabGroups">
		<launchConfigurationTabGroup
			type="org.scala-ide.ew.launcher.RuntimeWorkbench"
			class="org.scalaide.ew.launcher.EquinoxWeavingLauncherTabGroup"
			id="org.scala-ide.ew.launcher.WorkbenchLauncherTabGroup">
			<launchMode
				description="Create a configuration to launch an Equinox Weaving enabled Eclipse application in debug mode."
				perspective="org.eclipse.debug.ui.DebugPerspective"
				mode="debug">
			</launchMode>
			<launchMode
				description="Create a configuration to launch an Equinox Weaving enabled Eclipse application."
				mode="run">
			</launchMode>
		</launchConfigurationTabGroup>

    <launchConfigurationTabGroup
       type="org.scala-ide.ew.launcher.JunitLaunchConfig"
       class="org.scalaide.ew.launcher.EquinoxWeavingJUnitTabGroup"
       id="org.scala-ide.ew.launcher.JUnitTabGroup">
       <launchMode
         description="Create a configuration that will launch an Equinox Weaving enabled JUnit plug-in test in debug mode."
         perspective="org.eclipse.debug.ui.DebugPerspective"
         mode="debug">
       </launchMode>
       <launchMode
         description="Create a configuration that will launch an Equinox Weaving enabled JUnit plug-in test."
         mode="run">
       </launchMode>
    </launchConfigurationTabGroup>
	</extension>

  <extension
    point="org.eclipse.jdt.junit.junitLaunchConfigs">
    <launchConfigType
      configTypeID="org.scala-ide.ew.launcher.JunitLaunchConfig">
    </launchConfigType>
  </extension>

  <extension point="org.eclipse.debug.ui.launchShortcuts">
		<shortcut
      label="Equinox Weaving enabled Eclipse Application"
      icon="$nl$/icons/weaving_launcher.gif"
      modes="run, debug"
      class="org.scalaide.ew.launcher.EquinoxWeavingEclipseLaunchShortcut"
      id="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut">
 			<contextualLaunch>
				<enablement>
					<with variable="selection">
						<count value="1"/>
						<iterate>
 							<and>
								<instanceof value="org.eclipse.core.runtime.IAdaptable"/>
								<test property="org.eclipse.debug.ui.projectNature" value="org.eclipse.pde.PluginNature"/>
								<or>
									<adapt type="org.eclipse.core.resources.IProject"/>
									<test property="org.eclipse.debug.ui.matchesPattern" value="plugin.xml"/>
									<test property="org.eclipse.debug.ui.matchesPattern" value="MANIFEST.MF"/>
									<test property="org.eclipse.debug.ui.matchesPattern" value="*.product"/>
								</or>
 							</and>
						</iterate>
 					</with>
 				</enablement>
 			</contextualLaunch>
 			<configurationType
 				id="org.scala-ide.ew.launcher.RuntimeWorkbench">
 			</configurationType>
 			<description
 				description="Runs a separate Equinox Weaving enabled Eclipse application"
 				mode="run">
 			</description>
 			<description
 				description="Debugs a separate Equinox Weaving enabled Eclipse application"
 				mode="debug">
 			</description>
		</shortcut>

    <shortcut
      label="Equinox Weaving enabled JUnit Plug-in Test"
      icon="$nl$/icons/weaving_launcher.gif"
      modes="run, debug"
      class="org.scalaide.ew.launcher.EquinoxWeavingJUnitWorkbenchLaunchShortcut"
      id="org.scala-ide.ew.launcher.junitWorkbenchShortcut">
      <contextualLaunch>
        <enablement>
          <with variable="selection">
            <count value="1"/>
            <iterate>
              <adapt type="org.eclipse.jdt.core.IJavaElement">
		            <test property="org.eclipse.jdt.core.isInJavaProjectWithNature" value="org.eclipse.pde.PluginNature"/>
		            <test property="org.eclipse.jdt.core.hasTypeOnClasspath" value="junit.framework.Test"/>
		            <test property="org.eclipse.jdt.junit.canLaunchAsJUnit" forcePluginActivation="true"/>
		          </adapt>
		        </iterate>
          </with>
        </enablement>
      </contextualLaunch>
      <configurationType
        id="org.scala-ide.ew.launcher.JunitLaunchConfig">
      </configurationType>
      <description
        description="Runs a set of Equinox Weaving enabled JUnit plug-in tests"
        mode="run">
      </description>
      <description
        description="Debugs a set of Equinox Weaving enabled JUnit plug-in tests"
        mode="debug">
      </description>
    </shortcut>
	</extension>

  <extension point="org.eclipse.pde.ui.launchShortcuts">
    <shortcut
      id="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut"
      label="Launch an Equinox Weaving enabled Eclipse application"
      mode="run">
    </shortcut>
    <shortcut
      id="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut"
      label="Launch an Equinox Weaving enabled Eclipse application in Debug mode"
      mode="debug">
    </shortcut>
  </extension>

  <extension point="org.eclipse.ui.commands">
    <command
      name="Debug Equinox Weaving enabled Eclipse Application"
      description="Debug Equinox Weaving enabled Eclipse Application"
      categoryId="org.eclipse.debug.ui.category.run"
      id="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut.debug">
    </command>
    <command
      name="Run Equinox Weaving enabled Eclipse Application"
      description="Run Equinox Weaving enabled Eclipse Application"
      categoryId="org.eclipse.debug.ui.category.run"
      id="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut.run">
    </command>
    <command
      name="Debug Equinox Weaving enabled JUnit Plug-in Test"
      description="Debug Equinox Weaving enabled JUnit Plug-in Test"
      categoryId="org.eclipse.debug.ui.category.run"
      id="org.scala-ide.ew.launcher.junitWorkbenchShortcut.debug">
    </command>
    <command
      name="Run Equinox Weaving enabled JUnit Plug-in Test"
      description="Run Equinox Weaving enabled JUnit Plug-in Test"
      categoryId="org.eclipse.debug.ui.category.run"
      id="org.scala-ide.ew.launcher.junitWorkbenchShortcut.run">
    </command>
  </extension>

 	<extension point="org.eclipse.debug.core.launchConfigurationTypes">
		<launchConfigurationType
      delegate="org.scalaide.ew.launcher.EquinoxWeavingApplicationLaunchConfiguration"
      delegateDescription="The Equinox Weaving enabled Eclipse Application launcher is used to run or debug a separate instance of an Equinox Weaving enabled Eclipse application"
      delegateName="Equinox Weaving enabled Eclipse Application Launcher"
      id="org.scala-ide.ew.launcher.RuntimeWorkbench"
      migrationDelegate="org.eclipse.pde.internal.launching.launcher.PDEMigrationDelegate"
      modes="run, debug"
      name="Eclipse Application with Equinox Weaving "
      sourceLocatorId="org.eclipse.pde.ui.launcher.PDESourceLookupDirector"
      sourcePathComputerId="org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer">
		</launchConfigurationType>

    <launchConfigurationType
      delegate="org.scalaide.ew.launcher.EquinoxWeavingJUnitLaunchConfigurationDelegate"
      delegateDescription="The Equinox Weaving enabled JUnit Plugin Test launcher is used to run and debug test suites for Equinox Weaving enabled plug-in projects"
      delegateName="Equinox Weaving enabled JUnit Plugin Test Launcher"
      id="org.scala-ide.ew.launcher.JunitLaunchConfig"
      migrationDelegate="org.eclipse.pde.internal.launching.launcher.PDEMigrationDelegate"
      modes="run, debug"
      name="JUnit Plug-in Test with Equinox Weaving "
      sourceLocatorId="org.eclipse.pde.ui.launcher.PDESourceLookupDirector"
      sourcePathComputerId="org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer">
    </launchConfigurationType>
	</extension>

  <extension point="org.eclipse.ui.bindings">
    <key
      sequence="M2+M3+D W"
      commandId="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut.debug"
      schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
    </key>
    <key
      sequence="M2+M3+X W"
      commandId="org.scala-ide.ew.launcher.runtimeWorkbenchShortcut.run"
      schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
    </key>
    <key
      sequence="M2+M3+D U"
      commandId="org.scala-ide.ew.launcher.junitWorkbenchShortcut.debug"
      schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
    </key>
    <key
      sequence="M2+M3+X U"
      commandId="org.scala-ide.ew.launcher.junitWorkbenchShortcut.run"
      schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
    </key>
  </extension>
</plugin>


text:
import type { Object } from 'ts-toolbelt';
import type Koa from 'koa';
import type { Store as ReduxStore } from 'redux';
import type * as ActionCreators from './core/action-creators';
import type { ActionErrorType, UpdateErrorType } from './core/errors';
import type { Flow } from './core/flow';
import type { CreateGameReducer } from './core/reducer';
import type { INVALID_MOVE } from './core/constants';
import type { GameMethod } from './core/game-methods';
import type { Auth } from './server/auth';
import type * as StorageAPI from './server/db/base';
import type { EventsAPI } from './plugins/plugin-events';
import type { LogAPI } from './plugins/plugin-log';
import type { RandomAPI } from './plugins/random/random';
import type { Operation } from 'rfc6902';
export type { StorageAPI };
export declare type AnyFn = (...args: any[]) => any;
export interface State<G extends any = any> {
    G: G;
    ctx: Ctx;
    deltalog?: Array<LogEntry>;
    plugins: {
        [pluginName: string]: PluginState;
    };
    _undo: Array<Undo<G>>;
    _redo: Array<Undo<G>>;
    _stateID: number;
}
export declare type ErrorType = UpdateErrorType | ActionErrorType;
export interface ActionError {
    type: ErrorType;
    payload?: any;
}
export interface TransientMetadata {
    error?: ActionError;
}
export declare type ActionResult = any;
export interface TransientState<G extends any = any> extends State<G> {
    transients?: TransientMetadata;
}
export declare type PartialGameState = Pick<State, 'G' | 'ctx' | 'plugins'>;
export declare type StageName = string;
export declare type PlayerID = string;
export declare type StageArg = StageName | {
    stage?: StageName;
    /** @deprecated Use `minMoves` and `maxMoves` instead. */
    moveLimit?: number;
    minMoves?: number;
    maxMoves?: number;
};
export declare type ActivePlayersArg = PlayerID[] | {
    currentPlayer?: StageArg;
    others?: StageArg;
    all?: StageArg;
    value?: Record<PlayerID, StageArg>;
    minMoves?: number;
    maxMoves?: number;
    /** @deprecated Use `minMoves` and `maxMoves` instead. */
    moveLimit?: number;
    revert?: boolean;
    next?: ActivePlayersArg;
};
export interface ActivePlayers {
    [playerID: string]: StageName;
}
export interface Ctx {
    numPlayers: number;
    playOrder: Array<PlayerID>;
    playOrderPos: number;
    activePlayers: null | ActivePlayers;
    currentPlayer: PlayerID;
    numMoves?: number;
    gameover?: any;
    turn: number;
    phase: string;
    _activePlayersMinMoves?: Record<PlayerID, number>;
    _activePlayersMaxMoves?: Record<PlayerID, number>;
    _activePlayersNumMoves?: Record<PlayerID, number>;
    _prevActivePlayers?: Array<{
        activePlayers: null | ActivePlayers;
        _activePlayersMinMoves?: Record<PlayerID, number>;
        _activePlayersMaxMoves?: Record<PlayerID, number>;
        _activePlayersNumMoves?: Record<PlayerID, number>;
    }>;
    _nextActivePlayers?: ActivePlayersArg;
    _random?: {
        seed: string | number;
    };
}
export interface DefaultPluginAPIs {
    events: EventsAPI;
    log: LogAPI;
    random: RandomAPI;
}
export interface PluginState {
    data: any;
    api?: any;
}
export interface LogEntry {
    action: ActionShape.MakeMove | ActionShape.GameEvent | ActionShape.Undo | ActionShape.Redo;
    _stateID: number;
    turn: number;
    phase: string;
    redact?: boolean;
    automatic?: boolean;
    metadata?: any;
    patch?: Operation[];
}
export interface PluginContext<API extends any = any, Data extends any = any, G extends any = any> {
    G: G;
    ctx: Ctx;
    game: Game;
    api: API;
    data: Data;
}
export interface Plugin<API extends any = any, Data extends any = any, G extends any = any> {
    name: string;
    noClient?: (context: PluginContext<API, Data, G>) => boolean;
    setup?: (setupCtx: {
        G: G;
        ctx: Ctx;
        game: Game<G>;
    }) => Data;
    isInvalid?: (context: Omit<PluginContext<API, Data, G>, 'api'>) => false | string;
    action?: (data: Data, payload: ActionShape.Plugin['payload']) => Data;
    api?: (context: {
        G: G;
        ctx: Ctx;
        game: Game<G>;
        data: Data;
        playerID?: PlayerID;
    }) => API;
    flush?: (context: PluginContext<API, Data, G>) => Data;
    dangerouslyFlushRawState?: (flushCtx: {
        state: State<G>;
        game: Game<G>;
        api: API;
        data: Data;
    }) => State<G>;
    fnWrap?: (moveOrHook: (context: FnContext<G>, ...args: any[]) => any, methodType: GameMethod) => (context: FnContext<G>, ...args: any[]) => any;
    playerView?: (context: {
        G: G;
        ctx: Ctx;
        game: Game<G>;
        data: Data;
        playerID?: PlayerID | null;
    }) => any;
}
export declare type FnContext<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> = PluginAPIs & DefaultPluginAPIs & {
    G: G;
    ctx: Ctx;
};
export declare type MoveFn<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> = (context: FnContext<G, PluginAPIs> & {
    playerID: PlayerID;
}, ...args: any[]) => void | G | typeof INVALID_MOVE;
export interface LongFormMove<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    move: MoveFn<G, PluginAPIs>;
    redact?: boolean | ((context: {
        G: G;
        ctx: Ctx;
    }) => boolean);
    noLimit?: boolean;
    client?: boolean;
    undoable?: boolean | ((context: {
        G: G;
        ctx: Ctx;
    }) => boolean);
    ignoreStaleStateID?: boolean;
}
export declare type Move<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> = MoveFn<G, PluginAPIs> | LongFormMove<G, PluginAPIs>;
export interface MoveMap<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    [moveName: string]: Move<G, PluginAPIs>;
}
export interface PhaseConfig<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    start?: boolean;
    next?: ((context: FnContext<G, PluginAPIs>) => string | void) | string;
    onBegin?: (context: FnContext<G, PluginAPIs>) => void | G;
    onEnd?: (context: FnContext<G, PluginAPIs>) => void | G;
    endIf?: (context: FnContext<G, PluginAPIs>) => boolean | void | {
        next: string;
    };
    moves?: MoveMap<G, PluginAPIs>;
    turn?: TurnConfig<G, PluginAPIs>;
    wrapped?: {
        endIf?: (state: State<G>) => boolean | void | {
            next: string;
        };
        onBegin?: (state: State<G>) => void | G;
        onEnd?: (state: State<G>) => void | G;
        next?: (state: State<G>) => string | void;
    };
}
export interface StageConfig<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    moves?: MoveMap<G, PluginAPIs>;
    next?: string;
}
export interface StageMap<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    [stageName: string]: StageConfig<G, PluginAPIs>;
}
export interface TurnOrderConfig<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    first: (context: FnContext<G, PluginAPIs>) => number;
    next: (context: FnContext<G, PluginAPIs>) => number | undefined;
    playOrder?: (context: FnContext<G, PluginAPIs>) => PlayerID[];
}
export interface TurnConfig<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    activePlayers?: ActivePlayersArg;
    minMoves?: number;
    maxMoves?: number;
    /** @deprecated Use `minMoves` and `maxMoves` instead. */
    moveLimit?: number;
    onBegin?: (context: FnContext<G, PluginAPIs>) => void | G;
    onEnd?: (context: FnContext<G, PluginAPIs>) => void | G;
    endIf?: (context: FnContext<G, PluginAPIs>) => boolean | void | {
        next: PlayerID;
    };
    onMove?: (context: FnContext<G, PluginAPIs> & {
        playerID: PlayerID;
    }) => void | G;
    stages?: StageMap<G, PluginAPIs>;
    order?: TurnOrderConfig<G, PluginAPIs>;
    wrapped?: {
        endIf?: (state: State<G>) => boolean | void | {
            next: PlayerID;
        };
        onBegin?: (state: State<G>) => void | G;
        onEnd?: (state: State<G>) => void | G;
        onMove?: (state: State<G> & {
            playerID: PlayerID;
        }) => void | G;
    };
}
export interface PhaseMap<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>> {
    [phaseName: string]: PhaseConfig<G, PluginAPIs>;
}
export declare type AiEnumerate = Array<{
    event: string;
    args?: any[];
} | {
    move: string;
    args?: any[];
} | ActionShape.MakeMove | ActionShape.GameEvent>;
export interface Game<G extends any = any, PluginAPIs extends Record<string, unknown> = Record<string, unknown>, SetupData extends any = any> {
    name?: string;
    minPlayers?: number;
    maxPlayers?: number;
    deltaState?: boolean;
    disableUndo?: boolean;
    seed?: string | number;
    setup?: (context: PluginAPIs & DefaultPluginAPIs & {
        ctx: Ctx;
    }, setupData?: SetupData) => G;
    validateSetupData?: (setupData: SetupData | undefined, numPlayers: number) => string | undefined;
    moves?: MoveMap<G, PluginAPIs>;
    phases?: PhaseMap<G, PluginAPIs>;
    turn?: TurnConfig<G, PluginAPIs>;
    events?: {
        endGame?: boolean;
        endPhase?: boolean;
        endTurn?: boolean;
        setPhase?: boolean;
        endStage?: boolean;
        setStage?: boolean;
        pass?: boolean;
        setActivePlayers?: boolean;
    };
    endIf?: (context: FnContext<G, PluginAPIs>) => any;
    onEnd?: (context: FnContext<G, PluginAPIs>) => void | G;
    playerView?: (context: {
        G: G;
        ctx: Ctx;
        playerID: PlayerID | null;
    }) => any;
    plugins?: Array<Plugin<any, any, G>>;
    ai?: {
        enumerate: (G: G, ctx: Ctx, playerID: PlayerID) => AiEnumerate;
    };
    processMove?: (state: State<G>, action: ActionPayload.MakeMove) => State<G> | typeof INVALID_MOVE;
    flow?: ReturnType<typeof Flow>;
}
export declare type Undo<G extends any = any> = {
    G: G;
    ctx: Ctx;
    plugins: {
        [pluginName: string]: PluginState;
    };
    moveType?: string;
    playerID?: PlayerID;
};
export declare namespace Server {
    type GenerateCredentials = (ctx: Koa.DefaultContext) => Promise<string> | string;
    type AuthenticateCredentials = (credentials: string, playerMetadata: PlayerMetadata) => Promise<boolean> | boolean;
    type PlayerMetadata = {
        id: number;
        name?: string;
        credentials?: string;
        data?: any;
        isConnected?: boolean;
    };
    interface MatchData {
        gameName: string;
        players: {
            [id: number]: PlayerMetadata;
        };
        setupData?: any;
        gameover?: any;
        nextMatchID?: string;
        unlisted?: boolean;
        createdAt: number;
        updatedAt: number;
    }
    type AppCtx = Koa.DefaultContext & {
        db: StorageAPI.Async | StorageAPI.Sync;
        auth: Auth;
    };
    type App = Koa<Koa.DefaultState, AppCtx>;
}
export declare namespace LobbyAPI {
    export type GameList = string[];
    type PublicPlayerMetadata = Omit<Server.PlayerMetadata, 'credentials'>;
    export type Match = Omit<Server.MatchData, 'players'> & {
        matchID: string;
        players: PublicPlayerMetadata[];
    };
    export interface MatchList {
        matches: Match[];
    }
    export interface CreatedMatch {
        matchID: string;
    }
    export interface JoinedMatch {
        playerID: string;
        playerCredentials: string;
    }
    export interface NextMatch {
        nextMatchID: string;
    }
    export {};
}
export declare type Reducer = ReturnType<typeof CreateGameReducer>;
export declare type Store = ReduxStore<State, ActionShape.Any>;
export declare namespace CredentialedActionShape {
    type MakeMove = ReturnType<typeof ActionCreators.makeMove>;
    type GameEvent = ReturnType<typeof ActionCreators.gameEvent>;
    type Plugin = ReturnType<typeof ActionCreators.plugin>;
    type AutomaticGameEvent = ReturnType<typeof ActionCreators.automaticGameEvent>;
    type Undo = ReturnType<typeof ActionCreators.undo>;
    type Redo = ReturnType<typeof ActionCreators.redo>;
    type Any = MakeMove | GameEvent | AutomaticGameEvent | Undo | Redo | Plugin;
}
export declare namespace ActionShape {
    type StripCredentials<T extends CredentialedActionShape.Any> = Object.P.Omit<T, ['payload', 'credentials']>;
    export type MakeMove = StripCredentials<CredentialedActionShape.MakeMove>;
    export type GameEvent = StripCredentials<CredentialedActionShape.GameEvent>;
    export type Plugin = StripCredentials<CredentialedActionShape.Plugin>;
    export type AutomaticGameEvent = StripCredentials<CredentialedActionShape.AutomaticGameEvent>;
    export type Sync = ReturnType<typeof ActionCreators.sync>;
    export type Update = ReturnType<typeof ActionCreators.update>;
    export type Patch = ReturnType<typeof ActionCreators.patch>;
    export type Reset = ReturnType<typeof ActionCreators.reset>;
    export type Undo = StripCredentials<CredentialedActionShape.Undo>;
    export type Redo = StripCredentials<CredentialedActionShape.Redo>;
    export type StripTransients = ReturnType<typeof ActionCreators.stripTransients>;
    export type Any = MakeMove | GameEvent | AutomaticGameEvent | Sync | Update | Patch | Reset | Undo | Redo | Plugin | StripTransients;
    export {};
}
export declare namespace ActionPayload {
    type GetPayload<T extends ActionShape.Any> = Object.At<T, 'payload'>;
    export type MakeMove = GetPayload<ActionShape.MakeMove>;
    export type GameEvent = GetPayload<ActionShape.GameEvent>;
    export {};
}
export declare type FilteredMetadata = {
    id: number;
    name?: string;
    isConnected?: boolean;
}[];
export interface SyncInfo {
    state: State;
    filteredMetadata: FilteredMetadata;
    initialState: State;
    log: LogEntry[];
}
export interface ChatMessage {
    id: string;
    sender: PlayerID;
    payload: any;
}

redpajama_set_name: RedPajamaGithub


text:
using v8::FunctionTemplate;

// NativeExtension.cc represents the top level of the module.
// C++ constructs that are exposed to javascript are exported here

NAN_MODULE_INIT(InitAll) {

  Nan::Set(target, Nan::New("init").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(Init)).ToLocalChecked());
  Nan::Set(target, Nan::New("getSdkVersion").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(GetSdkVersion)).ToLocalChecked());

  Nan::Set(target, Nan::New("getConfigOptionNumber").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(GetConfigOptionNumber)).ToLocalChecked());
  Nan::Set(target, Nan::New("getConfigOptionBool").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(GetConfigOptionBool)).ToLocalChecked());
  Nan::Set(target, Nan::New("getConfigOptionColor").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(GetConfigOptionColor)).ToLocalChecked());
  Nan::Set(target, Nan::New("setConfigOptionLabel").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetConfigOptionLabel)).ToLocalChecked());

  Nan::Set(target, Nan::New("setTargetDevice").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetTargetDevice)).ToLocalChecked());
  Nan::Set(target, Nan::New("setLightingForTargetZone").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLightingForTargetZone)).ToLocalChecked());
  Nan::Set(target, Nan::New("saveCurrentLighting").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SaveCurrentLighting)).ToLocalChecked());
  Nan::Set(target, Nan::New("setLighting").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLighting)).ToLocalChecked());
  Nan::Set(target, Nan::New("restoreLighting").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(RestoreLighting)).ToLocalChecked());
  Nan::Set(target, Nan::New("flashLighting").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(FlashLighting)).ToLocalChecked());
  Nan::Set(target, Nan::New("pulseLighting").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(PulseLighting)).ToLocalChecked());
  Nan::Set(target, Nan::New("stopEffects").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(StopEffects)).ToLocalChecked());

  Nan::Set(target, Nan::New("setLightingFromBitmap").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLightingFromBitmap)).ToLocalChecked());
  Nan::Set(target, Nan::New("excludeKeysFromBitmap").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(ExcludeKeysFromBitmap)).ToLocalChecked());

  Nan::Set(target, Nan::New("setLightingForKeyWithKeyName").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLightingForKeyWithKeyName)).ToLocalChecked());
  Nan::Set(target, Nan::New("setLightingForKeyWithScanCode").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLightingForKeyWithScanCode)).ToLocalChecked());
  Nan::Set(target, Nan::New("setLightingForKeyWithQuartzCode").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SetLightingForKeyWithQuartzCode)).ToLocalChecked());

  Nan::Set(target, Nan::New("saveLightingForKey").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(SaveLightingForKey)).ToLocalChecked());
  Nan::Set(target, Nan::New("flashSingleKey").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(FlashSingleKey)).ToLocalChecked());
  Nan::Set(target, Nan::New("pulseSingleKey").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(PulseSingleKey)).ToLocalChecked());
  Nan::Set(target, Nan::New("restoreLightingForKey").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(RestoreLightingForKey)).ToLocalChecked());

  Nan::Set(target, Nan::New("stopEffectsOnKey").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(StopEffectsOnKey)).ToLocalChecked());

  Nan::Set(target, Nan::New("shutdown").ToLocalChecked(),
    Nan::GetFunction(Nan::New<FunctionTemplate>(Shutdown)).ToLocalChecked());

}

NODE_MODULE(logiled, InitAll)


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.7-5-b-62
description: >
    Object.defineProperties - 'configurable' property of 'descObj' is
    inherited data property (8.10.5 step 4.a)
---*/

        var obj = {};
        var proto = {
            configurable: true
        };
        var Con = function () { };
        Con.prototype = proto;
        var descObj = new Con();

        Object.defineProperties(obj, {
            prop: descObj
        });

        var result1 = obj.hasOwnProperty("prop");
        delete obj.prop;
        var result2 = obj.hasOwnProperty("prop");

assert.sameValue(result1, true, 'result1');
assert.sameValue(result2, false, 'result2');


text:
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.IOException;

class Solution
{
	static boolean move(int [] arr, int pos,int m)
	{
		int a = pos-1;
		if(a<0)
			a=0;
		int b = pos+1;
		int c = pos+m;
		arr[pos]=1;
		if(b>=arr.length || c>=arr.length)
			return true;
		if(arr[a]==0)
			if(Solution.move(arr,a,m))
				return true;
		if(arr[b]==0)
			if(Solution.move(arr,b,m))
				return true;
		if(arr[c]==0)
			if(Solution.move(arr,c,m))
				return true;
		return false;

	}
	public static void main(String ... ags)throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(in.readLine());
		for(int i=0;i<n;i++)
		{
			StringTokenizer tk = new StringTokenizer(in.readLine());
			int len = Integer.parseInt(tk.nextToken());
			int m = Integer.parseInt(tk.nextToken());
			int [] arr = new int [len];
			tk = new StringTokenizer(in.readLine());
			for(int j=0 ;j<len;j++)
			{
				arr[j] = Integer.parseInt(tk.nextToken());
			}
			if(Solution.move(arr,0,m))
				System.out.println("YES");
			else
				System.out.println("NO");
		}
	}
}


text:
CBIX-PHP
========

[![Build Status](https://travis-ci.org/Digital-Currency-Research/CBIX-PHP.svg)](https://travis-ci.org/Digital-Currency-Research/CBIX-PHP)
[![Code Climate](https://codeclimate.com/github/Digital-Currency-Research/CBIX-PHP/badges/gpa.svg)](https://codeclimate.com/github/Digital-Currency-Research/CBIX-PHP)
[![Test Coverage](https://codeclimate.com/github/Digital-Currency-Research/CBIX-PHP/badges/coverage.svg)](https://codeclimate.com/github/Digital-Currency-Research/CBIX-PHP)

This library provides a simple PHP interface to the [Canadian Bitcoin Index API](https://www.cbix.ca/api).

### Installing via Composer

The recommended way to install the library is through [Composer](http://getcomposer.org).

```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php

# Add Chain-PHP as a dependency
php composer.phar require cbix/cbix-php:dev-master
```

After installing, you need to require Composer's autoloader:

```php
require 'vendor/autoload.php';
```

### Setup

Simply call the make method on the Cbix class.

    $cbix = Cbix::make();

### Methods

All methods of the [CBIX API](https://www.cbix.ca/api) are supported and more will be added when fully supported.

    $index = $cbix->index();
    $history = $cbix->history(['limit=100']);
    $convert = $cbix->convert(500, 'CAD', 'BTC');
    $news = $cbix->news();
    $summary = $cbix->summary();
    $orderbook = $cbix->orderbook(['limit=25']);
    $volatility = $cbix->volatility(['limit=10']);

## Exceptions

If there are any issues during the API request a CbixException will be thrown which can be caught
and managed according to your application needs.

    try {
        $index = $cbix->index();
        echo $index->index->value;
    } catch (CbixException $e) {
        //There was an error more information in $e->getMessage();
        var_dump($e->getMessage());
    }

## Unit Tests

This library uses PHPUnit for unit testing. In order to run the unit tests, you'll first need
to install the dependencies of the project using Composer: `php composer.phar install --dev`.
You can then run the tests using `vendor/bin/phpunit`. The library comes with a set of mocked responses
from the CBIX API for running the unit tests.

## Contributions

Patches, bug fixes, feature requests, and pull requests are welcome.


text:
javascript-utility-library
==========================

javascript utility library

toDo:
* избавиться от underscore
* придумать namespace
* переписать loadScript && loadRaw
* англоязычные комменты


text:
define(['knockout'], function(ko) {
    'use strict';

    ko.bindingHandlers.executeOnEnter = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var allBindings = allBindingsAccessor();
            $(element).keypress(function (event) {
                var keyCode = (event.which ? event.which : event.keyCode);
                if (keyCode === 13) {
                    allBindings.executeOnEnter.call(viewModel);
                    return false;
                }
                return true;
            });
        }
    };
});


text:
/**
 * @module EnumerableOperation
 */ /** */

import { invalidArgumentsCheck } from '../../../../utilities/utilities.index';
import { BooleanExpression } from '../../../expressions/expressions.index';
import { IEnumerable } from '../enumerable.index';

export function count<T>(source: IEnumerable<T>, predicate: BooleanExpression<T> = (element: T) => true): number {
    invalidArgumentsCheck(arguments, 1);

    const enumerator = source.getEnumerator();
    let elementCount = 0;

    while (enumerator.moveNext()) {
        if (predicate(enumerator.current)) {
            elementCount++;
        }
    }

    return elementCount;
}


text:
package org.jnosql.diana.hbase.column;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
import org.jnosql.diana.api.column.Column;
import org.jnosql.diana.api.column.ColumnEntity;

import java.util.ArrayList;
import java.util.List;

import static org.apache.hadoop.hbase.CellUtil.cloneFamily;
import static org.apache.hadoop.hbase.CellUtil.cloneQualifier;
import static org.apache.hadoop.hbase.CellUtil.cloneRow;
import static org.apache.hadoop.hbase.CellUtil.cloneValue;
import static org.jnosql.diana.hbase.column.HBaseUtils.getKey;

class EntityUnit {

    private String rowKey;

    private String columnFamily;

    private final List<Column> columns = new ArrayList<>();

    EntityUnit(Result result) {

        for (Cell cell : result.rawCells()) {

            String name = new String(cloneQualifier(cell));
            String value = new String(cloneValue(cell));
            if (this.rowKey == null) {
                this.rowKey = new String(cloneRow(cell));
            }
            if (this.columnFamily == null) {
                this.columnFamily = new String(cloneFamily(cell));
            }
            columns.add(Column.of(name, value));
        }
    }

    public boolean isNotEmpty() {
        return !columns.isEmpty();
    }

    public ColumnEntity toEntity() {
        ColumnEntity entity = ColumnEntity.of(columnFamily);
        entity.addAll(columns);
        entity.add(getKey(rowKey));
        return entity;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("EntityUnit{");
        sb.append("rowKey='").append(rowKey).append('\'');
        sb.append(", columnFamily='").append(columnFamily).append('\'');
        sb.append(", columns=").append(columns);
        sb.append('}');
        return sb.toString();
    }
}


text:
using BulletML.Nodes;
using System.Diagnostics;

namespace BulletML.Tasks
{
    /// <summary>
    /// This action sets the velocity of a bullet
    /// </summary>
    public class SpeedTask : BulletMLTask
    {
        #region Methods

        /// <summary>
        /// Initializes a new instance of the <see cref="BulletMLTask"/> class.
        /// </summary>
        /// <param name="node">Node.</param>
        /// <param name="owner">Owner.</param>
        public SpeedTask(SpeedNode node, BulletMLTask owner) : base(node, owner)
        {
            Debug.Assert(null != Node);
            Debug.Assert(null != Owner);
        }

        #endregion Methods
    }
}


text:
<?php

namespace Manhattan\PorterStemmerBundle\Tests\Component;

use Manhattan\PorterStemmerBundle\Component\AnnotationParser;

/**
 * AnnotationParserTest
 *
 * @author James Rickard <james@frodosghost.com>
 */
class AnnotationParserTest extends \PHPUnit_Framework_TestCase
{
    private $annotationReader;

    public function setUp()
    {
        $this->annotationReader = $this->getMock('Doctrine\Common\Annotations\AnnotationReader');
    }

    /**
     * @covers Manhattan\PorterStemmerBundle\Component\AnnotationParser::__construct
     */
    public function testConstruct()
    {
        $annotationParser = new AnnotationParser($this->annotationReader);

        $this->assertInstanceOf('Manhattan\PorterStemmerBundle\Component\AnnotationParser', $annotationParser);
    }

    public function testIncorrectConfigureMetadata()
    {
        $annotationParser = new AnnotationParser($this->annotationReader);

        $this->setExpectedException('\Exception');
        $annotationParser->configureMetadata(null);
    }

    public function testIncompleteConfigureMetadata()
    {
        $annotationParser = new AnnotationParser($this->annotationReader);

        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')
            ->disableOriginalConstructor()
            ->getMock();

        $this->setExpectedException('\Manhattan\PorterStemmerBundle\Exception\ConfigurationException');
        $annotationParser->configureMetadata($classMetadata);
    }

    public function testConfigureMetadata()
    {
        $annotationParser = new AnnotationParser($this->annotationReader);
        $test = $this;

        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')
            ->disableOriginalConstructor()
            ->getMock();

        $classMetadata->expects($this->any())
            ->method('getReflectionClass')
            ->will($this->returnCallback(function () use ($test) {
                return $test->getMockBuilder('ReflectionClass')
                        ->disableOriginalConstructor()
                        ->getMock();
            }));

        $this->assertInstanceOf('Manhattan\PorterStemmerBundle\Component\AnnotationParser', $annotationParser->configureMetadata($classMetadata));
    }

}


text:
namespace Akumuli {
namespace QP {

// -----
// Absolute
// -----

Absolute::Absolute(std::shared_ptr<Node> next)
    : next_(next)
{
}

Absolute::Absolute(const boost::property_tree::ptree&, ReshapeRequest const&, std::shared_ptr<Node> next)
    : next_(next)
{
}

void Absolute::complete() {
    next_->complete();
}

bool Absolute::put(MutableSample &mut) {
    auto size = mut.size();
    for (u32 ix = 0; ix < size; ix++) {
        double* value = mut[ix];
        if (value) {
            *value = std::abs(*value);
        }
    }
    return next_->put(mut);
}

void Absolute::set_error(aku_Status status) {
    next_->set_error(status);
}

int Absolute::get_requirements() const {
    return TERMINAL;
}

static QueryParserToken<Absolute> token("abs");

}}  // namespace


text:
'use strict';

angular.module('myApp.register',['ngRoute', 'firebase'])

//Declare route
.config(['$routeProvider', function($routeProvider){
	$routeProvider.when('/register', {
		templateUrl: 'register/register.html',
		controller: 'RegisterCtrl'
	});
}])

// Register Controller

.controller('RegisterCtrl', ['$scope', '$location', '$firebaseAuth', function($scope, $location, $firebaseAuth){

	var firebaseObj = new Firebase("https://blazing-heat-8641.firebaseio.com");
	var auth = $firebaseAuth(firebaseObj);

	$scope.signUp = function(){

	var login={};
	$scope.login=login;
	login.loading = true;

		if(!$scope.regForm.$invalid){

		var email = $scope.user.email;
 		var password = $scope.user.password;

			if (email && password) {
				auth.$createUser({email, password})
					.then(function() {
  						console.log("Successfully created user account");
  						login.loading  = false;
    					$location.path('/home');
    				}, function(error){
    					console.log("Error creating user:", error);
    					$scope.regError = true;
    					$scope.regErrorMessage = error.message;
    					login.loading  = false;
  					});
  			}
  		}

	};

}]);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. helv. 11(2): 131 (2001)

#### Original name
Pluteus albineus Bonnard

### Remarks
null


text:
<?php

namespace Kendo\Dataviz\UI;

class MapLayerDefaults extends \Kendo\SerializableObject {
//>> Properties

    /**
    * The default configuration for marker layers.
    * @param \Kendo\Dataviz\UI\MapLayerDefaultsMarker|array $value
    * @return \Kendo\Dataviz\UI\MapLayerDefaults
    */
    public function marker($value) {
        return $this->setProperty('marker', $value);
    }

    /**
    * The default configuration for shape layers.
    * @param \Kendo\Dataviz\UI\MapLayerDefaultsShape|array $value
    * @return \Kendo\Dataviz\UI\MapLayerDefaults
    */
    public function shape($value) {
        return $this->setProperty('shape', $value);
    }

    /**
    * The default configuration for bubble layers.
    * @param \Kendo\Dataviz\UI\MapLayerDefaultsBubble|array $value
    * @return \Kendo\Dataviz\UI\MapLayerDefaults
    */
    public function bubble($value) {
        return $this->setProperty('bubble', $value);
    }

    /**
    * The default configuration for tile layers.
    * @param \Kendo\Dataviz\UI\MapLayerDefaultsTile|array $value
    * @return \Kendo\Dataviz\UI\MapLayerDefaults
    */
    public function tile($value) {
        return $this->setProperty('tile', $value);
    }

    /**
    * The default configuration for Bing (tm) tile layers.
    * @param \Kendo\Dataviz\UI\MapLayerDefaultsBing|array $value
    * @return \Kendo\Dataviz\UI\MapLayerDefaults
    */
    public function bing($value) {
        return $this->setProperty('bing', $value);
    }

//<< Properties
}

?>


text:
require('./harness').run();

var recvCount = 0;
var body = "hello world";

connection.addListener('ready', function () {
  puts("connected to " + connection.serverProperties.product);

  var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
  var q = connection.queue('node-123ack-queue', function() {
    q.bind(e, 'ackmessage.*');
    q.on('queueBindOk', function() {
      q.on('basicConsumeOk', function () {
        puts("publishing 2 json messages");

        e.publish('ackmessage.json1', { name: 'A' });
        e.publish('ackmessage.json2', { name: 'B' });
        e.publish('ackmessage.json3', { name: 'C' });
      });

      q.subscribe({ ack: true }, function (json) {
        recvCount++;
        puts('Got message ' + JSON.stringify(json));

        if (recvCount == 1) {
          puts('Got message 1.. waiting');
          assert.equal('A', json.name);
          setTimeout(function () {
            puts('shift!');
            q.shift();
          }, 1000);
        } else if (recvCount == 2) {
          puts('got message 2');
          assert.equal('B', json.name);
          setTimeout(function () {
            puts('reject!');
            q.shift(true);
          }, 1000);
        } else if (recvCount == 3) {
          puts('got message 3');
          assert.equal('C', json.name);
          setTimeout(function () {
            puts('requeue!');
            q.shift(true, true);
          }, 1000);
        } else if (recvCount == 4) {
          puts('got message 4');
          assert.equal('C', json.name);

          puts('closing connection');

          connection.end();
        } else {
          throw new Error('Too many message!');
        }
      });
    });
  });
});

process.addListener('exit', function () {
  assert.equal(4, recvCount);
});


text:
<?php

class BattleNetAPI_Wow_Challenge_Endpoint extends BattleNetAPI_Endpoint {
	function __construct( $params ) {
		$this->url = BattleNetAPI::getHost() . '/wow/challenge/region';
	}
}


text:
#if !defined(BOOST_SPIRIT_X3_SKIP_APRIL_16_2006_0625PM)
#define BOOST_SPIRIT_X3_SKIP_APRIL_16_2006_0625PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/x3/support/unused.hpp>
#include <boost/spirit/home/x3/support/context.hpp>
#include <boost/spirit/home/x3/support/traits/attribute_category.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/not.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/utility/declval.hpp>

namespace boost { namespace spirit { namespace x3
{
    ///////////////////////////////////////////////////////////////////////////
    // Move the /first/ iterator to the first non-matching position
    // given a skip-parser. The function is a no-op if unused_type or
    // unused_skipper is passed as the skip-parser.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Skipper>
    struct unused_skipper : unused_type
    {
        unused_skipper(Skipper const& skipper)
          : skipper(skipper) {}
        Skipper const& skipper;
    };

    namespace detail
    {
        template <typename Skipper>
        struct is_unused_skipper
          : mpl::false_ {};

        template <typename Skipper>
        struct is_unused_skipper<unused_skipper<Skipper>>
          : mpl::true_ {};

        template <>
        struct is_unused_skipper<unused_type>
          : mpl::true_ {};

        template <typename Skipper>
        inline Skipper const&
        get_unused_skipper(Skipper const& skipper)
        {
            return skipper;
        }
        template <typename Skipper>
        inline Skipper const&
        get_unused_skipper(unused_skipper<Skipper> const& unused_skipper)
        {
            return unused_skipper.skipper;
        }

        template <typename Iterator, typename Skipper>
        inline void skip_over(
            Iterator& first, Iterator const& last, Skipper const& skipper)
        {
            while (first != last && skipper.parse(first, last, unused, unused, unused))
                /***/;
        }

        template <typename Iterator>
        inline void skip_over(Iterator&, Iterator const&, unused_type)
        {
        }

        template <typename Iterator, typename Skipper>
        inline void skip_over(
            Iterator&, Iterator const&, unused_skipper<Skipper> const&)
        {
        }
    }

    // this tag is used to find the skipper from the context
    struct skipper_tag;

    template <typename Context>
    struct has_skipper
      : mpl::not_<detail::is_unused_skipper<
            typename remove_cv<typename remove_reference<
                decltype(x3::get<skipper_tag>(boost::declval<Context>()))
            >::type>::type
        >> {};

    template <typename Iterator, typename Context>
    inline void skip_over(
        Iterator& first, Iterator const& last, Context const& context)
    {
        detail::skip_over(first, last, x3::get<skipper_tag>(context));
    }
}}}

#endif


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Search — Flask AppBuilder</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.3.4/flatly/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="Flask AppBuilder" href="index.html" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Flask-AppBuilder
        1.4.4

Diagrams

  Site

Introduction

Installation

Command Line Manager

Base Configuration

Base Views

Model Views (Quick How to)

Model Views on MongoDB

Chart Views

Model Views with Files and Images

Quick Minimal Application

Model Relations

Actions

Advanced Configuration

Customizing

Templates

Generic Data Sources

Multiple Databases

i18n Translations

Security

User Registration

API Reference

Version Migration

Versions

  Page

Search

    Please activate JavaScript to enable the search
    functionality.

    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.

  <form class="form-inline" action="" method="get">

      <input type="text" class="form-control" name="q" value="" />

    <input type="submit" class="btn btn-default" value="search" />

  </form>

      Back to top

        © Copyright 2013, Daniel Vaz Gaspar.

      Created using Sphinx 1.3.1.


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GeoAPI.Geometries;
using NetTopologySuite.Algorithm;

namespace DotSpatial.Data
{
    /// <summary>
    /// A shapefile class that handles the special case where the data is made up of polygons
    /// </summary>
    public class PolygonShapefile : Shapefile
    {
        /// <summary>
        /// Creates a new instance of a PolygonShapefile for in-ram handling only.
        /// </summary>
        public PolygonShapefile()
            : base(FeatureType.Polygon, ShapeType.Polygon) { }

        /// <summary>
        /// Creates a new instance of a PolygonShapefile that is loaded from the supplied fileName.
        /// </summary>
        /// <param name="fileName">The string fileName of the polygon shapefile to load</param>
        public PolygonShapefile(string fileName)
            : this()
        {
            Open(fileName, null);
        }

        /// <summary>
        /// Opens a shapefile.
        /// </summary>
        /// <param name="fileName">The string fileName of the polygon shapefile to load.</param>
        /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
        public void Open(string fileName, IProgressHandler progressHandler)
        {
            if (!File.Exists(fileName)) return;

            Filename = fileName;
            IndexMode = true;
            Header = new ShapefileHeader(Filename);

            switch (Header.ShapeType)
            {
                case ShapeType.PolygonM:
                    CoordinateType = CoordinateType.M;
                    break;
                case ShapeType.PolygonZ:
                    CoordinateType = CoordinateType.Z;
                    break;
                default:
                    CoordinateType = CoordinateType.Regular;
                    break;
            }

            Extent = Header.ToExtent();
            Name = Path.GetFileNameWithoutExtension(fileName);
            Attributes.Open(Filename);

            LineShapefile.FillLines(Filename, progressHandler, this, FeatureType.Polygon);
            ReadProjection();
        }

        // X Y Poly Lines: Total Length = 28 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 3        Integer     1           Little
        // Byte 12      Xmin                Double      1           Little
        // Byte 20      Ymin                Double      1           Little
        // Byte 28      Xmax                Double      1           Little
        // Byte 36      Ymax                Double      1           Little
        // Byte 44      NumParts            Integer     1           Little
        // Byte 48      NumPoints           Integer     1           Little
        // Byte 52      Parts               Integer     NumParts    Little
        // Byte X       Points              Point       NumPoints   Little
        // X = 52 + 4 * NumParts

        // X Y M Poly Lines: Total Length = 34 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 23       Integer     1           Little
        // Byte 12      Box                 Double      4           Little
        // Byte 44      NumParts            Integer     1           Little
        // Byte 48      NumPoints           Integer     1           Little
        // Byte 52      Parts               Integer     NumParts    Little
        // Byte X       Points              Point       NumPoints   Little
        // Byte Y*      Mmin                Double      1           Little
        // Byte Y + 8*  Mmax                Double      1           Little
        // Byte Y + 16* Marray              Double      NumPoints   Little
        // X = 52 + (4 * NumParts)
        // Y = X + (16 * NumPoints)
        // * = optional

        // X Y Z M Poly Lines: Total Length = 44 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number  Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 13       Integer     1           Little
        // Byte 12      Box                 Double      4           Little
        // Byte 44      NumParts            Integer     1           Little
        // Byte 48      NumPoints           Integer     1           Little
        // Byte 52      Parts               Integer     NumParts    Little
        // Byte X       Points              Point       NumPoints   Little
        // Byte Y       Zmin                Double      1           Little
        // Byte Y + 8   Zmax                Double      1           Little
        // Byte Y + 16  Zarray              Double      NumPoints   Little
        // Byte Z*      Mmin                Double      1           Little
        // Byte Z+8*    Mmax                Double      1           Little
        // Byte Z+16*   Marray              Double      NumPoints   Little
        // X = 52 + (4 * NumParts)
        // Y = X + (16 * NumPoints)
        // Z = Y + 16 + (8 * NumPoints)
        // * = optional

        /// <summary>
        /// Gets the specified feature by constructing it from the vertices, rather
        /// than requiring that all the features be created. (which takes up a lot of memory).
        /// </summary>
        /// <param name="index">The integer index</param>
        public override IFeature GetFeature(int index)
        {
            IFeature f;
            if (!IndexMode)
            {
                f = Features[index];
            }
            else
            {
                f = GetPolygon(index);
                f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0];
            }
            return f;
        }

        /// <inheritdoc />
        protected override void SetHeaderShapeType()
        {
            if (CoordinateType == CoordinateType.Regular)
                Header.ShapeType = ShapeType.Polygon;
            else if (CoordinateType == CoordinateType.M)
                Header.ShapeType = ShapeType.PolygonM;
            else if (CoordinateType == CoordinateType.Z)
                Header.ShapeType = ShapeType.PolygonZ;
        }

        /// <inheritdoc />
        protected override StreamLengthPair PopulateShpAndShxStreams(Stream shpStream, Stream shxStream, bool indexed)
        {
            if (indexed)
                return LineShapefile.PopulateStreamsIndexed(shpStream, shxStream, this, ShapeType.PolygonZ, ShapeType.PolygonM, true);

            return LineShapefile.PopulateStreamsNotIndexed(shpStream, shxStream, this, AddPoints, ShapeType.PolygonZ, ShapeType.PolygonM, true);
        }

        /// <summary>
        /// Adds the parts and points of the given feature to the given parts and points lists.
        /// </summary>
        /// <param name="parts">List of parts, where the features parts get added.</param>
        /// <param name="points">List of points, where the features points get added.</param>
        /// <param name="f">Feature, whose parts and points get added to the lists.</param>
        private static void AddPoints(List<int> parts, List<Coordinate> points, IFeature f)
        {
            for (int iPart = 0; iPart < f.Geometry.NumGeometries; iPart++)
            {
                parts.Add(points.Count);
                IPolygon pg = f.Geometry.GetGeometryN(iPart) as IPolygon;
                if (pg == null) continue;

                ILineString bl = pg.Shell;

                // Exterior rings need to be clockwise
                IEnumerable<Coordinate> coords = CGAlgorithms.IsCCW(bl.Coordinates) ? bl.Coordinates.Reverse() : bl.Coordinates;
                points.AddRange(coords);

                foreach (var hole in pg.Holes)
                {
                    parts.Add(points.Count);

                    // Interior rings need to be counter-clockwise
                    IEnumerable<Coordinate> holeCoords = CGAlgorithms.IsCCW(hole.Coordinates) ? hole.Coordinates : hole.Coordinates.Reverse();
                    points.AddRange(holeCoords);
                }
            }
        }

    }
}


text:
/**
 *
 */
package com.marcestarlet.booksearcher.rest.model.dao;

import java.io.Serializable;
import java.util.List;

/**
 * DAO defines how the Data Access will be
 * @author MarceStarlet
 *
 * mongodb-basics
 */
public interface DAO <D extends Serializable>{

	/**
	 * Creates a new entity into the data store
	 * @param e Entity to be created
	 */
	public void create( D e );

	/**
	 * Updates an existent entity into the data store
	 * @param e Entity to be updated
	 */
	public void update( D e );

	/**
	 * Deletes an existent entity from the data store
	 * @param id ID of the entity to be deleted
	 */
	public void delete( final String id );

	/**
	 * Finds an entity by the ID
	 * @param id ID of the entity
	 * @return Entity found
	 */
	public D findById( final String id );

	/**
	 * Finds all the entities from the data store
	 * @return All the existent entities
	 */
	public List<D> findAll();

	/**
	 * Finds all the corresponding entities that matches the
	 * filters passed through
	 * @param filters Array of filters
	 * @return All the entities that matched
	 */
	public List<D> findByFilters( String filter );
}


text:
package typev3

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"sort"
	"strings"
	"time"
	"unicode/utf8"

	"google.golang.org/protobuf/types/known/anypb"
)

// ensure the imports are used
var (
	_ = bytes.MinRead
	_ = errors.New("")
	_ = fmt.Print
	_ = utf8.UTFMax
	_ = (*regexp.Regexp)(nil)
	_ = (*strings.Reader)(nil)
	_ = net.IPv4len
	_ = time.Duration(0)
	_ = (*url.URL)(nil)
	_ = (*mail.Address)(nil)
	_ = anypb.Any{}
	_ = sort.Sort
)

// Validate checks the field values on Percent with the rules defined in the
// proto definition for this message. If any rules are violated, the first
// error encountered is returned, or nil if there are no violations.
func (m *Percent) Validate() error {
	return m.validate(false)
}

// ValidateAll checks the field values on Percent with the rules defined in the
// proto definition for this message. If any rules are violated, the result is
// a list of violation errors wrapped in PercentMultiError, or nil if none found.
func (m *Percent) ValidateAll() error {
	return m.validate(true)
}

func (m *Percent) validate(all bool) error {
	if m == nil {
		return nil
	}

	var errors []error

	if val := m.GetValue(); val < 0 || val > 100 {
		err := PercentValidationError{
			field:  "Value",
			reason: "value must be inside range [0, 100]",
		}
		if !all {
			return err
		}
		errors = append(errors, err)
	}

	if len(errors) > 0 {
		return PercentMultiError(errors)
	}

	return nil
}

// PercentMultiError is an error wrapping multiple validation errors returned
// by Percent.ValidateAll() if the designated constraints aren't met.
type PercentMultiError []error

// Error returns a concatenation of all the error messages it wraps.
func (m PercentMultiError) Error() string {
	var msgs []string
	for _, err := range m {
		msgs = append(msgs, err.Error())
	}
	return strings.Join(msgs, "; ")
}

// AllErrors returns a list of validation violation errors.
func (m PercentMultiError) AllErrors() []error { return m }

// PercentValidationError is the validation error returned by Percent.Validate
// if the designated constraints aren't met.
type PercentValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e PercentValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e PercentValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e PercentValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e PercentValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e PercentValidationError) ErrorName() string { return "PercentValidationError" }

// Error satisfies the builtin error interface
func (e PercentValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sPercent.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = PercentValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = PercentValidationError{}

// Validate checks the field values on FractionalPercent with the rules defined
// in the proto definition for this message. If any rules are violated, the
// first error encountered is returned, or nil if there are no violations.
func (m *FractionalPercent) Validate() error {
	return m.validate(false)
}

// ValidateAll checks the field values on FractionalPercent with the rules
// defined in the proto definition for this message. If any rules are
// violated, the result is a list of violation errors wrapped in
// FractionalPercentMultiError, or nil if none found.
func (m *FractionalPercent) ValidateAll() error {
	return m.validate(true)
}

func (m *FractionalPercent) validate(all bool) error {
	if m == nil {
		return nil
	}

	var errors []error

	// no validation rules for Numerator

	if _, ok := FractionalPercent_DenominatorType_name[int32(m.GetDenominator())]; !ok {
		err := FractionalPercentValidationError{
			field:  "Denominator",
			reason: "value must be one of the defined enum values",
		}
		if !all {
			return err
		}
		errors = append(errors, err)
	}

	if len(errors) > 0 {
		return FractionalPercentMultiError(errors)
	}

	return nil
}

// FractionalPercentMultiError is an error wrapping multiple validation errors
// returned by FractionalPercent.ValidateAll() if the designated constraints
// aren't met.
type FractionalPercentMultiError []error

// Error returns a concatenation of all the error messages it wraps.
func (m FractionalPercentMultiError) Error() string {
	var msgs []string
	for _, err := range m {
		msgs = append(msgs, err.Error())
	}
	return strings.Join(msgs, "; ")
}

// AllErrors returns a list of validation violation errors.
func (m FractionalPercentMultiError) AllErrors() []error { return m }

// FractionalPercentValidationError is the validation error returned by
// FractionalPercent.Validate if the designated constraints aren't met.
type FractionalPercentValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e FractionalPercentValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e FractionalPercentValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e FractionalPercentValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e FractionalPercentValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e FractionalPercentValidationError) ErrorName() string {
	return "FractionalPercentValidationError"
}

// Error satisfies the builtin error interface
func (e FractionalPercentValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sFractionalPercent.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = FractionalPercentValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = FractionalPercentValidationError{}


text:
#include "gradients.h"

#include <QApplication>

int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(gradients);

    QApplication app(argc, argv);

    GradientWidget gradientWidget(0);
    QStyle *arthurStyle = new ArthurStyle();
    gradientWidget.setStyle(arthurStyle);
    QList<QWidget *> widgets = gradientWidget.findChildren<QWidget *>();
    foreach (QWidget *w, widgets) {
        w->setStyle(arthurStyle);
        w->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    gradientWidget.show();

    return app.exec();
}


text:
/*
 *  SDL_RWops support for python objects
 */
#define NO_PYGAME_C_API
#define PYGAMEAPI_RWOBJECT_INTERNAL
#include "pygame.h"
#include "pgcompat.h"
#include "doc/pygame_doc.h"

/* With Python 2.5 exception types became new-style classes and
 * PyExc_BaseException was introduced.
 */
#if PY_VERSION_HEX < 0x02050000
#define ExcClassType_Check(o) PyClass_Check(o)
#define PyExc_BaseException PyExc_Exception
#else
#define ExcClassType_Check(o) PyType_Check(o)
#endif

typedef struct
{
    PyObject* read;
    PyObject* write;
    PyObject* seek;
    PyObject* tell;
    PyObject* close;
} RWHelper;

/*static const char default_encoding[] = "unicode_escape";*/
/*static const char default_errors[] = "backslashreplace";*/
static const char default_encoding[] = "unicode_escape";
static const char default_errors[] = "backslashreplace";

static int rw_seek (SDL_RWops* context, int offset, int whence);
static int rw_read (SDL_RWops* context, void* ptr, int size, int maxnum);
static int rw_write (SDL_RWops* context, const void* ptr, int size, int maxnum);
static int rw_close (SDL_RWops* context);

#ifdef WITH_THREAD
static int rw_seek_th (SDL_RWops* context, int offset, int whence);
static int rw_read_th (SDL_RWops* context, void* ptr, int size, int maxnum);
static int rw_write_th (SDL_RWops* context, const void* ptr, int size,
                        int maxnum);
static int rw_close_th (SDL_RWops* context);
#endif

static int
is_exception_class(PyObject *obj, void **optr)
{
    PyObject **rval = (PyObject **)optr;
    PyObject *oname;
#if PY3
    PyObject *tmp;
#endif

    if (!ExcClassType_Check(obj) || /* conditional or */
        !PyObject_IsSubclass(obj, PyExc_BaseException)) {
        oname = PyObject_Str(obj);
        if (oname == NULL) {
            return 0;
        }
#if PY3
        tmp = PyUnicode_AsEncodedString(oname, "ascii", "replace");
        Py_DECREF(tmp);
        if (tmp == NULL) {
            return 0;
        }
        oname = tmp;
#endif
        PyErr_Format(PyExc_TypeError,
                     "Expected an exception class: got %.1024s",
                     Bytes_AS_STRING(oname));
        Py_DECREF(oname);
        return 0;
    }
    *rval = obj;
    return 1;
}

static void
fetch_object_methods (RWHelper* helper, PyObject* obj)
{
    helper->read = helper->write = helper->seek = helper->tell =
        helper->close = NULL;

    if (PyObject_HasAttrString (obj, "read"))
    {
        helper->read = PyObject_GetAttrString (obj, "read");
        if(helper->read && !PyCallable_Check (helper->read))
        {
            Py_DECREF (helper->read);
            helper->read = NULL;
        }
    }
    if (PyObject_HasAttrString (obj, "write"))
    {
        helper->write = PyObject_GetAttrString (obj, "write");
        if (helper->write && !PyCallable_Check (helper->write))
        {
            Py_DECREF (helper->write);
            helper->write = NULL;
        }
    }
    if (PyObject_HasAttrString (obj, "seek"))
    {
        helper->seek = PyObject_GetAttrString (obj, "seek");
        if (helper->seek && !PyCallable_Check (helper->seek))
        {
            Py_DECREF (helper->seek);
            helper->seek = NULL;
        }
    }
    if (PyObject_HasAttrString (obj, "tell"))
    {
        helper->tell = PyObject_GetAttrString (obj, "tell");
        if (helper->tell && !PyCallable_Check (helper->tell))
        {
            Py_DECREF (helper->tell);
            helper->tell = NULL;
        }
    }
    if(PyObject_HasAttrString(obj, "close"))
    {
        helper->close = PyObject_GetAttrString (obj, "close");
        if (helper->close && !PyCallable_Check (helper->close))
        {
            Py_DECREF (helper->close);
            helper->close = NULL;
        }
    }
}

static PyObject*
RWopsEncodeString(PyObject *obj,
                  const char *encoding,
                  const char *errors,
                  PyObject *eclass)
{
    PyObject *oencoded;
    PyObject *exc_type;
    PyObject *exc_value;
    PyObject *exc_trace;
    PyObject *str;

    if (obj == NULL) {
        /* Assume an error was raise; forward it */
        return NULL;
    }
    if (encoding == NULL) {
        encoding = default_encoding;
    }
    if (errors == NULL) {
        errors = default_errors;
    }
    if (PyUnicode_Check(obj)) {
        oencoded = PyUnicode_AsEncodedString(obj, encoding, errors);
        if (oencoded != NULL) {
            return oencoded;
        }
        else if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
            /* Forward memory errors */
            return NULL;
        }
        else if (eclass != NULL) {
            /* Foward as eclass error */
            PyErr_Fetch(&exc_type, &exc_value, &exc_trace);
            Py_DECREF(exc_type);
            Py_XDECREF(exc_trace);
            if (exc_value == NULL) {
                PyErr_SetString(eclass,
                                "Unicode encoding error");
            }
            else {
                str = PyObject_Str(exc_value);
                Py_DECREF(exc_value);
                if (str != NULL) {
                    PyErr_SetObject(eclass, str);
                    Py_DECREF(str);
                }
            }
            return NULL;
        }
        else if (encoding == default_encoding && errors == default_errors) {
            /* The default encoding and error handling should not fail */
            return RAISE(PyExc_SystemError,
                         "Pygame bug (in RWopsEncodeString):"
                         " unexpected encoding error");
        }
        PyErr_Clear();
    }
    else if (Bytes_Check(obj)) {
        Py_INCREF(obj);
        return obj;
    }

    Py_RETURN_NONE;
}

static PyObject*
RWopsEncodeFilePath(PyObject *obj, PyObject *eclass)
{
    PyObject *result = RWopsEncodeString(obj,
                                         UNICODE_DEF_FS_CODEC,
                                         UNICODE_DEF_FS_ERROR,
                                         eclass);
    if (result == NULL || result == Py_None) {
        return result;
    }
    if ((size_t)Bytes_GET_SIZE(result) != strlen(Bytes_AS_STRING(result))) {
        if (eclass != NULL) {
            Py_DECREF(result);
            result = RWopsEncodeString(obj, NULL, NULL, NULL);
            if (result == NULL) {
                return NULL;
            }
            PyErr_Format(eclass,
                         "File path '%.1024s' contains null characters",
                         Bytes_AS_STRING(result));
            Py_DECREF(result);
            return NULL;
        }
        Py_DECREF(result);
        Py_RETURN_NONE;
    }
    return result;
}

static SDL_RWops*
RWopsFromFileObject(PyObject *obj)
{
    SDL_RWops *rw = NULL;
    RWHelper *helper;

    if (obj == NULL) {
        return (SDL_RWops *)RAISE(PyExc_TypeError, "Invalid filetype object");
    }
#if PY2
    if (PyFile_Check(obj))
    {
        rw = SDL_RWFromFP(PyFile_AsFile(obj), 0);
        if (rw) {
            return rw;
        }
        SDL_ClearError();
    }
#endif
    helper = PyMem_New(RWHelper, 1);
    if (helper == NULL) {
        return (SDL_RWops *)PyErr_NoMemory();
    }
    rw = SDL_AllocRW();
    if (rw == NULL) {
        PyMem_Del(helper);
        return (SDL_RWops *)PyErr_NoMemory();
    }
    fetch_object_methods(helper, obj);
    rw->hidden.unknown.data1 = (void *)helper;
    rw->seek = rw_seek;
    rw->read = rw_read;
    rw->write = rw_write;
    rw->close = rw_close;

    return rw;
}

static SDL_RWops*
RWopsFromObject(PyObject *obj)
{
    PyObject *oencoded;
    SDL_RWops *rw = NULL;

    if (obj != NULL) {
        oencoded = RWopsEncodeFilePath(obj, NULL);
        if (oencoded == NULL) {
            return NULL;
        }
        if (oencoded != Py_None) {
            rw = SDL_RWFromFile(Bytes_AS_STRING(oencoded), "rb");
        }
        Py_DECREF(oencoded);
        if (rw) {
            return rw;
        }
        SDL_ClearError();
    }
    return RWopsFromFileObject(obj);
}

static int
RWopsCheckObject (SDL_RWops* rw)
{
    return rw->close == rw_close;
}

static int
rw_seek (SDL_RWops* context, int offset, int whence)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;

    if (!helper->seek || !helper->tell)
        return -1;

    if (!(offset == 0 && whence == SEEK_CUR)) /*being called only for 'tell'*/
    {
        result = PyObject_CallFunction (helper->seek, "ii", offset, whence);
        if (!result)
            return -1;
        Py_DECREF (result);
    }

    result = PyObject_CallFunction (helper->tell, NULL);
    if (!result)
        return -1;

    retval = PyInt_AsLong (result);
    Py_DECREF (result);

    return retval;
}

static int
rw_read (SDL_RWops* context, void* ptr, int size, int maxnum)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;

    if (!helper->read)
        return -1;

    result = PyObject_CallFunction (helper->read, "i", size * maxnum);
    if (!result)
        return -1;

    if (!Bytes_Check (result))
    {
        Py_DECREF (result);
        return -1;
    }

    retval = Bytes_GET_SIZE (result);
    memcpy (ptr, Bytes_AsString (result), retval);
    retval /= size;

    Py_DECREF (result);
    return retval;
}

static int
rw_write (SDL_RWops* context, const void* ptr, int size, int num)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;

    if (!helper->write)
        return -1;

    result = PyObject_CallFunction (helper->write, "s#", ptr, size * num);
    if(!result)
        return -1;

    Py_DECREF (result);
    return num;
}

static int
rw_close (SDL_RWops* context)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval = 0;

    if (helper->close)
    {
        result = PyObject_CallFunction (helper->close, NULL);
        if (result)
            retval = -1;
        Py_XDECREF (result);
    }

    Py_XDECREF (helper->seek);
    Py_XDECREF (helper->tell);
    Py_XDECREF (helper->write);
    Py_XDECREF (helper->read);
    Py_XDECREF (helper->close);
    PyMem_Del (helper);
    SDL_FreeRW (context);
    return retval;
}

static SDL_RWops*
RWopsFromFileObjectThreaded(PyObject *obj)
{
    SDL_RWops *rw;
    RWHelper *helper;

    if (obj == NULL) {
        return (SDL_RWops *)RAISE(PyExc_TypeError, "Invalid filetype object");
    }

#ifndef WITH_THREAD
    return (SDL_RWops *)RAISE(PyExc_NotImplementedError,
                              "Python built without thread support");
#else
    helper = PyMem_New(RWHelper, 1);
    if (helper == NULL) {
        return (SDL_RWops *)PyErr_NoMemory();
    }
    rw = SDL_AllocRW();
    if (rw == NULL) {
        PyMem_Del(helper);
        return (SDL_RWops *)PyErr_NoMemory();
    }
    fetch_object_methods(helper, obj);
    rw->hidden.unknown.data1 = (void *)helper;
    rw->seek = rw_seek_th;
    rw->read = rw_read_th;
    rw->write = rw_write_th;
    rw->close = rw_close_th;

    PyEval_InitThreads();

    return rw;
#endif
}

static int
RWopsCheckObjectThreaded (SDL_RWops* rw)
{
#ifdef WITH_THREAD
    return rw->close == rw_close_th;
#else
    return 0;
#endif
}

#ifdef WITH_THREAD
static int
rw_seek_th (SDL_RWops* context, int offset, int whence)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;
    PyGILState_STATE state;

    if (!helper->seek || !helper->tell)
        return -1;

    state = PyGILState_Ensure();

    if (!(offset == 0 && whence == SEEK_CUR)) /* being seek'd, not just tell'd */
    {
        result = PyObject_CallFunction (helper->seek, "ii", offset, whence);
        if(!result)
        {
            PyErr_Print();
            retval = -1;
            goto end;
        }
        Py_DECREF (result);
    }

    result = PyObject_CallFunction (helper->tell, NULL);
    if (!result)
    {
        PyErr_Print();
        retval = -1;
        goto end;
    }

    retval = PyInt_AsLong (result);
    Py_DECREF (result);

end:
    PyGILState_Release(state);

    return retval;
}

static int
rw_read_th (SDL_RWops* context, void* ptr, int size, int maxnum)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;
    PyGILState_STATE state;

    if (!helper->read)
        return -1;

    state = PyGILState_Ensure();

    result = PyObject_CallFunction (helper->read, "i", size * maxnum);
    if (!result)
    {
        PyErr_Print();
        retval = -1;
        goto end;
    }

    if (!Bytes_Check (result))
    {
        Py_DECREF (result);
        PyErr_Print();
        retval = -1;
        goto end;
    }

    retval = Bytes_GET_SIZE (result);
    memcpy (ptr, Bytes_AsString (result), retval);
    retval /= size;

    Py_DECREF (result);

end:
    PyGILState_Release(state);

    return retval;
}

static int
rw_write_th (SDL_RWops* context, const void* ptr, int size, int num)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;
    PyGILState_STATE state;

    if (!helper->write)
        return -1;

    state = PyGILState_Ensure();

    result = PyObject_CallFunction (helper->write, "s#", ptr, size * num);
    if (!result)
    {
        PyErr_Print();
        retval = -1;
        goto end;
    }

    Py_DECREF (result);
    retval = num;

end:
    PyGILState_Release(state);

    return retval;
}

static int
rw_close_th (SDL_RWops* context)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval = 0;
    PyGILState_STATE state;

    state = PyGILState_Ensure();

    if (helper->close)
    {
        result = PyObject_CallFunction (helper->close, NULL);
        if (!result)
        {
            PyErr_Print();
            retval = -1;
        }
        Py_XDECREF (result);
    }

    Py_XDECREF (helper->seek);
    Py_XDECREF (helper->tell);
    Py_XDECREF (helper->write);
    Py_XDECREF (helper->read);
    Py_XDECREF (helper->close);

    PyMem_Del (helper);

    PyGILState_Release(state);

    SDL_FreeRW (context);
    return retval;
}
#endif

static PyObject*
rwobject_encode_string(PyObject *self, PyObject *args, PyObject *keywds)
{
    PyObject *obj = NULL;
    PyObject *eclass = NULL;
    const char *encoding = NULL;
    const char *errors = NULL;
    static char *kwids[] = {"obj", "encoding", "errors", "etype", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|OssO&", kwids,
                                     &obj, &encoding, &errors,
                                     &is_exception_class, &eclass)) {
        return NULL;
    }

    if (obj == NULL) {
        RAISE(PyExc_SyntaxError, "Forwarded exception");
    }
    return RWopsEncodeString(obj, encoding, errors, eclass);
}

static PyObject*
rwobject_encode_file_path(PyObject *self, PyObject *args, PyObject *keywds)
{
    PyObject *obj = NULL;
    PyObject *eclass = NULL;
    static char *kwids[] = {"obj", "etype", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|OO&", kwids,
                                     &obj, &is_exception_class, &eclass)) {
        return NULL;
    }

    if (obj == NULL) {
        RAISE(PyExc_SyntaxError, "Forwarded exception");
    }
    return RWopsEncodeFilePath(obj, eclass);
}

static PyMethodDef _rwobject_methods[] =
{
    { "encode_string", (PyCFunction)rwobject_encode_string,
      METH_VARARGS | METH_KEYWORDS, DOC_PYGAMEENCODESTRING },
    { "encode_file_path", (PyCFunction)rwobject_encode_file_path,
      METH_VARARGS | METH_KEYWORDS, DOC_PYGAMEENCODEFILEPATH },
    { NULL, NULL, 0, NULL }
};

/*DOC*/ static char _rwobject_doc[] =
/*DOC*/    "SDL_RWops support";

MODINIT_DEFINE (rwobject)
{
    PyObject *module, *dict, *apiobj;
    int ecode;
    static void* c_api[PYGAMEAPI_RWOBJECT_NUMSLOTS];

#if PY3
    static struct PyModuleDef _module = {
        PyModuleDef_HEAD_INIT,
        "rwobject",
        _rwobject_doc,
        -1,
        _rwobject_methods,
        NULL, NULL, NULL, NULL
    };
#endif

    /* Create the module and add the functions */
#if PY3
    module = PyModule_Create (&_module);
#else
    module = Py_InitModule3 (MODPREFIX "rwobject",
                             _rwobject_methods,
                             _rwobject_doc);
#endif
    if (module == NULL) {
        MODINIT_ERROR;
    }
    dict = PyModule_GetDict (module);

    /* export the c api */
    c_api[0] = RWopsFromObject;
    c_api[1] = RWopsCheckObject;
    c_api[2] = RWopsFromFileObjectThreaded;
    c_api[3] = RWopsCheckObjectThreaded;
    c_api[4] = RWopsEncodeFilePath;
    c_api[5] = RWopsEncodeString;
    c_api[6] = RWopsFromFileObject;
    apiobj = encapsulate_api (c_api, "rwobject");
    if (apiobj == NULL) {
        DECREF_MOD (module);
    MODINIT_ERROR;
    }
    ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
    Py_DECREF (apiobj);
    if (ecode == -1) {
        DECREF_MOD (module);
        MODINIT_ERROR;
    }
    MODINIT_RETURN (module);
}


text:
<!-- test for winodw.history -->
<html>
  <body>
    <script>
      var historyobj = window.history;   // History object
      var __result1 = historyobj.length;
      var __expect1 = "__UInt";
      var __result2 = historyobj.go();
      var __expect2 = undefined;
    </script>
  </body>
</html>


text:
<?php

namespace PronouncePHP\Config;

class Config
{
    /**
     * Get config key value
     *
     * @param string $key
     * @return mixed
    */
    public static function get($key)
    {
        $config = include('config.php');

        return $config[$key];
    }
}


text:
#pragma once

#include "Diff3Parse.h"
#include "ConflictPipelineComponent.h"

namespace FilePersistence {

class ListMergeComponent : public ConflictPipelineComponent
{
	public:
		ListMergeComponent(QSet<QString>& conflictTypes, QSet<QString>& listTypes, QSet<QString>& unorderedTypes);
		~ListMergeComponent();
		LinkedChangesTransition run(std::shared_ptr<GenericTree>& treeA,
											 std::shared_ptr<GenericTree>& treeB,
											 std::shared_ptr<GenericTree>& treeBase,
											 ChangeDependencyGraph& cdgA, ChangeDependencyGraph& cdgB,
					QSet<std::shared_ptr<ChangeDescription> >& conflictingChanges,
					ConflictPairs& conflictPairs, LinkedChangesSet&linkedChangesSet);
	private:
		struct Position
		{
				bool valid_{};
				Model::NodeIdType predecessor_;

				Position(bool valid, Model::NodeIdType predecessor);
				bool operator ==(const Position &other) const;
				bool operator !=(const Position &other) const;
		};

		/**
		 * Returns the IDs of all lists that shall be attempted to be merged by the component.
		 */
		QSet<Model::NodeIdType> computeListsToMerge(
				ChangeDependencyGraph& cdgA,
				ChangeDependencyGraph& cdgB,
				QSet<std::shared_ptr<ChangeDescription> >& conflictingChanges,
				ConflictPairs& conflictPairs);

		std::shared_ptr<ChangeDescription> getConflictingChange(
				ConflictPairs& conflictPairs,
				std::shared_ptr<ChangeDescription>& change);

		QPair<std::shared_ptr<ChangeDescription>, std::shared_ptr<ChangeDescription>> findBranches(
				ChangeDependencyGraph& cdgA,
				std::shared_ptr<ChangeDescription> first,
				std::shared_ptr<ChangeDescription> second);

		QPair<bool, QSet<Model::NodeIdType>> checkAndGetAllElementIds(
				std::shared_ptr<ChangeDescription> changeA,
				std::shared_ptr<ChangeDescription> changeB);

		/**
		 * Given an unstable \a chunk, this method tries to construct the merged version of it.
		 *
		 * The \a idList arguments represent the state of the list in the associated revisions.
		 *
		 * The returned chunk has \a valid_ set to \a false if the chunk could not be merged.
		 */
		void computeMergedChunk(Chunk* chunk, const Model::NodeIdType containerId,
										ChangeDependencyGraph& cdgA, ChangeDependencyGraph& cdgB);

		/**
		 * Returns false if there was a conflict.
		 */
		bool insertElemsIntoChunk(Chunk* chunk,
													const QList<Model::NodeIdType>& spanBase, const Model::NodeIdType containerId,
													const ChangeDependencyGraph& cdgThis,
													const ChangeDependencyGraph& cdgOther,
													const QList<Model::NodeIdType>& spanThis,
													const QList<Model::NodeIdType>& spanOther, bool branchIsA);

		/**
		 * Tries to find a unique position for \a elem in \a chunk that is similar to the position of \a elem in \a origin.
		 * Returns a Position \a pos where \a pos.valid = true if and only if such a position could be found and
		 * \a pos.predecessor is the element after which \a elem should be inserted or 0 if elem should be inserted at
		 * the beginning. Such a position can be found if the nearest predecessor and successor of \elem in \a origin that
		 * are common in \a chunk are next to each other and in order in \a chunk.
		 */
		static Position findPosition(const Model::NodeIdType& element,
											  const QList<Model::NodeIdType>& origin,
											  const Chunk* chunk);

		void markAsResolved(QSet<std::shared_ptr<ChangeDescription> >& conflictingChanges,
										ConflictPairs& conflictPairs, std::shared_ptr<ChangeDescription> change,
										ChangeDependencyGraph& cdgA, ChangeDependencyGraph& cdgB);
		bool noConflictingDependencies(ChangeDependencyGraph& cdg,
												 QSet<std::shared_ptr<ChangeDescription> >& conflictingChanges,
												 std::shared_ptr<ChangeDescription>& change);
		void markDependingAsResolved(ChangeDependencyGraph& cdg,
											  QSet<std::shared_ptr<ChangeDescription> >& conflictingChanges,
											  ConflictPairs& conflictPairs, std::shared_ptr<ChangeDescription>& change);

		/**
		 * Marks all chunks that transitively depend on \a chunk as conflicting. \a chunk itself is not explicitly marked but
		 * implicitly if it transitively depends on itself.
		 */
		void markDependingAsConflicting(Chunk* chunk); // TODO rename to reflect that chunk is also marked

		static bool elementIsStable(const Model::NodeIdType& elem,
									const QList<Model::NodeIdType>& listA,
									const QList<Model::NodeIdType>& listB);

		/**
		 * Returns the chunk of the list of \a listContainer that contains \a element in the base version if
		 * \a listContainer is the id of a prepared list and \a nullptr otherwise.
		 *
		 * We treat a return value of \a nullptr like a chunk that is conflict free.
		 */
		Chunk* findOriginalChunk(Model::NodeIdType element, Model::NodeIdType listContainer, Chunk* guess = nullptr);

		/**
		 * This maps list container IDs to their lists, partitioned into chunks.
		 */
		QHash<Model::NodeIdType, QList<Chunk*>> preparedLists_;

		/**
		 * These nodes have been reordered.
		 */
		QSet<Model::NodeIdType> reorderedNodesA_;
		QSet<Model::NodeIdType> reorderedNodesB_;
		/**
		 * These nodes must not be reordered by the respective branch.
		 * If they are, the mapped chunk must be marked as conflicting.
		 */
		QHash<Model::NodeIdType, Chunk*> mustBeUnchangedByA_;
		QHash<Model::NodeIdType, Chunk*> mustBeUnchangedByB_;
		/**
		 * If the key chunk gets marked as conflicting, all mapped chunks must be marked as conflicting as well.
		 */
		QMultiHash<Chunk*, Chunk*> chunkDependencies_;

		QSet<QString> conflictTypes_;
		QSet<QString> listTypes_;
		QSet<QString> unorderedTypes_;

		std::shared_ptr<GenericTree> treeA_;
		std::shared_ptr<GenericTree> treeB_;
		std::shared_ptr<GenericTree> treeBase_;

		/**
		 * Inserts \a elem into \a chunk according to \a pos.
		 */
		static void insertAfter(Model::NodeIdType elem, Position pos, Chunk* chunk);

		static QList<Model::NodeIdType> nodeListToSortedIdList(const QList<GenericNode*>& list);
};

inline ListMergeComponent::Position::Position(bool valid, Model::NodeIdType predecessor) :
	valid_{valid}, predecessor_{predecessor} {}

inline bool ListMergeComponent::Position::operator ==(const Position &other) const
	{ return this->valid_ && other.valid_ && this->predecessor_ == other.predecessor_; }

inline bool ListMergeComponent::Position::operator !=(const Position &other) const
	{ return !(*this == other); }

} /* namespace FilePersistence */


text:
@implementation UIView (Benihime)

- (UIView *)findFirstResponder {
  if (self.isFirstResponder) {
    return self;
  }

  for (UIView *subView in self.subviews) {
    UIView *firstResponder = [subView findFirstResponder];

    if (firstResponder != nil) {
      return firstResponder;
    }
  }

  return nil;
}

- (UIView *)findAndResignFirstResponder {
  UIView *firstResponder = [self findFirstResponder];
  if (firstResponder)
    [firstResponder resignFirstResponder];
  return firstResponder;
}

- (void)setTapResignsFirstResponder {
  UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]
                                     initWithTarget:self
                                     action:@selector(benihimeDidTapView:)];
  gesture.cancelsTouchesInView = NO;
  [self addGestureRecognizer:gesture];
}

- (void)benihimeDidTapView:(UITapGestureRecognizer *)gesture {
  [self findAndResignFirstResponder];
}

- (UIView *)ancestorWithClass:(Class)ancestorClass {
  return [self.class ancestorOfView:self withClass:ancestorClass];
}

+ (UIView *)ancestorOfView:(UIView *)child withClass:(Class)ancestorClass {
  if (!child.superview)
    return nil;
  if ([child.superview isKindOfClass:ancestorClass])
    return child.superview;
  return [self.class ancestorOfView:child.superview withClass:ancestorClass];
}

- (UIView *)descendantWithClass:(Class)descendantClass {
  return [self.class descendantOfView:self withClass:descendantClass];
}

+ (UIView *)descendantOfView:(UIView *)parent withClass:(Class)descendantClass {
  // Search direct children first
  for (UIView *child in parent.subviews) {
    if ([child isKindOfClass:descendantClass])
      return child;
  }
  // Search grandchildren.
  for (UIView *child in parent.subviews) {
    UIView *match = [self.class descendantOfView:child withClass:descendantClass];
    if (match)
      return match;
  }

  return nil;
}

- (UIView *)childWithClass:(Class)childClass {
  return [self.class childOfView:self withClass:childClass];
}

+ (UIView *)childOfView:(UIView *)parent withClass:(Class)childClass {
  for (UIView *child in parent.subviews) {
    if ([child isKindOfClass:childClass])
      return child;
  }

  return nil;
}

- (UIViewController *)firstAvailableViewController {
  // convenience function for casting and to "mask" the recursive function
  return (UIViewController *)[self traverseResponderChainForUIViewController];
}

- (id)traverseResponderChainForUIViewController {
  id nextResponder = [self nextResponder];
  if ([nextResponder isKindOfClass:[UIViewController class]]) {
    return nextResponder;
  } else if ([nextResponder isKindOfClass:[UIView class]]) {
    return [nextResponder traverseResponderChainForUIViewController];
  } else {
    return nil;
  }
}
@end


text:
require 'spec_helper'

RSpec.describe DataMaker::CN::NIN do
  describe "#self.national_id_number" do
    it "calls DataMaker::CN::GenerateNationalIDNumber#generate" do
      expect_any_instance_of(described_class::GenerateNationalIDNumber).to receive(:generate)
      described_class.national_id_number
    end
  end

  describe "::GenerateNationalIDNumber" do
    describe "#initialize" do
      let(:param) { rand(1000..2000) }

      it "raises an error when a parameter is passed" do
        expect { described_class::GenerateNationalIDNumber.new(param) }.to raise_error
      end
    end

    describe "#generate" do
      let(:generate) { described_class::GenerateNationalIDNumber.new.generate }

      it "generates a string with a length of 18" do
        expect(generate.length).to eq(18)
      end

      it "generates a valid national id number" do
        nin = generate
        expect(DataMaker::Validators::ChineseNINValidator.valid?(nin)).to be_truthy
      end
    end
  end
end


text:
<?
    //============= GARBAGE COLLECTOR ===========================
    //get rid of cache
    $smarty->clear_cache(null,"______rootpage");
    $smarty->clear_cache(null,"keyword");
    $smarty->clear_cache(null,date("Y|m|d",$date));

    //kill empty sections and unused keywords
    # keywords
    $keywords = array();
    $keywords = $db->getCol("SELECT DISTINCT wordid FROM ".PREFIX."keywords");
    if(!empty($keywords)){
        $db->query("DELETE FROM ".PREFIX."keyword WHERE wordid NOT IN(".implode(",",$keywords).")");
        $db->query("OPTIMIZE TABLE ".PREFIX."keyword");
    }

    #sections
    $sections = array();
    $sections = $db->getCol("SELECT DISTINCT catid FROM ".PREFIX."entry");
    if(!empty($sections)){
        $db->query("DELETE FROM ".PREFIX."category WHERE catid NOT IN(".implode(",",$sections).")");
        $db->query("OPTIMIZE TABLE ".PREFIX."category");
    }

    //============= END GARBAGE COLLECTOR =======================
?>