text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="@dimen/margin"
    android:background="@color/screen_background">

    <LinearLayout android:id="@+id/row_1"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/row_spacing">

        <LinearLayout android:id="@+id/box_steps"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingRight="@dimen/margin"
            android:layout_weight="1">

            <TextView android:id="@+id/step_value"
                android:textSize="@dimen/value"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:background="@color/display_background"
                android:paddingLeft="@dimen/padding"
                android:paddingRight="@dimen/padding"
                android:paddingTop="@dimen/padding"
                android:text=""/>
            <TextView android:id="@+id/step_units"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/units"
                android:text="@string/steps"
                android:background="@color/display_background"
                android:paddingBottom="@dimen/padding"/>

        </LinearLayout>

        <LinearLayout android:id="@+id/box_distance"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_weight="1">

            <TextView android:id="@+id/distance_value"
                android:textSize="@dimen/value"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:background="@color/display_background"
                android:paddingTop="@dimen/padding"
                android:paddingRight="@dimen/padding"
                android:paddingLeft="@dimen/padding"
                android:text=""/>
            <TextView android:id="@+id/distance_units"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/units"
                android:text="@string/kilometers"
                android:background="@color/display_background"
                android:paddingBottom="@dimen/padding"/>

        </LinearLayout>
    </LinearLayout>

    <LinearLayout android:id="@+id/row_2"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/row_spacing">

        <LinearLayout android:id="@+id/box_pace"
            android:orientation="vertical"
            android:layout_height="wrap_content"
            android:paddingRight="@dimen/margin"
            android:layout_width="fill_parent"
            android:layout_weight="1">

            <TextView android:id="@+id/pace_value"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@color/display_background"
                android:textSize="@dimen/small_value"
                android:paddingLeft="@dimen/padding"
                android:paddingRight="@dimen/padding"
                android:paddingTop="@dimen/padding"
                android:text=""/>
            <TextView android:id="@+id/pace_units"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/units"
                android:text="@string/steps_per_minute"
                android:paddingBottom="@dimen/padding"
                android:background="@color/display_background"/>

        </LinearLayout>

        <LinearLayout android:id="@+id/box_speed"
            android:orientation="vertical"
            android:paddingRight="@dimen/margin"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1">

            <TextView android:id="@+id/speed_value"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@color/display_background"
                android:textSize="@dimen/small_value"
                android:paddingLeft="@dimen/padding"
                android:paddingRight="@dimen/padding"
                android:paddingTop="@dimen/padding"
                android:text=""/>
            <TextView android:id="@+id/speed_units"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/units"
                android:text="@string/kilometers_per_hour"
                android:paddingBottom="@dimen/padding"
                android:background="@color/display_background"/>
        </LinearLayout>

        <LinearLayout android:id="@+id/box_calories"
            android:orientation="vertical"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1">

            <TextView android:id="@+id/calories_value"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@color/display_background"
                android:textSize="@dimen/small_value"
                android:paddingLeft="@dimen/padding"
                android:paddingRight="@dimen/padding"
                android:paddingTop="@dimen/padding"
                android:text=""/>
            <TextView android:id="@+id/calories_units"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/units"
                android:text="@string/calories_burned"
                android:paddingBottom="@dimen/padding"
                android:background="@color/display_background"/>

        </LinearLayout>

    </LinearLayout>

    <!-- Desired pace/speed row -->
    <LinearLayout
        android:id="@+id/desired_pace_control"
        android:paddingTop="@dimen/row_spacing"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <!-- Button "-", for decrementing desired pace/speed -->
        <Button android:id="@+id/button_desired_pace_lower"
            android:text="-"
            android:textSize="@dimen/button_sign"
            android:layout_width="@dimen/button"
            android:layout_height="@dimen/button"/>

        <!-- Container for desired pace/speed -->
        <LinearLayout
            android:gravity="center_horizontal"
            android:orientation="vertical"
            android:layout_width="@dimen/desired_pace_width"
            android:layout_height="wrap_content">

            <TextView android:id="@+id/desired_pace_label"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/desired_pace"/>

            <!-- Current desired pace/speed -->
            <TextView android:id="@+id/desired_pace_value"
                android:gravity="center_horizontal"
                android:textSize="@dimen/desired_pace"
                android:layout_width="@dimen/desired_pace_width"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <!-- Button "+", for incrementing desired pace/speed -->
        <Button android:id="@+id/button_desired_pace_raise"
            android:text="+"
            android:textSize="@dimen/button_sign"
            android:layout_width="@dimen/button"
            android:layout_height="@dimen/button"/>

    </LinearLayout>

</LinearLayout>


text:
/* eslint-disable unicorn/consistent-function-scoping */
import { describe, it } from 'mocha';

import { ConfigurationError } from '../src';
import { OutputStream } from '../src/adapter';
import { ActivityFinished, ActivityStarts, DomainEvent, TestRunnerDetected } from '../src/events';
import { CorrelationId, Name } from '../src/model';
import { Actor, Interaction } from '../src/screenplay';
import { Serenity } from '../src/Serenity';
import { Cast, Clock, ListensToDomainEvents, Stage, StageCrewMember, StageCrewMemberBuilder } from '../src/stage';
import { StageCrewMemberBuilderDependencies } from '../src/stage/StageCrewMemberBuilderDependencies';
import { expect } from './expect';
import sinon = require('sinon');

describe('Serenity', () => {

    describe('when constructing a Stage', () => {
        it('connects it with a provided Cast', () => {

            const prepareSpy = sinon.spy();

            // no-op actors with no special Abilities
            class Extras implements Cast {
                prepare(actor: Actor): Actor {
                    prepareSpy(actor);
                    return actor;
                }
            }

            const serenity = new Serenity(new Clock());

            serenity.configure({
                actors: new Extras(),
            });

            const Joe = serenity.theActorCalled('Joe');

            expect(prepareSpy).to.have.been.calledOnce;
            expect(prepareSpy.getCall(0).args[0]).to.equal(Joe);
        });

        it('connects it with provided StageCrewMembers', () => {

            const stageCrewMember: StageCrewMember = {
                assignedTo: sinon.spy(),
                notifyOf(event: DomainEvent) { /* no-op */ }
            }

            const serenity = new Serenity(new Clock());

            serenity.configure({
                crew: [
                    stageCrewMember
                ]
            });

            expect(stageCrewMember.assignedTo).to.have.been.calledOnceWith(sinon.match.instanceOf(Stage));
        });

        it('injects dependencies into StageCrewMemberBuilders', () => {

            const stageCrewMemberBuilder: StageCrewMemberBuilder = {
                build: sinon.spy(),
            };

            const outputStream: OutputStream = {
                write(content: string) {
                    // no-op
                }
            }

            const serenity = new Serenity(new Clock());

            serenity.configure({
                outputStream,
                crew: [
                    stageCrewMemberBuilder
                ]
            });

            expect(stageCrewMemberBuilder.build).to.have.been.calledOnceWith(
                sinon.match.has('stage', sinon.match.instanceOf(Stage))
                    .and(
                        sinon.match.has('outputStream', outputStream)
                    )
            );
        });

        it(`complains when a provided crew member doesn't implement StageCrewMember or StageCrewMemberBuilder interfaces`, () => {

            const stageCrewMemberBuilder: StageCrewMemberBuilder = {
                build(dependencies: StageCrewMemberBuilderDependencies): ListensToDomainEvents {
                    return {
                        notifyOf(event: DomainEvent): void {
                            // no-op
                        }
                    };
                }
            };

            const serenity = new Serenity(new Clock());

            expect(() => {
                serenity.configure({
                    crew: [
                        stageCrewMemberBuilder,
                        undefined,
                    ]
                });
            }).to.throw(ConfigurationError,
                'Entries under `crew` should implement either StageCrewMember or StageCrewMemberBuilder interfaces, `undefined` found at index 1'
            )
        });
    });

    it(`enables propagation of DomainEvents triggered by Actors' Activities and StageCrewMembers`, () => {

        class Extras implements Cast {
            prepare(actor: Actor): Actor {
                return actor;
            }
        }

        const PerformSomeInteraction = () =>
            Interaction.where(`#actor performs some interaction`, actor => {
                return void 0;
            });

        const frozenClock = new Clock(() => new Date('1983-07-03'));
        const serenity = new Serenity(frozenClock);
        const listener = new Listener<ActivityStarts | ActivityFinished>();

        serenity.configure({
            actors: new Extras(),
            crew: [ listener ],
        });

        return serenity.theActorCalled('Joe').attemptsTo(
            PerformSomeInteraction(),
        ).
        then(() => serenity.waitForNextCue()).
        then(() => {
            expect(listener.events).to.have.lengthOf(2);

            expect(listener.events[0]).to.be.instanceOf(ActivityStarts);
            expect(listener.events[0].details.name.value).to.equal(`Joe performs some interaction`);

            expect(listener.events[1]).to.be.instanceOf(ActivityFinished);
            expect(listener.events[1].details.name.value).to.equal(`Joe performs some interaction`);
        });
    });

    it('allows for external parties, such as test runner adapters, to announce DomainEvents', () => {

        const frozenClock = new Clock(() => new Date('1983-07-03'));
        const serenity = new Serenity(frozenClock);
        const listener = new Listener<TestRunnerDetected>();

        const testRunnerName = new Name('mocha');

        serenity.configure({ crew: [ listener ] });

        serenity.announce(new TestRunnerDetected(CorrelationId.create(), testRunnerName, serenity.currentTime()));

        return serenity.waitForNextCue().
            then(() => {
                expect(listener.events).to.have.lengthOf(1);

                expect(listener.events[0]).to.be.instanceOf(TestRunnerDetected);
                expect(listener.events[0].name).to.equal(testRunnerName);
            });
    });

    class Listener<Event_Type extends DomainEvent> implements StageCrewMember {
        public readonly events: Event_Type[] = [];

        constructor(private stage?: Stage) {
        }

        assignedTo(stage: Stage): StageCrewMember {
            this.stage = stage;

            return this;
        }

        notifyOf(event: Event_Type): void {
            this.events.push(event);
        }
    }
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
  <head>
    <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, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="mobile-web-app-capable" content="yes">
    <title>ScoreKeeper</title>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="fonts/scorekeeper-icon-font.css">
    <link rel="stylesheet" href="score_keeper.css">

    <!-- import the click-counter -->
    <link rel="import" href="elements/game.html">
    <script type="application/dart">export 'package:polymer/init.dart';</script>
    <script src="packages/browser/dart.js"></script>
  </head>
  <body>
    <sk-game></sk-game>
  </body>
</html>


text:
        {{ if .PrevInSection }}

Next

        {{ end }}
        {{ if .NextInSection }}

Previous

        {{ end }}


text:
#pragma once

#include "Base/BaseTypes.h"
#include "Debug/DVAssert.h"

namespace DAVA
{
/**
    \addtogroup input
    \{
*/

/**
    List of all supported input elements.

    An input element is a part of a device which can be used for input. For example, a keyboard button, a mouse button, a mouse wheel, gamepad's stick etc.
    Number values used in this enum are safe to be saved in order to be restored later (e.g. in a config file).

    These values can be tested for different properties using functions defined below (i.e. what device type it belongs to, is it a button or not, etc.).
*/
enum eInputElements : uint32
{
    // Order of elements and values should not be changed
    // To provide backward compatibility in case some of these values are saved somewhere

    NONE = 0,

    // Keyboard scancode keys
    // These are named after characters they produce in QWERTY US layout
    // E.g. KB_W produces 'w' in QWERTY, but 'z' in AZERTY
    // TODO: except for Android, since we handle keycodes instead of scancodes there (see DavaSurfaceView.onKey). Needs some research

    // TODO: add support for virtual keys in addition to scancode keys we have now

    // TODO: order of keyboard elements is made to be backward compatible with old DAVA::Key implementation,
    // since these values could be saved to config file by a client.
    // Reorder these into more logical sequences and remove KB_UNUSED when switching to new action system

    KB_ESCAPE,
    KB_BACKSPACE,
    KB_TAB,
    KB_ENTER,
    KB_SPACE,
    KB_LSHIFT,
    KB_LCTRL,
    KB_LALT,
    KB_LCMD,
    KB_RCMD,
    KB_MENU,
    KB_PAUSE,
    KB_CAPSLOCK,
    KB_NUMLOCK,
    KB_SCROLLLOCK,
    KB_PAGEUP,
    KB_PAGEDOWN,
    KB_HOME,
    KB_END,
    KB_INSERT,
    KB_DELETE,
    KB_LEFT,
    KB_UP,
    KB_RIGHT,
    KB_DOWN,
    KB_0,
    KB_1,
    KB_2,
    KB_3,
    KB_4,
    KB_5,
    KB_6,
    KB_7,
    KB_8,
    KB_9,
    KB_A,
    KB_B,
    KB_C,
    KB_D,
    KB_E,
    KB_F,
    KB_G,
    KB_H,
    KB_I,
    KB_J,
    KB_K,
    KB_L,
    KB_M,
    KB_N,
    KB_O,
    KB_P,
    KB_Q,
    KB_R,
    KB_S,
    KB_T,
    KB_U,
    KB_V,
    KB_W,
    KB_X,
    KB_Y,
    KB_Z,
    KB_GRAVE,
    KB_MINUS,
    KB_EQUALS,
    KB_BACKSLASH,
    KB_LBRACKET,
    KB_RBRACKET,
    KB_SEMICOLON,
    KB_APOSTROPHE,
    KB_COMMA,
    KB_PERIOD,
    KB_SLASH,
    KB_NUMPAD_0,
    KB_NUMPAD_1,
    KB_NUMPAD_2,
    KB_NUMPAD_3,
    KB_NUMPAD_4,
    KB_NUMPAD_5,
    KB_NUMPAD_6,
    KB_NUMPAD_7,
    KB_NUMPAD_8,
    KB_NUMPAD_9,
    KB_MULTIPLY,
    KB_DIVIDE,
    KB_NUMPAD_PLUS,
    KB_NUMPAD_MINUS,
    KB_NUMPAD_DELETE,
    KB_F1,
    KB_F2,
    KB_F3,
    KB_F4,
    KB_F5,
    KB_F6,
    KB_F7,
    KB_F8,
    KB_F9,
    KB_F10,
    KB_F11,
    KB_F12,
    KB_UNUSED1, // Used to be Key::Back on Andorid, which does not exist anymore. Left for compatibility
    KB_UNUSED2, // Used to be Key::Menu on Android, which does not exist anymore. Left for compatibility
    KB_NONUSBACKSLASH,
    KB_NUMPAD_ENTER,
    KB_PRINTSCREEN,
    KB_RSHIFT,
    KB_RCTRL,
    KB_RALT,
    KB_F13,
    KB_F14,
    KB_F15,
    KB_F16,
    KB_F17,
    KB_F18,
    KB_F19,
    KB_LWIN,
    KB_RWIN,
    KB_CAMERA_FOCUS,
    KB_FUNCTION,
    KB_MEDIA_PREVIOUS,
    KB_MEDIA_NEXT,
    KB_MEDIA_PLAY_PAUSE,
    KB_MEDIA_EJECT,
    KB_VOLUME_MUTE,
    KB_VOLUME_UP,
    KB_VOLUME_DOWN,

    // Mouse

    MOUSE_LBUTTON = 1024, // Range from 1 to 1023 is reserved for keyboard
    MOUSE_RBUTTON,
    MOUSE_MBUTTON,
    MOUSE_EXT1BUTTON,
    MOUSE_EXT2BUTTON,
    MOUSE_WHEEL,
    MOUSE_POSITION,

    // Gamepad

    GAMEPAD_START = 1024 * 2, // Range from 1024 to 2047 is reserved for mouse
    GAMEPAD_A,
    GAMEPAD_B,
    GAMEPAD_X,
    GAMEPAD_Y,
    GAMEPAD_DPAD_LEFT,
    GAMEPAD_DPAD_RIGHT,
    GAMEPAD_DPAD_UP,
    GAMEPAD_DPAD_DOWN,
    GAMEPAD_LTHUMB,
    GAMEPAD_RTHUMB,
    GAMEPAD_LSHOULDER,
    GAMEPAD_RSHOULDER,

    GAMEPAD_AXIS_LTRIGGER,
    GAMEPAD_AXIS_RTRIGGER,
    GAMEPAD_AXIS_LTHUMB,
    GAMEPAD_AXIS_RTHUMB,

    // Touch

    TOUCH_CLICK0 = 1024 * 3, // Range from 2048 to 3071 is reserved for gamepad
    TOUCH_CLICK1,
    TOUCH_CLICK2,
    TOUCH_CLICK3,
    TOUCH_CLICK4,
    TOUCH_CLICK5,
    TOUCH_CLICK6,
    TOUCH_CLICK7,
    TOUCH_CLICK8,
    TOUCH_CLICK9,

    TOUCH_POSITION0,
    TOUCH_POSITION1,
    TOUCH_POSITION2,
    TOUCH_POSITION3,
    TOUCH_POSITION4,
    TOUCH_POSITION5,
    TOUCH_POSITION6,
    TOUCH_POSITION7,
    TOUCH_POSITION8,
    TOUCH_POSITION9,

    // This element is used for sending UIEvent indicating back navigation
    // TODO: make clients to use Window::backNavigation event only!
    BACK = 1024 * 4, // Range from 3071 to 4095 is reserved for touch screen

    // Counters

    FIRST = NONE,
    LAST = TOUCH_POSITION9,

    MOUSE_FIRST = MOUSE_LBUTTON,
    MOUSE_LAST = MOUSE_POSITION,
    MOUSE_FIRST_BUTTON = MOUSE_LBUTTON,
    MOUSE_LAST_BUTTON = MOUSE_EXT2BUTTON,

    KB_FIRST = KB_ESCAPE,
    KB_LAST = KB_VOLUME_DOWN,

    GAMEPAD_FIRST = GAMEPAD_START,
    GAMEPAD_LAST = GAMEPAD_AXIS_RTHUMB,
    GAMEPAD_FIRST_BUTTON = GAMEPAD_START,
    GAMEPAD_LAST_BUTTON = GAMEPAD_RSHOULDER,
    GAMEPAD_FIRST_AXIS = GAMEPAD_AXIS_LTRIGGER,
    GAMEPAD_LAST_AXIS = GAMEPAD_AXIS_RTHUMB,

    TOUCH_FIRST = TOUCH_CLICK0,
    TOUCH_LAST = TOUCH_POSITION9,

    TOUCH_FIRST_CLICK = TOUCH_CLICK0,
    TOUCH_LAST_CLICK = TOUCH_CLICK9,

    TOUCH_FIRST_POSITION = TOUCH_POSITION0,
    TOUCH_LAST_POSITION = TOUCH_POSITION9
};

// Helper values
enum
{
    INPUT_ELEMENTS_KB_COUNT = eInputElements::KB_LAST - eInputElements::KB_FIRST + 1,
    INPUT_ELEMENTS_MOUSE_BUTTON_COUNT = eInputElements::MOUSE_LAST_BUTTON - eInputElements::MOUSE_FIRST_BUTTON + 1,
    INPUT_ELEMENTS_TOUCH_CLICK_COUNT = eInputElements::TOUCH_LAST_CLICK - eInputElements::TOUCH_FIRST_CLICK + 1,
    INPUT_ELEMENTS_TOUCH_POSITION_COUNT = eInputElements::TOUCH_LAST_POSITION - eInputElements::TOUCH_FIRST_POSITION + 1
};

// Each touch should have both _CLICK and _POSITION pieces
static_assert(INPUT_ELEMENTS_TOUCH_CLICK_COUNT == INPUT_ELEMENTS_TOUCH_POSITION_COUNT, "Amount of touch clicks does not match amount of touch positions");

/** List of element types. */
enum class eInputElementTypes
{
    /** Button, which can just be pressed and released. */
    DIGITAL,

    /** Element whose state can only be described using multiple float values. */
    ANALOG
};

/** Contains additional information about an input element. */
struct InputElementInfo final
{
    /** Name of the element */
    String name;

    /** Type of the element */
    eInputElementTypes type;
};

/**
    Return true if specified `element` is a mouse element.
    This function is thread-safe.
 */
inline bool IsMouseInputElement(eInputElements element)
{
    return eInputElements::MOUSE_FIRST <= element && element <= eInputElements::MOUSE_LAST;
}

/**
    Return true if specified `element` is a mouse button element.
    This function is thread-safe.
 */
inline bool IsMouseButtonInputElement(eInputElements element)
{
    return eInputElements::MOUSE_FIRST_BUTTON <= element && element <= eInputElements::MOUSE_LAST_BUTTON;
}

/**
    Return true if specified `element` is a gamepad element.
    This function is thread-safe.
 */
inline bool IsGamepadInputElement(eInputElements element)
{
    return eInputElements::GAMEPAD_FIRST <= element && element <= eInputElements::GAMEPAD_LAST;
}

/**
    Return true if specified `element` is a gamepad button element.
    This function is thread-safe.
 */
inline bool IsGamepadButtonInputElement(eInputElements element)
{
    return eInputElements::GAMEPAD_FIRST_BUTTON <= element && element <= eInputElements::GAMEPAD_LAST_BUTTON;
}

/**
    Return true if specified `element` is a gamepad axis element.
    This function is thread-safe.
 */
inline bool IsGamepadAxisInputElement(eInputElements element)
{
    return eInputElements::GAMEPAD_FIRST_AXIS <= element && element <= eInputElements::GAMEPAD_LAST_AXIS;
}

/**
    Return true if specified `element` is a keyboard element.
    This function is thread-safe.
 */
inline bool IsKeyboardInputElement(eInputElements element)
{
    return eInputElements::KB_FIRST <= element && element <= eInputElements::KB_LAST;
}

/**
    Return true if specified keyboard `element` is a keyboard modifier element.
    This function is thread-safe.
 */
inline bool IsKeyboardModifierInputElement(eInputElements element)
{
    return (element == eInputElements::KB_LSHIFT ||
            element == eInputElements::KB_LCTRL ||
            element == eInputElements::KB_LALT ||
            element == eInputElements::KB_RSHIFT ||
            element == eInputElements::KB_RCTRL ||
            element == eInputElements::KB_RALT ||
            element == eInputElements::KB_LCMD ||
            element == eInputElements::KB_RCMD);
}

/**
    Return true if specified keyboard `element` is a keyboard 'system' element.
    This function is thread-safe.
 */
inline bool IsKeyboardSystemInputElement(eInputElements element)
{
    return (element == eInputElements::KB_ESCAPE ||
            element == eInputElements::KB_CAPSLOCK ||
            element == eInputElements::KB_LWIN ||
            element == eInputElements::KB_RWIN ||
            element == eInputElements::KB_PRINTSCREEN ||
            element == eInputElements::KB_SCROLLLOCK ||
            element == eInputElements::KB_PAUSE ||
            element == eInputElements::KB_INSERT ||
            element == eInputElements::KB_HOME ||
            element == eInputElements::KB_DELETE ||
            element == eInputElements::KB_END ||
            element == eInputElements::KB_NUMLOCK ||
            element == eInputElements::KB_MENU ||
            element == eInputElements::KB_CAMERA_FOCUS ||
            element == eInputElements::KB_FUNCTION ||
            element == eInputElements::KB_MEDIA_PREVIOUS ||
            element == eInputElements::KB_MEDIA_NEXT ||
            element == eInputElements::KB_MEDIA_PLAY_PAUSE ||
            element == eInputElements::KB_MEDIA_EJECT ||
            element == eInputElements::KB_VOLUME_DOWN ||
            element == eInputElements::KB_VOLUME_UP ||
            element == eInputElements::KB_VOLUME_MUTE);
}

/**
    Return true if specified `element` is a touch element.
    This function is thread-safe.
 */
inline bool IsTouchInputElement(eInputElements element)
{
    return eInputElements::TOUCH_FIRST <= element && element <= eInputElements::TOUCH_LAST;
}

/**
    Return true if specified `element` is a touch click element.
    This function is thread-safe.
 */
inline bool IsTouchClickInputElement(eInputElements element)
{
    return eInputElements::TOUCH_FIRST_CLICK <= element && element <= eInputElements::TOUCH_LAST_CLICK;
}

/**
    Return true if specified `element` is a touch position element.
    This function is thread-safe.
 */
inline bool IsTouchPositionInputElement(eInputElements element)
{
    return eInputElements::TOUCH_FIRST_POSITION <= element && element <= eInputElements::TOUCH_LAST_POSITION;
}

/**
    Return TOUCH_POSITION element for specified click `element. I.e. TOUCH_POSITION3 for TOUCH_CLICK3 etc.
    This function is thread-safe.
*/
inline eInputElements GetTouchPositionElementFromClickElement(eInputElements element)
{
    DVASSERT(IsTouchClickInputElement(element));

    return static_cast<eInputElements>(eInputElements::TOUCH_FIRST_POSITION + (element - eInputElements::TOUCH_FIRST_CLICK));
}

/**
    Get additional information about an element.
    This function is thread-safe.
*/
const InputElementInfo& GetInputElementInfo(eInputElements element);

// TODO: add glyphs api (i.e. getting element's `image` representation)

/**
    \}
*/

} // namespace DAVA


text:
// -*- C++ -*-

//==========================================================================
/**
 *  @file    Thread_Semaphore.h
 *
 *  $Id: Thread_Semaphore.h 2179 2013-05-28 22:16:51Z mesnierp $
 *
 *   Moved from Synch.h.
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//==========================================================================

#ifndef ACE_THREAD_SEMAPHORE_H
#define ACE_THREAD_SEMAPHORE_H
#include /**/ "ace/pre.h"

#include /**/ "ace/ACE_export.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if !defined (ACE_HAS_THREADS)
#  include "ace/Null_Semaphore.h"
#else /* ACE_HAS_THREADS */
// ACE platform supports some form of threading.

#include "ace/Semaphore.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_Thread_Semaphore
 *
 * @brief Wrapper for Dijkstra style general semaphores that work
 * only within one process.
 */
class ACE_Export ACE_Thread_Semaphore : public ACE_Semaphore
{
public:
  /// Initialize the semaphore, with an initial value of @a count,
  /// maximum value of @a max, and unlocked by default.
  ACE_Thread_Semaphore (unsigned int count = 1, // By default make this unlocked.
                        const ACE_TCHAR *name = 0,
                        void * = 0,
                        int max = 0x7FFFFFFF);

  /// Default destructor.
  ~ACE_Thread_Semaphore (void);

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;
};

/*****************************************************************************/

template <class T> class ACE_Malloc_Lock_Adapter_T;

/**
 * @brief Template specialization of ACE_Malloc_Lock_Adapter_T for
 * ACE_Thread_Semaphore.
 *
 * This is needed since the ctor for ACE_Thread_Semaphore doesn't match
 * the standard form used by other lock strategy classes.
 */
template<>
class ACE_Export ACE_Malloc_Lock_Adapter_T<ACE_Thread_Semaphore>
{
public:
  ACE_Thread_Semaphore * operator () (const ACE_TCHAR *name);
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/Thread_Semaphore.inl"
#endif /* __ACE_INLINE__ */

#endif /* !ACE_HAS_THREADS */

#include /**/ "ace/post.h"
#endif /* ACE_THREAD_SEMAPHORE_H */


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

<TITLE>
PropertiesChunk (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.hsmf.datatypes

Class PropertiesChunk

java.lang.Object
  org.apache.poi.hsmf.datatypes.Chunk
      org.apache.poi.hsmf.datatypes.PropertiesChunk

Direct Known Subclasses:
MessagePropertiesChunk, StoragePropertiesChunk

public abstract class PropertiesChunk
extends Chunk

A Chunk which holds (single) fixed-length properties, and pointer
  to the variable length ones / multi-valued ones (which get their
  own chunk).

There are two kinds of PropertiesChunks, which differ only in
  their headers.

Field Summary

static java.lang.String
NAME

Fields inherited from class org.apache.poi.hsmf.datatypes.Chunk

chunkId, DEFAULT_NAME_PREFIX, namePrefix, type

Constructor Summary

protected
PropertiesChunk(ChunkGroup parentGroup)

          Creates a Properties Chunk.

Method Summary

 java.lang.String
getEntryName()

          Creates a string to use to identify this chunk in the POI file system object.

 java.util.Map<MAPIProperty,java.util.List<PropertyValue>>
getProperties()

          Returns all the properties in the chunk, along with their
  values.

 java.util.Map<MAPIProperty,PropertyValue>
getRawProperties()

          Returns all the properties in the chunk, without
  looking up any chunk-based values

 PropertyValue
getRawValue(MAPIProperty property)

          Returns the value / pointer to the value chunk of
  the property, or null if none exists

 java.util.List<PropertyValue>
getValues(MAPIProperty property)

          Returns all values for the given property, looking up chunk based
  ones as required, of null if none exist

protected  void
matchVariableSizedPropertiesToChunks()

          Called once the parent ChunkGroup has been populated, to match
  up the Chunks in it with our Variable Sized Properties.

protected  void
readProperties(java.io.InputStream value)

protected  void
writeProperties(java.io.OutputStream out)

Methods inherited from class org.apache.poi.hsmf.datatypes.Chunk

getChunkId, getType, readValue, writeValue

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NAME

public static final java.lang.String NAME

See Also:
Constant Field Values

Constructor Detail

PropertiesChunk

protected PropertiesChunk(ChunkGroup parentGroup)

Creates a Properties Chunk.

Method Detail

getEntryName

public java.lang.String getEntryName()

Description copied from class: Chunk

Creates a string to use to identify this chunk in the POI file system object.

Overrides:
getEntryName in class Chunk

getRawProperties

public java.util.Map<MAPIProperty,PropertyValue> getRawProperties()

Returns all the properties in the chunk, without
  looking up any chunk-based values

getProperties

public java.util.Map<MAPIProperty,java.util.List<PropertyValue>> getProperties()

Returns all the properties in the chunk, along with their
  values.

Any chunk-based values will be looked up and returned as such

getValues

public java.util.List<PropertyValue> getValues(MAPIProperty property)

Returns all values for the given property, looking up chunk based
  ones as required, of null if none exist

getRawValue

public PropertyValue getRawValue(MAPIProperty property)

Returns the value / pointer to the value chunk of
  the property, or null if none exists

matchVariableSizedPropertiesToChunks

protected void matchVariableSizedPropertiesToChunks()

Called once the parent ChunkGroup has been populated, to match
  up the Chunks in it with our Variable Sized Properties.

readProperties

protected void readProperties(java.io.InputStream value)
                       throws java.io.IOException

Throws:

java.io.IOException

writeProperties

protected void writeProperties(java.io.OutputStream out)
                        throws java.io.IOException

Throws:

java.io.IOException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
require 'spec_helper'

RSpec.describe "fail_and_return!" do
  describe "returns immediately from executed block" do
    class FailAndReturnAction
      extend LightService::Action
      promises :one, :two

      executed do |ctx|
        ctx.one = 1
        # Have to set it in Context
        ctx.two = nil

        ctx.fail_and_return!('Something went wrong')
        ctx.two = 2
      end
    end

    it "returns immediately from executed block" do
      result = FailAndReturnAction.execute

      expect(result).to be_failure
      expect(result.two).to be_nil
    end
  end

  describe "accepts error_code option" do
    class FailAndReturnWithErrorCodeAction
      extend LightService::Action
      promises :one, :two

      executed do |ctx|
        ctx.one = 1
        # Have to set it in Context
        ctx.two = nil

        ctx.fail_and_return!('Something went wrong', :error_code => 401)
        ctx.two = 2
      end
    end

    it "returned context contains the error_code" do
      result = FailAndReturnWithErrorCodeAction.execute

      expect(result).to be_failure
      expect(result.error_code).to eq 401
      expect(result.two).to be_nil
    end
  end
end


text:
This appendix is intended to provide more background on Ivy changes. Many of these examples list error messages you may see, so searching by error message might be a good idea if you are debugging.

<div class="alert is-critical">
NOTE: Most of these issues affect a small percentage of applications encountering unusual or rare edge cases.
</div>

{@a content-children-descendants}
## @ContentChildren queries only match direct children by default

### Basic example of change

Let's say a component (`Comp`) has a `@ContentChildren` query for `'foo'`:

```html
<comp>
    <div>
         <div #foo></div>   <!-- matches in old runtime, not in new runtime -->
    </div>
</comp>
```

In the previous runtime, the `<div>` with `#foo` would match.
With Ivy, that `<div>` does not match because it is not a direct child of `<comp>`.

### Background

By default, `@ContentChildren` queries have the `descendants` flag set to `false`.

In the previous rendering engine, "descendants" referred to "descendant directives".
An element could be a match as long as there were no other directives between the element and the requesting directive.
This made sense for directives with nesting like tabs, where nested tab directives might not be desirable to match.
However, this caused surprising behavior for users because adding an unrelated directive like `ngClass` to a wrapper element could invalidate query results.

For example, with the content query and template below, the last two `Tab` directives would not be matches:

```
@ContentChildren(Tab, {descendants: false}) tabs: QueryList<Tab>
```

```
<tab-list>
  <div>
    <tab> One </tab>     <!-- match (nested in element) -->
  </div>
  <tab>                  <!-- match (top level) -->
    <tab> A </tab>       <!-- not a match (nested in tab) -->
  </tab>
  <div [ngClass]="classes">
    <tab> Two </tab>     <!-- not a match (nested in ngClass) -->
  </div>
</tab-list>
```

In addition, the differences between type and string predicates were subtle and sometimes unclear.
For example, if you replace the type predicate above with a `'foo'` string predicate, the matches change:

```
@ContentChildren('foo', {descendants: false}) foos: QueryList<ElementRef>
```

```
<tab-list>
  <div>
    <div #foo> One </div>     <!-- match (nested in element) -->
  </div>
  <tab #foo>                  <!-- match (top level) -->
    <div #foo> A </div>       <!-- match (nested in tab) -->
  </tab>
  <div [ngClass]="classes">
    <div #foo> Two </div>     <!-- match (nested in ngClass) -->
  </div>
</tab-list>
```

Because the previous behavior was inconsistent and surprising to users, we did not want to reproduce it in Ivy.
Instead, we simplified the mental model so that "descendants" refers to DOM nesting only.
Any DOM element between the requesting component and a potential match will invalidate that match.
Type predicates and string predicates also have identical matching behavior.

Ivy behavior for directive/string predicates:
```
<tab-list>
  <div>
    <tab> One </tab>     <!-- not a match (nested in element) -->
  </div>
  <tab>                  <!-- match (top level) -->
    <tab> A </tab>       <!-- not a match (nested in tab) -->
  </tab>
  <div [ngClass]="classes">
    <tab> Two </tab>     <!-- not a match (nested in div) -->
  </div>
</tab-list>
```

### Example of error

The error message that you see will depend on how the particular content query is used in the application code.
Frequently, an error is thrown when a property is referenced on the content query result (which is now `undefined`).

For example, if the component sets the content query results to a property, `foos`, `foos.first.bar` would throw the error:

```
Uncaught TypeError: Cannot read property 'bar' of undefined
```

If you see an error like this, and the `undefined` property refers to the result of a `@ContentChildren` query, it may well be caused by this change.

### Recommended fix

You can either add the `descendants: true` flag to ignore wrapper elements or remove the wrapper elements themselves.

Option 1:
```
@ContentChildren('foo', {descendants: true}) foos: QueryList<ElementRef>;
```

Option 2:
```
<comp>
   <div #foo></div>   <!-- matches in both old runtime and  new runtime -->
</comp>
```

{@a undecorated-classes}
## All classes that use Angular DI must have an Angular class-level decorator

### Basic example of change:

In the previous rendering engine, the following would work:

```
export class DataService {
  constructor(@Inject('CONFIG') public config: DataConfig) {}
}

@Injectable()
export class AppService extends DataService {...}
```

In Ivy, it will throw an error because `DataService` is using Angular dependency injection, but is missing an `@Injectable` decorator.

The following would also work in the previous rendering engine, but in Ivy would require a `@Directive` decorator because it uses DI:

```
export class BaseMenu {
  constructor(private vcr: ViewContainerRef) {}
}

@Directive({selector: '[settingsMenu]'})
export class SettingsMenu extends BaseMenu {}
```

The same is true if your directive class extends a decorated directive, but does not have a decorator of its own.

If you're using the CLI, there are two automated migrations that should transition your code for you ([this one](guide/migration-injectable) and [this one](guide/migration-undecorated-classes)).
However, as you're adding new code in version 9, you may run into this difference.

### Background

When a class has an Angular decorator like `@Injectable` or `@Directive`, the Angular compiler generates extra code to support injecting dependencies into the constructor of your class.
When using inheritance, Ivy needs both the parent class and the child class to apply a decorator to generate the correct code.
Otherwise, when the decorator is missing from the parent class, the subclass will inherit a constructor from a class for which the compiler did not generate special constructor info, and Angular won't have the dependency info it needs to create it properly.

In the previous rendering engine, the compiler had global knowledge, so in some cases (such as AOT mode or the presence of certain injection flags), it could look up the missing data.
However, the Ivy compiler only processes each class in isolation.
This means that compilation has the potential to be faster (and opens the framework up for optimizations and features going forward), but the compiler can't automatically infer the same information as before.

Adding the proper decorator explicitly provides this information.

### Example of error

In JIT mode, the framework will throw the following error:

```
ERROR: This constructor is not compatible with Angular Dependency Injection because its dependency at index X of the parameter list is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.

Please check that 1) the type for the parameter at index X is correct and 2) the correct Angular decorators are defined for this class and its ancestors.
```

In AOT mode, you'll see something like:

```
X inherits its constructor from Y, but the latter does not have an Angular decorator of its own.
Dependency injection will not be able to resolve the parameters of Y's constructor. Either add a
@Directive decorator to Y, or add an explicit constructor to X.
```

In some cases, the framework may not be able to detect the missing decorator.
In these cases, you'll generally see a runtime error thrown when there is a property access attempted on the missing dependency.
If dependency was `foo`, you'd see an error when accessing something like `foo.bar`:

```
Uncaught TypeError: Cannot read property 'bar' of undefined
```

If you see an error like this, and the `undefined` value refers to something that should have been injected, it may be this change.

### Recommended fix

- Add an `@Injectable` decorator to anything you plan to provide or inject.

```
@Injectable()
export class DataService {
  constructor(@Inject('CONFIG') public config: DataConfig) {}
}

@Injectable()
export class AppService extends DataService {...}
```

- Add a [selectorless `@Directive` decorator](guide/migration-undecorated-classes#what-does-it-mean-to-have-a-directive-decorator-with-no-metadata-inside-of-it) to any class that extends a directive or any class from which a directive inherits.

```
@Directive()            // selectorless, so it's not usable directly
export class BaseMenu {
  constructor(private vcr: ViewContainerRef) {}
}

@Directive({selector: '[settingsMenu]'})
export class SettingsMenu extends BaseMenu {}
```

{@a select-value-binding}
## Cannot Bind to `value` property of `<select>` with `*ngFor`

### Basic example of change

```html
<select [value]="someValue">
  <option *ngFor="let option of options" [value]="option"> {{ option }} <option>
</select>
```

In the View Engine runtime, the above code would set the initial value of the `<select>` as expected.
In Ivy, the initial value would not be set at all in this case.

### Background

Prior to Ivy, directive input bindings were always executed in their own change detection pass before any DOM bindings were processed.
This was an implementation detail that supported the use case in question:

```html
<select [value]="someValue">
  <option *ngFor="let option of options" [value]="option"> {{ option }} <option>
</select>
```

It happened to work because the `*ngFor` would be checked first, during the directive input binding pass, and thus create the options first.
Then the DOM binding pass would run, which would check the `value` binding.
At this time, it would be able to match the value against one of the existing options, and set the value of the `<select>` element in the DOM to display that option.

In Ivy, bindings are checked in the order they are defined in the template, regardless of whether they are directive input bindings or DOM bindings.
This change makes change detection easier to reason about for debugging purposes, since bindings will be checked in depth-first order as declared in the template.

In this case, it means that the `value` binding will be checked before the `*ngFor` is checked, as it is declared above the `*ngFor` in the template.
Consequently, the value of the `<select>` element will be set before any options are created, and it won't be able to match and display the correct option in the DOM.

### Example of error

There is no error thrown, but the `<select>` in question will not have the correct initial value displayed in the DOM.

### Recommended fix

To fix this problem, we recommend binding to the `selected` property on the `<option>` instead of the `value` on the `<select>`.

*Before*
```html
<select [value]="someValue">
  <option *ngFor="let option of options" [value]="option"> {{ option }} <option>
</select>
```

*After*
```html
<select>
  <option *ngFor="let option of options" [value]="option" [selected]="someValue == option">
    {{ option }}
  <option>
</select>
```


text:
<?php

namespace Ilios\MeSH\Model;

/**
 * Class TermTest
 * @package Ilios\MeSH\Model
 */
class TermTest extends ReferenceTest
{
    /**
     * @var Term
     */
    protected $object;

    /**
     * @inheritdoc
     */
    public function setUp(): void
    {
        parent::setUp();
        $this->object = new Term();
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::__construct
     */
    public function testConstructor()
    {
        $this->assertEmpty($this->object->getThesaurusIds());
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::isPermuted
     * @covers \Ilios\MeSH\Model\Term::setPermuted
     */
    public function testIsSetPermuted()
    {
        $this->booleanSetTest($this->object, 'permuted', true);
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::isConceptPreferred
     * @covers \Ilios\MeSH\Model\Term::setConceptPreferred
     */
    public function testIsSetConceptPreferred()
    {
        $this->booleanSetTest($this->object, 'conceptPreferred', true);
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::isRecordPreferred
     * @covers \Ilios\MeSH\Model\Term::setRecordPreferred
     */
    public function testIsSetRecordPreferred()
    {
        $this->booleanSetTest($this->object, 'recordPreferred', true);
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getLexicalTag
     * @covers \Ilios\MeSH\Model\Term::setLexicalTag
     */
    public function testGetSetLexicalTag()
    {
        $this->basicSetTest($this->object, 'lexicalTag', 'string');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getAbbreviation
     * @covers \Ilios\MeSH\Model\Term::setAbbreviation
     */
    public function testGetSetAbbreviation()
    {
        $this->basicSetTest($this->object, 'abbreviation', 'string');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getSortVersion
     * @covers \Ilios\MeSH\Model\Term::setSortVersion
     */
    public function testGetSetSortVersion()
    {
        $this->basicSetTest($this->object, 'sortVersion', 'string');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getEntryVersion
     * @covers \Ilios\MeSH\Model\Term::setEntryVersion
     */
    public function testGetSetEntryVersion()
    {
        $this->basicSetTest($this->object, 'entryVersion', 'string');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::addThesaurusId
     * @covers \Ilios\MeSH\Model\Term::getThesaurusIds
     */
    public function testAddGetThesaurusIds()
    {
        $this->addTextToListTest($this->object, 'thesaurusId');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getNote
     * @covers \Ilios\MeSH\Model\Term::setNote
     */
    public function testGetSetNote()
    {
        $this->basicSetTest($this->object, 'note', 'string');
    }

    /**
     * @covers \Ilios\MeSH\Model\Term::getDateCreated
     * @covers \Ilios\MeSH\Model\Term::setDateCreated
     */
    public function testGetDateCreated()
    {
        $this->basicSetTest($this->object, 'dateCreated', 'datetime');
    }
}


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Template10.Common
{
    public enum ActivateWindowSources
    {
        Launching,
        Activating,
        SplashScreen,
        Resuming
    }
}


text:
# <small>nlohmann::basic_json::</small>meta

```cpp
static basic_json meta();
```

This function returns a JSON object with information about the library, including the version number and information on
the platform and compiler.

## Return value

JSON object holding version information

| key         | description                                                                                |
|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `compiler`  | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). |
| `copyright` | The copyright line for the library as string.                                                                                |
| `name`      | The name of the library as string.                                                                                |
| `platform`  | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.                                                                                |
| `url`       | The URL of the project as string.                                                                                |
| `version`   | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).                                                                                |

## Exception safety

Strong guarantee: if an exception is thrown, there are no changes to any JSON value.

## Complexity

Constant.

## Examples

??? example

    The following code shows an example output of the `meta()` function.

    ```cpp
    --8<-- "examples/meta.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/meta.output"
    ```

    Note the output is platform-dependent.

## See also

- [**NLOHMANN_JSON_VERSION_MAJOR**/**NLOHMANN_JSON_VERSION_MINOR**/**NLOHMANN_JSON_VERSION_PATCH**](../macros/nlohmann_json_version_major.md)
  \- library version information

## Version history

- Added in version 2.1.0.


text:
layout: post
title: "Parsing JSON in Android"
categories: Android
share: y
disqus: y
---

As part of the college mini project,  I along with my group, developed a
micro-blogging platform for Android. One of the biggest hurdles I had to face
was of choosing the proper data format for receiving responses from the web
service. I needed something that was fast as well as easy to understand and
parse.  I first chose XML as it was easy to read and mostly because I knew no
other alternatives. But parsing XML certainly wasnt easy. With the variety of
tags in the responses from the server and the heaviness of XML format, it just
became impossible to use it.

That's when [JSON](http://www.json.org/fatfree.html)(JavaScript Object Notation) came up as an alternative to XML. I was circumspect about using JSON at first as I had doubts about its readability and ease of deserialization. But those doubts were not much more than just superstitions. JSON is smaller and easier to parse, than it's XML equivalent. Many say its less readable than XML, but considering it was used for data interchange, readability was not important.

The easiest way to parse JSON and convert to POJO (Plain Old Java Objects) in Android is to use the Google's GSON library.

### Download GSON

Download the latest Google GSON library from [here](http://code.google.com/p/google-gson/). Add this library into your Android Project as an external by right clicking on the desired project and do the following

> Properties -> Java Build Path -> Libraries -> Add External JARs and point to the downloaded gson library.

The following is an array of JSON Objects.  You have to develop a class structure in accordance with the structure of the JSON response received.  For the above example I had the class structure based on the following logic.

{% highlight java %}

{ "posts":
  [
     { "post":
       {
       "username": "John",
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
       }},
     { "post":
       {
       "username": "Smith",
       "message": "I've been waiting",
       "time": "2010-4-6 10:30:26"
       }}]}

{% endhighlight %}

The "posts" data structure contain multiple posts, each of which contains an "post" type. In order to match this structure, I need to have 3 classes namely PostList, PostContainer and Posts. The PostList class should have an ArrayList of objects of type PostContainer. PostContainer needs just one field which is an object of type Posts. Posts classes must have  3 fields namely username, message and time

{% highlight java %}

public class PostList {

private List<PostContainer> posts = new ArrayList<PostContainer>();
public List<PostContainer> getPostContainterList() {
return posts;
}
}

class PostContainer{
Posts post;
public Posts getPost(){
return post;
}
}

public class Posts {
String message;
String time;
String username;
}

{% endhighlight %}

### Deserialization Part

Now let's get into the real business of Deserialization. Using GSON this can be done very easily.

First, import the Google gson library into the class in which JSON String is to be deserialized

{% highlight java %}

import com.google.gson.Gson;

{% endhighlight %}

I am initializing an ArrayList which contains objects of type Posts

{% highlight java %}

private List<Posts> mObjectList = new ArrayList<Posts>() ;

{% endhighlight %}

This can be latter on used for adding the Posts objects after deserialization is done.

{% highlight java %}

String jsonString = "Insert your JSON Data here"

{% endhighlight %}

Instantiate an Object of type PostList

{% highlight java %}

PostList list = null;
list = getPostList(jsonString);

{% endhighlight %}

The following function deserializes JSON response to an Object of type PostList and returns it.

{% highlight java %}

protected PostList getPostList (String jsonString){
PostList pl = null;
Gson gson = new GSON;
pl = gson.fromJson(jsonString, PostList.class);
return pl;
}

{% endhighlight %}
What the function getPostList does is, it creates an object of type GSON and deserialize the JSON String to POJO using that object(gson).

{% highlight java %}

gson.fromJson(jsonString, PostList.class)

{% endhighlight %}
The first parameter to the function is the JSON String and second parameter is the name of the class to which it should be deserialized. Two important things have to be taken care of while using GSON to parse JSON

 1. Tags in JSON String and name of fields of the respective classes should match exactly.

 2. Object hierarchy should be built correctly.

Failure to comply to the both conditions above would result in some or all of the fields of the classes being left null.

Having parsed the JSON string to POJO, we can get various Posts objects separately and add it to the ArrayList which we created earlier as follows.

{% highlight java %}
List <PostContainer> post_list = list.getPostContainterList();
PostContainer pc;
for (int i = 0; i < post_list.size(); i++) {
    pc = post_list.get(i);
    mObjectList.add(pc.getPost());
{% endhighlight %}

This ArrayList can be used to populate a custom list view. If you have any doubts regarding this post, feel free to ask through comments. In the next post, I will post an tutorial on how to build a custom listview which looks the twitter timeline efficiently.


text:
#ifndef __PANGO_GLYPH_ITEM_H__
#define __PANGO_GLYPH_ITEM_H__

#include <pango/pango-attributes.h>
#include <pango/pango-break.h>
#include <pango/pango-item.h>
#include <pango/pango-glyph.h>

G_BEGIN_DECLS

/**
 * PangoGlyphItem:
 *
 * A #PangoGlyphItem is a pair of a #PangoItem and the glyphs
 * resulting from shaping the text corresponding to an item.
 * As an example of the usage of #PangoGlyphItem, the results
 * of shaping text with #PangoLayout is a list of #PangoLayoutLine,
 * each of which contains a list of #PangoGlyphItem.
 */
typedef struct _PangoGlyphItem PangoGlyphItem;

struct _PangoGlyphItem
{
  PangoItem        *item;
  PangoGlyphString *glyphs;
};

/**
 * PANGO_TYPE_GLYPH_ITEM:
 *
 * The #GObject type for #PangoGlyphItem.
 */
#define PANGO_TYPE_GLYPH_ITEM (pango_glyph_item_get_type ())

GType pango_glyph_item_get_type (void) G_GNUC_CONST;

PangoGlyphItem *pango_glyph_item_split        (PangoGlyphItem *orig,
					       const char     *text,
					       int             split_index);
PangoGlyphItem *pango_glyph_item_copy         (PangoGlyphItem *orig);
void            pango_glyph_item_free         (PangoGlyphItem *glyph_item);
GSList *        pango_glyph_item_apply_attrs  (PangoGlyphItem *glyph_item,
					       const char     *text,
					       PangoAttrList  *list);
void            pango_glyph_item_letter_space (PangoGlyphItem *glyph_item,
					       const char     *text,
					       PangoLogAttr   *log_attrs,
					       int             letter_spacing);
void 	  pango_glyph_item_get_logical_widths (PangoGlyphItem *glyph_item,
					       const char     *text,
					       int            *logical_widths);

/**
 * PangoGlyphItemIter:
 *
 * A #PangoGlyphItemIter is an iterator over the clusters in a
 * #PangoGlyphItem.  The <firstterm>forward direction</firstterm> of the
 * iterator is the logical direction of text.  That is, with increasing
 * @start_index and @start_char values.  If @glyph_item is right-to-left
 * (that is, if <literal>@glyph_item->item->analysis.level</literal> is odd),
 * then @start_glyph decreases as the iterator moves forward.  Moreover,
 * in right-to-left cases, @start_glyph is greater than @end_glyph.
 *
 * An iterator should be initialized using either of
 * pango_glyph_item_iter_init_start() and
 * pango_glyph_item_iter_init_end(), for forward and backward iteration
 * respectively, and walked over using any desired mixture of
 * pango_glyph_item_iter_next_cluster() and
 * pango_glyph_item_iter_prev_cluster().  A common idiom for doing a
 * forward iteration over the clusters is:
 * <programlisting>
 * PangoGlyphItemIter cluster_iter;
 * gboolean have_cluster;
 *
 * for (have_cluster = pango_glyph_item_iter_init_start (&cluster_iter,
 *                                                       glyph_item, text);
 *      have_cluster;
 *      have_cluster = pango_glyph_item_iter_next_cluster (&cluster_iter))
 * {
 *   ...
 * }
 * </programlisting>
 *
 * Note that @text is the start of the text for layout, which is then
 * indexed by <literal>@glyph_item->item->offset</literal> to get to the
 * text of @glyph_item.  The @start_index and @end_index values can directly
 * index into @text.  The @start_glyph, @end_glyph, @start_char, and @end_char
 * values however are zero-based for the @glyph_item.  For each cluster, the
 * item pointed at by the start variables is included in the cluster while
 * the one pointed at by end variables is not.
 *
 * None of the members of a #PangoGlyphItemIter should be modified manually.
 *
 * Since: 1.22
 */
typedef struct _PangoGlyphItemIter PangoGlyphItemIter;

struct _PangoGlyphItemIter
{
  PangoGlyphItem *glyph_item;
  const gchar *text;

  int start_glyph;
  int start_index;
  int start_char;

  int end_glyph;
  int end_index;
  int end_char;
};

/**
 * PANGO_TYPE_GLYPH_ITEM_ITER:
 *
 * The #GObject type for #PangoGlyphItemIter.
 *
 * Since: 1.22
 */
#define PANGO_TYPE_GLYPH_ITEM_ITER (pango_glyph_item_iter_get_type ())

GType               pango_glyph_item_iter_get_type (void) G_GNUC_CONST;
PangoGlyphItemIter *pango_glyph_item_iter_copy (PangoGlyphItemIter *orig);
void                pango_glyph_item_iter_free (PangoGlyphItemIter *iter);

gboolean pango_glyph_item_iter_init_start   (PangoGlyphItemIter *iter,
					     PangoGlyphItem     *glyph_item,
					     const char         *text);
gboolean pango_glyph_item_iter_init_end     (PangoGlyphItemIter *iter,
					     PangoGlyphItem     *glyph_item,
					     const char         *text);
gboolean pango_glyph_item_iter_next_cluster (PangoGlyphItemIter *iter);
gboolean pango_glyph_item_iter_prev_cluster (PangoGlyphItemIter *iter);

G_END_DECLS

#endif /* __PANGO_GLYPH_ITEM_H__ */


text:
package org.jmeterplugins.repository;

import kg.apc.emulators.TestJMeterUtils;
import org.apache.jmeter.util.JMeterUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.net.URL;
import java.util.LinkedList;

import static junit.framework.Assert.assertEquals;
import static junit.framework.TestCase.fail;

public class PluginManagerCMDTest {
    @BeforeClass
    public static void setup() {
        TestJMeterUtils.createJmeterEnv();
        URL url = PluginManagerTest.class.getResource("/testVirtualPlugin.json");
        JMeterUtils.setProperty("jpgc.repo.address", url.getFile());
    }

    @AfterClass
    public static void tearDown() throws Exception {
        JMeterUtils.getJMeterProperties().remove("jpgc.repo.address");
    }

    @Test
    public void processParams_status() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("status");
        cmd.processParams(params.listIterator());
    }

    @Test
    public void processParams_install() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("install");
        try {
            cmd.processParams(params.listIterator());
            fail();
        } catch (IllegalArgumentException ignored) {
        }
        params.add("jpgc-dep1,jpgc-dep2=2.0");
        cmd.processParams(params.listIterator());
    }

    @Test
    public void processParams_install_all() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("install-all-except");
        cmd.processParams(params.listIterator());
        params.add("jpgc-dep1,jpgc-dep2=2.0");
        cmd.processParams(params.listIterator());
    }

    @Test
    public void processParams_install_invalid() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("install");
        params.add("jpgc-invalid");
        try {
            cmd.processParams(params.listIterator());
            fail();
        } catch (RuntimeException ignored) {
        }
    }

    @Test
    public void processParams_uninstall() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("uninstall");
        try {
            cmd.processParams(params.listIterator());
            fail();
        } catch (IllegalArgumentException ignored) {
        }
        params.add("jpgc-dep1,jpgc-dep2=2.0");
        cmd.processParams(params.listIterator());
    }

    @Test
    public void showHelp() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();

        LinkedList<String> params = new LinkedList<>();
        params.add("help");
        int code = cmd.processParams(params.listIterator());
        assertEquals(0, code);

        params.clear();
        params.add("help me pls");
        try {
            cmd.processParams(params.listIterator());
        } catch (Throwable ex) {
            //
        }

        params.clear();
        try {
            cmd.processParams(params.listIterator());
        } catch (IllegalArgumentException ex) {
            //
        }
    }

    @Test
    public void testAvailable() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("available");
        int code = cmd.processParams(params.listIterator());
        assertEquals(0, code);
    }

    @Test
    public void testUpgrades() throws Exception {
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("upgrades");
        int code = cmd.processParams(params.listIterator());
        assertEquals(0, code);
    }

    @Test
    public void testInstallPluginsForJMX() throws Exception {
        JMeterUtils.getJMeterProperties().remove("jpgc.repo.address");
        String path = getClass().getResource("/testplan.xml").getPath();
        PluginManagerCMD cmd = new PluginManagerCMD();
        LinkedList<String> params = new LinkedList<>();
        params.add("install-for-jmx");
        params.add(path);
        int code = cmd.processParams(params.listIterator());
        assertEquals(0, code);
    }
}


text:
package com.siyeh.ig.style;

import javax.annotation.Nonnull;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import consulo.java.module.util.JavaClassNames;

public class ExtendsObjectInspection extends BaseInspection {

  @Override
  @Nonnull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("extends.object.display.name");
  }

  @Override
  @Nonnull
  public String getID() {
    return "ClassExplicitlyExtendsObject";
  }

  @Override
  @Nonnull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message(
      "extends.object.problem.descriptor");
  }

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

  @Override
  protected InspectionGadgetsFix buildFix(Object... infos) {
    return new ExtendsObjectFix();
  }

  private static class ExtendsObjectFix extends InspectionGadgetsFix {

    @Nonnull
    public String getName() {
      return InspectionGadgetsBundle.message(
        "extends.object.remove.quickfix");
    }

    @Override
    public void doFix(@Nonnull Project project, ProblemDescriptor descriptor)
      throws IncorrectOperationException {
      final PsiElement extendClassIdentifier = descriptor.getPsiElement();
      final PsiClass element =
        (PsiClass)extendClassIdentifier.getParent();
      if (element == null) {
        return;
      }
      final PsiReferenceList extendsList = element.getExtendsList();
      if (extendsList == null) {
        return;
      }
      final PsiJavaCodeReferenceElement[] referenceElements =
        extendsList.getReferenceElements();
      for (PsiJavaCodeReferenceElement referenceElement :
        referenceElements) {
        deleteElement(referenceElement);
      }
    }
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new ExtendsObjectVisitor();
  }

  private static class ExtendsObjectVisitor extends BaseInspectionVisitor {

    @Override
    public void visitClass(@Nonnull PsiClass aClass) {
      if (aClass.isInterface() || aClass.isAnnotationType()) {
        return;
      }
      if (aClass instanceof PsiTypeParameter) {
        return;
      }
      final PsiClassType[] types = aClass.getExtendsListTypes();
      for (final PsiClassType type : types) {
        if (type.equalsToText(JavaClassNames.JAVA_LANG_OBJECT)) {
          registerClassError(aClass);
        }
      }
    }
  }
}


text:
package transactionapi

import (
	"gost/api"
	"gost/auth/identity"
	"gost/dal/service/transactionservice"
	"net/http"

	"errors"

	"gopkg.in/mgo.v2/bson"
)

// Errors returned by the transactionapi
var (
	ErrTransactionNotFound = errors.New("There is no transaction with the specified ID")
)

// getTransaction endpoint retrieves a certain transaction based on its Id
func getTransaction(transactionID bson.ObjectId) api.Response {
	dbTransaction, err := transactionservice.GetTransaction(transactionID)
	if err != nil || dbTransaction == nil {
		return api.NotFound(ErrTransactionNotFound)
	}

	payer, _ := identity.GetUser(dbTransaction.PayerID)
	receiver, _ := identity.GetUser(dbTransaction.PayerID)
	transaction := NewFrom(dbTransaction, payer, receiver)

	return api.JSONResponse(http.StatusOK, transaction)
}

// createTransaction endpoint creates a new transaction with the valid transfer tokens and data
func createTransaction(transaction *Transaction) api.Response {
	var dbTransaction = transaction.ToDalModel()

	err := transactionservice.CreateTransaction(dbTransaction)
	if err != nil {
		return api.InternalServerError(err)
	}
	transaction.ID = dbTransaction.ID

	return api.JSONResponse(http.StatusCreated, transaction)
}


text:
var path = require('path');
var gulp = require('gulp');
var concat = require('gulp-concat');
var argv = require('yargs').argv;
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var babel = require('gulp-babel');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var streamqueue = require('streamqueue');

function handleError(e) {
  console.log(e.toString());
  this.emit('end');
}

module.exports = function(options) {
  options = options || {};

  options.files = options.files || [];
  options.modules = options.modules || {};
  options.outputFile = options.outputFile || 'dist/extension.js';
  options.externalHelpers = typeof options.externalHelpers === 'undefined' ? true : options.externalHelpers;

  gulp.task('default', function() {
    var stream = streamqueue({objectMode: true});

    stream.queue(gulp.src(options.files));

    for (var prefix in options.modules) {
      stream.queue(
        gulp.src(options.modules[prefix])
          .pipe(cached('modules'))
          .pipe(babel({
            modules: 'system',
            moduleIds: true,
            moduleRoot: prefix,
            externalHelpers: options.externalHelpers,
            jsxPragma: 'm',
            plugins: [require('babel-plugin-object-assign')]
          }))
          .on('error', handleError)
          .pipe(remember('modules'))
      );
    }

    return stream.done()
      .pipe(concat(path.basename(options.outputFile), {newLine: ';\n'}))
      .pipe(gulpif(argv.production, uglify()))
      .pipe(gulp.dest(path.dirname(options.outputFile)));
  });

  gulp.task('watch', ['default'], function () {
    gulp.watch(options.files, ['default']);

    for (var prefix in options.modules) {
      var watcher = gulp.watch(options.modules[prefix], ['default']);

      watcher.on('change', function (event) {
        if (event.type === 'deleted') {
          delete cached.caches['modules' + prefix][event.path];
          remember.forget('modules' + prefix, event.path);
        }
      });
    }
  });
};


text:
export default ['IgniteVersion', 'SpringTransformer', function(Version, spring) {
    const ctrl = this;

    delete ctrl.data;

    const targetSince = Version.available.bind(Version);

    // Setup generator.
    switch (ctrl.generator) {
        case 'igniteConfiguration':
            ctrl.generate = (cluster) => spring.cluster(cluster, Version.current, ctrl.client === 'true');

            break;
        case 'clusterCaches':
            ctrl.generate = (cluster, caches) => {
                const clusterCaches = _.reduce(caches, (acc, cache) => {
                    if (_.includes(cluster.caches, cache.value))
                        acc.push(cache.cache);

                    return acc;
                }, []);

                const cfg = spring.generator.clusterGeneral(cluster, targetSince);

                spring.generator.clusterCaches(cluster, clusterCaches, null, targetSince, false, cfg);

                return spring.toSection(cfg);
            };

            break;
        case 'cacheStore':
        case 'cacheQuery':
            ctrl.generate = (cache, domains) => {
                const cacheDomains = _.reduce(domains, (acc, domain) => {
                    if (_.includes(cache.domains, domain.value))
                        acc.push(domain.meta);

                    return acc;
                }, []);

                return spring[ctrl.generator](cache, cacheDomains, targetSince);
            };

            break;
        case 'cacheNodeFilter':
            ctrl.generate = (cache, igfss) => {
                const cacheIgfss = _.reduce(igfss, (acc, igfs) => {
                    acc.push(igfs.igfs);

                    return acc;
                }, []);

                return spring.cacheNodeFilter(cache, cacheIgfss);
            };

            break;
        case 'clusterServiceConfiguration':
            ctrl.generate = (cluster, caches) => {
                const clusterCaches = _.reduce(caches, (acc, cache) => {
                    if (_.includes(cluster.caches, cache.value))
                        acc.push(cache.cache);

                    return acc;
                }, []);

                return spring.clusterServiceConfiguration(cluster.serviceConfigurations, clusterCaches);
            };

            break;
        case 'igfss':
            ctrl.generate = (cluster, igfss) => {
                const clusterIgfss = _.reduce(igfss, (acc, igfs) => {
                    if (_.includes(cluster.igfss, igfs.value))
                        acc.push(igfs.igfs);

                    return acc;
                }, []);

                return spring.clusterIgfss(clusterIgfss, targetSince);
            };

            break;
        default:
            ctrl.generate = (master) => spring[ctrl.generator](master, targetSince);
    }
}];


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>establishment</type>
  <type>point_of_interest</type>
  <formatted_address>Mimar Sinan Mahallesi, Ağadere Cad. No:14, 41780 Körfez/Kocaeli (Izmit), Turkey</formatted_address>
  <address_component>
   <long_name>14</long_name>
   <short_name>14</short_name>
   <type>street_number</type>
  </address_component>
  <address_component>
   <long_name>Ağadere Cad.</long_name>
   <short_name>Ağadere Cad.</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Mimar Sinan Mahallesi</long_name>
   <short_name>Mimar Sinan Mahallesi</short_name>
   <type>administrative_area_level_4</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Körfez</long_name>
   <short_name>Körfez</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Kocaeli (Izmit)</long_name>
   <short_name>Kocaeli (Izmit)</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Turkey</long_name>
   <short_name>TR</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>41780</long_name>
   <short_name>41780</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>40.7578402</lat>
    <lng>29.7594437</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>40.7564912</lat>
     <lng>29.7580947</lng>
    </southwest>
    <northeast>
     <lat>40.7591892</lat>
     <lng>29.7607927</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJtdbN-YE4yxQR3Lt4hMcArr4</place_id>
 </result>
</GeocodeResponse>


text:
@interface QCFlameImage : QCPatch
{
	QCColorPort *inputColorStart;	// 156 = 0x9c
	QCColorPort *inputColorMiddle;	// 160 = 0xa0
	QCColorPort *inputColorEnd;	// 164 = 0xa4
	QCImagePort *outputImage;	// 168 = 0xa8
	NSUInteger _width;	// 172 = 0xac
	NSUInteger _height;	// 176 = 0xb0
	BOOL _colorCorrection;	// 180 = 0xb4
	unsigned int _clut[256];	// 184 = 0xb8
	char *_bufferAddress;	// 1208 = 0x4b8
	NSUInteger _bufferRowBytes;	// 1212 = 0x4bc
	GLuint _target;	// 1216 = 0x4c0
	NSUInteger _mipmapLevels;	// 1220 = 0x4c4
}

+ (BOOL)isSafe;
+ (QCPatchExecutionMode)executionModeWithIdentifier:(id)identifier;
+ (BOOL)allowsSubpatchesWithIdentifier:(id)fp8;
+ (id)stateKeysWithIdentifier:(id)fp8;
- (id)initWithIdentifier:(id)fp8;
- (void)setWidth:(NSUInteger)fp8 height:(NSUInteger)fp12;
- (NSUInteger)width;
- (NSUInteger)height;
- (NSDictionary*)state;
- (BOOL)setState:(NSDictionary*)state;
- (BOOL)setup:(QCOpenGLContext *)context;
- (BOOL)execute:(QCOpenGLContext*)context time:(double)time arguments:(NSDictionary*)args;
- (void)cleanup:(QCOpenGLContext *)context;
@end

@interface QCFlameImage (QCInspector)
+ (Class)inspectorClassWithIdentifier:(id)fp8;
@end


text:
package com.github.mkopylec.rpggame.domain.services;

import com.github.mkopylec.ddd.buildingblocks.DomainService;
import com.github.mkopylec.rpggame.domain.hero.Hero;
import com.github.mkopylec.rpggame.domain.world.Enemy;

@DomainService
public class BattleSimulator {

    public void performBattle(Hero hero, Enemy enemy) {
        BattleParticipant attacker = hero;
        BattleParticipant defender = enemy;

        while (areOpponentsAlive(hero, enemy)) {
            int attackDamage = attacker.getAttackDamage();
            defender.receiveAttack(attackDamage);

            attacker = changeBattleRole(attacker, hero, enemy);
            defender = changeBattleRole(defender, hero, enemy);
        }
    }

    private boolean areOpponentsAlive(Hero hero, Enemy enemy) {
        return hero.isAlive() && enemy.isAlive();
    }

    private BattleParticipant changeBattleRole(BattleParticipant participant, Hero hero, Enemy enemy) {
        return participant.equals(hero)
                ? enemy
                : hero;
    }
}


text:
def can_build(env, platform):
    return True

def configure(env):
    pass

def get_doc_classes():
    return [
        "ResourceImporterTheora",
        "VideoStreamTheora",
    ]

def get_doc_path():
    return "doc_classes"


text:
class Gws::Notice::TrashesController < ApplicationController
  include Gws::BaseFilter
  include Gws::CrudFilter

  before_action :set_items
  before_action :set_item, only: [:show, :delete, :destroy, :undo_delete]
  before_action :set_selected_items, only: [:destroy_all, :soft_delete_all]

  model Gws::Notice::Post

  navi_view "gws/notice/main/navi"

  private

  def set_crumbs
    @crumbs << [t("mongoid.models.gws/notice/post"), gws_notice_main_path]
    @crumbs << [t('ss.navi.trash'), action: :index]
  end

  def fix_params
    { cur_user: @cur_user, cur_site: @cur_site }
  end

  def set_items
    @items = @model.site(@cur_site).
      allow(:read, @cur_user, site: @cur_site).
      only_deleted.
      search(params[:s])
  end

  def set_item
    @item ||= begin
      item = @items.find(params[:id])
      item.attributes = fix_params
      item
    end
  rescue Mongoid::Errors::DocumentNotFound => e
    return render_destroy(true) if params[:action] == 'destroy'
    raise e
  end

  def set_selected_items
    ids = params[:ids]
    raise "400" unless ids
    ids = ids.split(",") if ids.is_a?(String)
    @items = @items.in(id: ids)
    raise "400" unless @items.present?
  end

  public

  def index
    @items = @items.page(params[:page]).per(50)
  end
end


text:
<?php

namespace Ledjin\Sagepay\Action;

use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Request\GetStatusInterface;
use Payum\Core\Exception\RequestNotSupportedException;
use Ledjin\Sagepay\Api;
use Ledjin\Sagepay\Api\State\StateInterface;

class StatusAction implements ActionInterface, StateInterface
{
    /**
     * {@inheritDoc}
     *
     * @param GetStatusInterface $request
     */

    /**
     * {@inheritDoc}
     *
     * @param GetStatusInterface $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = new ArrayObject($request->getModel());

        $state = $model['state'];

        if (null === $state ||
            self::STATE_WAITING === $state
        ) {
            $request->markNew();

            return;
        }

        if (self::STATE_REPLIED === $state ||
            self::STATE_NOTIFIED === $state
        ) {
            $request->markPending();

            return;
        }

        if (self::STATE_CONFIRMED === $state) {
            $request->markCaptured();

            return;
        }

        $request->markFailed();
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof GetStatusInterface &&
            $request->getModel() instanceof \ArrayAccess
        ;
    }
}


text:
namespace midi {

namespace {

enum {
  kDefaultRunner = TaskService::kDefaultRunnerId,
  kFirstRunner,
  kSecondRunner
};

base::WaitableEvent* GetEvent() {
  static base::WaitableEvent* event =
      new base::WaitableEvent(base::WaitableEvent::ResetPolicy::MANUAL,
                              base::WaitableEvent::InitialState::NOT_SIGNALED);
  return event;
}

void SignalEvent() {
  GetEvent()->Signal();
}

void WaitEvent() {
  GetEvent()->Wait();
}

void ResetEvent() {
  GetEvent()->Reset();
}

class TaskServiceClient {
 public:
  TaskServiceClient(TaskService* task_service)
      : task_service_(task_service),
        wait_task_event_(std::make_unique<base::WaitableEvent>(
            base::WaitableEvent::ResetPolicy::MANUAL,
            base::WaitableEvent::InitialState::NOT_SIGNALED)),
        count_(0u) {
    DCHECK(task_service);
  }

  bool Bind() { return task_service()->BindInstance(); }

  bool Unbind() { return task_service()->UnbindInstance(); }

  void PostBoundTask(TaskService::RunnerId runner_id) {
    task_service()->PostBoundTask(
        runner_id, base::BindOnce(&TaskServiceClient::IncrementCount,
                                  base::Unretained(this)));
  }

  void PostBoundSignalTask(TaskService::RunnerId runner_id) {
    task_service()->PostBoundTask(
        runner_id, base::BindOnce(&TaskServiceClient::SignalEvent,
                                  base::Unretained(this)));
  }

  void PostBoundWaitTask(TaskService::RunnerId runner_id) {
    wait_task_event_->Reset();
    task_service()->PostBoundTask(
        runner_id,
        base::BindOnce(&TaskServiceClient::WaitEvent, base::Unretained(this)));
  }

  void PostBoundDelayedSignalTask(TaskService::RunnerId runner_id) {
    task_service()->PostBoundDelayedTask(
        runner_id,
        base::BindOnce(&TaskServiceClient::SignalEvent, base::Unretained(this)),
        base::Milliseconds(100));
  }

  void WaitTask() { wait_task_event_->Wait(); }

  size_t count() {
    base::AutoLock lock(lock_);
    return count_;
  }

 private:
  TaskService* task_service() { return task_service_; }

  void IncrementCount() {
    base::AutoLock lock(lock_);
    count_++;
  }

  void SignalEvent() {
    IncrementCount();
    midi::SignalEvent();
  }

  void WaitEvent() {
    IncrementCount();
    wait_task_event_->Signal();
    midi::WaitEvent();
  }

  base::Lock lock_;
  TaskService* task_service_;
  std::unique_ptr<base::WaitableEvent> wait_task_event_;
  size_t count_;

  DISALLOW_COPY_AND_ASSIGN(TaskServiceClient);
};

class MidiTaskServiceTest : public ::testing::Test {
 public:
  MidiTaskServiceTest() = default;

 protected:
  TaskService* task_service() { return &task_service_; }
  void RunUntilIdle() { task_runner_->RunUntilIdle(); }

 private:
  void SetUp() override {
    ResetEvent();
    task_runner_ = new base::TestSimpleTaskRunner();
    thread_task_runner_handle_ =
        std::make_unique<base::ThreadTaskRunnerHandle>(task_runner_);
  }

  void TearDown() override {
    thread_task_runner_handle_.reset();
    task_runner_.reset();
  }

  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
  std::unique_ptr<base::ThreadTaskRunnerHandle> thread_task_runner_handle_;
  TaskService task_service_;

  DISALLOW_COPY_AND_ASSIGN(MidiTaskServiceTest);
};

// Tests if posted tasks without calling BindInstance() are ignored.
TEST_F(MidiTaskServiceTest, RunUnauthorizedBoundTask) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  client->PostBoundTask(kFirstRunner);

  // Destruct |client| immediately, then see if the posted task is just ignored.
  // If it isn't, another thread will touch the destructed instance and will
  // cause a crash due to a use-after-free.
  client = nullptr;
}

// Tests if invalid BindInstance() calls are correctly rejected, and it does not
// make the service insanity.
TEST_F(MidiTaskServiceTest, BindTwice) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());

  // Should not be able to call BindInstance() twice before unbinding current
  // bound instance.
  EXPECT_FALSE(client->Bind());

  // Should be able to unbind only the first instance.
  EXPECT_TRUE(client->Unbind());
  EXPECT_FALSE(client->Unbind());
}

// Tests if posted static tasks can be processed correctly.
TEST_F(MidiTaskServiceTest, RunStaticTask) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());
  // Should be able to post a static task while an instance is bound.
  task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
  WaitEvent();
  EXPECT_TRUE(client->Unbind());

  ResetEvent();

  EXPECT_TRUE(client->Bind());
  task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
  // Should be able to unbind the instance to process a static task.
  EXPECT_TRUE(client->Unbind());
  WaitEvent();

  ResetEvent();

  // Should be able to post a static task without a bound instance.
  task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
  WaitEvent();
}

// Tests functionalities to run bound tasks.
TEST_F(MidiTaskServiceTest, RunBoundTasks) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());

  // Tests if a post task run.
  EXPECT_EQ(0u, client->count());
  client->PostBoundSignalTask(kFirstRunner);
  WaitEvent();
  EXPECT_EQ(1u, client->count());

  // Tests if another posted task is handled correctly even if the instance is
  // unbound immediately. The posted task should run safely if it starts before
  // UnboundInstance() is call. Otherwise, it should be ignored. It completely
  // depends on timing.
  client->PostBoundTask(kFirstRunner);
  EXPECT_TRUE(client->Unbind());
  client = std::make_unique<TaskServiceClient>(task_service());

  // Tests if an immediate call of another BindInstance() works correctly.
  EXPECT_TRUE(client->Bind());

  // Runs two tasks in two runners.
  ResetEvent();
  client->PostBoundSignalTask(kFirstRunner);
  client->PostBoundTask(kSecondRunner);

  // Waits only the first runner completion to see if the second runner handles
  // the task correctly even if the bound instance is destructed.
  WaitEvent();
  EXPECT_TRUE(client->Unbind());
  client = nullptr;
}

// Tests if a blocking task does not block other task runners.
TEST_F(MidiTaskServiceTest, RunBlockingTask) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());

  // Posts a task that waits until the event is signaled.
  client->PostBoundWaitTask(kFirstRunner);
  // Confirms if the posted task starts. Now, the task should block in the task
  // until the second task is invoked.
  client->WaitTask();

  // Posts another task to the second runner. The task should be able to run
  // even though another posted task is blocking inside a critical section that
  // protects running tasks from an instance unbinding.
  client->PostBoundSignalTask(kSecondRunner);

  // Wait until the second task runs.
  WaitEvent();

  // UnbindInstance() should wait until any running task finishes so that the
  // instance can be destructed safely.
  EXPECT_TRUE(client->Unbind());
  EXPECT_EQ(2u, client->count());
  client = nullptr;
}

// Tests if a bound delayed task runs correctly.
TEST_F(MidiTaskServiceTest, RunBoundDelayedTask) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());

  // Posts a delayed task that signals after 100msec.
  client->PostBoundDelayedSignalTask(kFirstRunner);

  // Wait until the delayed task runs.
  WaitEvent();

  EXPECT_TRUE(client->Unbind());
  EXPECT_EQ(1u, client->count());
  client = nullptr;
}

// Tests if a bound task runs on the thread that bound the instance.
TEST_F(MidiTaskServiceTest, RunBoundTaskOnDefaultRunner) {
  std::unique_ptr<TaskServiceClient> client =
      std::make_unique<TaskServiceClient>(task_service());

  EXPECT_TRUE(client->Bind());

  // Posts a task that increments the count on the caller thread.
  client->PostBoundTask(kDefaultRunner);

  // The posted task should not run until the current message loop is processed.
  EXPECT_EQ(0u, client->count());
  RunUntilIdle();
  EXPECT_EQ(1u, client->count());

  EXPECT_TRUE(client->Unbind());
}

}  // namespace

}  // namespace midi


text:
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace DsAdmin
{
    public class DAO
    {
        private SqlConnection conn;
        private SqlTransaction transaction;

        public DAO()
        {

            conn = new SqlConnection("Data Source=sql.servidor.homologacao;Initial Catalog=PreventCataclysmSystems;User ID=danilo;Password='danilo123*';");
            conn.Open();
            transaction = conn.BeginTransaction();
        }

        public DbCommand InicializaProcedure(String procedure)
        {
            DbCommand cmd = new System.Data.SqlClient.SqlCommand(procedure, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Transaction = transaction;

            return cmd;
        }

        public DataSet ConsultaQueryDataSet(DbCommand comando, String tabela)
        {
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter((SqlCommand)comando);
            da.Fill(ds);
            ds.Tables[0].TableName = tabela;
            return ds;
        }

        public int ExecutaNonQuery(DbCommand commando)
        {
            try
            {
                return commando.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
        }

        public void Fechar()
        {
            conn.Close();
            conn.Dispose();
        }

        public void Commit()
        {
            if (transaction.Connection != null)
            {
                transaction.Commit();
            }
        }

        public bool IsClosed
        {
            get { return conn.State == ConnectionState.Closed; }
        }

        public void Rollback()
        {
            if (transaction.Connection != null)
            {
                transaction.Rollback();
            }
        }
    }
}