text:
module("Api", {
  'setup': function() {
    BMTestUtils.ApiPre = BMTestUtils.getAllElements();
  },
  'teardown': function(assert) {

    // Do not ignore intermittent failures in this test --- you
    // risk breaking the entire suite in hard-to-debug ways
    assert.equal(jQuery.active, 0,
      "All test functions MUST complete jQuery activity before exiting");

    // Delete all elements we expect this module to create
    delete Api.test_data;
    delete Api.button;
    delete Api.buttonSet;
    delete Api.player;
    delete Api.new_games;
    delete Api.active_games;
    delete Api.completed_games;
    delete Api.cancelled_games;
    delete Api.user_prefs;
    delete Api.game;
    delete Api.gameNavigation;
    delete Api.forumNavigation;
    delete Api.game_history;
    delete Api.siteConfig;
    delete Api.forum_overview;
    delete Api.forum_board;
    delete Api.forum_thread;
    delete Api.open_games;
    delete Api.join_game_result;
    delete Api.active_players;
    delete Api.profile_info;
    delete Api.pending_games;
    delete Env.message;
    BMTestUtils.deleteEnvMessage();

    Api.automatedApiCall = false;

    // Page elements (for test use only)
    $('#api_page').remove();

    // Fail if any other elements were added or removed
    BMTestUtils.ApiPost = BMTestUtils.getAllElements();
    assert.deepEqual(
      BMTestUtils.ApiPost, BMTestUtils.ApiPre,
      "After testing, the page should have no unexpected element changes");
  }
});

// pre-flight test of whether the Api module has been loaded
test("test_Api_is_loaded", function(assert) {
  expect(3); // number of tests plus 2 for the teardown test
  assert.ok(Api, "The Api namespace exists");
});

test("test_Api.parseApiPost_automatedApiCall", function(assert) {
  stop(2); // this test has two async calls that need to resolve separately
  expect(4); // tests + 2 teardown

  Api.automatedApiCall = true;

  // Api.getGameData calls Api.parseApiPost
  var gameId = BMTestUtils.testGameId('frasquito_wiseman_specifydice');
  Api.getGameData(gameId, 10, function() {
    assert.equal(Api.game.load_status, 'ok',
      'getGameData should be a valid automated API call');
    start();
  });

  // Api.getUserPrefsData calls Api.parseApiPost
  Api.getUserPrefsData(function() {
    assert.notEqual(Api.game.user_prefs, 'ok',
      'getUserPrefsData should not be a valid automated API call');
    start();
  });

});

test("test_Api.parseGenericData", function(assert) {
  expect(3); // number of tests plus 2 for the teardown test

  var apiKey = 'test_data';
  Api[apiKey] = { };
  var data = { 'value': 37 };
  Api.parseGenericData(data, apiKey);
  assert.equal(Api.test_data.value, 37, 'Data value should be set on the Api object');
});

test("test_Api.verifyApiData", function(assert) {
  expect(4); // number of tests plus 2 for the teardown test

  var apiKey = 'test_data';

  Env.message = undefined;
  var message = undefined;
  Api.verifyApiData(apiKey, function(assert) {
    message = Env.message;
  });
  assert.equal(message.type, 'error', 'Should error if data is missing');

  Env.message = undefined;
  message = undefined;
  Api[apiKey] = { 'load_status': 'ok' };
  Api.verifyApiData(apiKey, function() {
    message = Env.message;
  });
  assert.equal(message, undefined, 'Should not error if data is present');
});

test("test_Api.getButtonData", function(assert) {
  stop();
  expect(6); // number of tests plus 2 for the teardown test
  Api.getButtonData(null, function() {
    assert.equal(Api.button.load_status, "ok", "Api.button.load_status should be ok");
    assert.equal(typeof Api.button.list, "object",
          "Api.button.list should be an object");
    assert.deepEqual(
      Api.button.list["Avis"],
      {
        'buttonId': 256,
        'buttonName': 'Avis',
        'hasUnimplementedSkill': false,
        'recipe': '(4) (4) (10) (12) (X)',
        'buttonSet': 'Soldiers',
        'dieTypes': [ 'X Swing', ],
        'dieSkills': [],
        'isTournamentLegal': true,
        'artFilename': 'avis.png',
        'tags': [ ],
      },
      "Button Avis should have correct contents");
    assert.deepEqual(Env.message, undefined,
              "Api.getButtonData should not set Env.message");
    start();
  });
});

test("test_Api.getPlayerData", function(assert) {
  stop();
  expect(6); // number of tests plus 2 for the teardown test
  Api.getPlayerData(function() {
    assert.equal(Api.player.load_status, "ok", "Api.player.load_status should be ok");
    assert.equal(typeof Api.player.list, "object",
          "Api.player.list should be an object");
    assert.deepEqual(
      Api.player.list["tester2"],
      {'status': 'ACTIVE', },
      "Player tester2 should have correct contents");
    assert.deepEqual(Env.message, undefined,
              "Api.getPlayerData should not set Env.message");
    start();
  });
});

test("test_Api.parseButtonData", function(assert) {
  expect(5); // number of tests plus 2 for the teardown test

  Api.button = {};
  var retval = Api.parseButtonData([
    {
      'buttonName': 'Avis',
      'recipe': '(4) (4) (10) (12) (X)',
      'hasUnimplementedSkill': false,
      'buttonSet': 'Soldiers',
      'dieTypes': [ 'X Swing', ],
      'dieSkills': [],
      'isTournamentLegal': true,
      'artFilename': 'avis.png',
    },
    {
      'buttonName': 'Adam Spam',
      'recipe': 'F(4) F(6) (6) (12) (X)',
      'hasUnimplementedSkill': true,
      'buttonSet': 'Polycon',
      'dieTypes': [ 'X Swing', ],
      'dieSkills': [ 'Fire', ],
      'isTournamentLegal': true,
      'artFilename': 'adamspam.png',
    },
    {
      'buttonName': 'Jellybean',
      'recipe': 'p(20) s(20) (V) (X)',
      'hasUnimplementedSkill': false,
      'buttonSet': 'BROM',
      'dieTypes': [ 'V Swing', 'X Swing', ],
      'dieSkills': [ 'Poison', 'Shadow', ],
      'isTournamentLegal': true,
      'artFilename': 'jellybean.png',
    },
  ]);
  assert.equal(retval, true, "Api.parseButtonData() returns true");
  assert.deepEqual(
    Api.button.list,
    { 'Adam Spam': {
        'buttonName': 'Adam Spam',
        'hasUnimplementedSkill': true,
        'recipe': 'F(4) F(6) (6) (12) (X)',
        'buttonSet': 'Polycon',
        'dieTypes': [ 'X Swing', ],
        'dieSkills': [ 'Fire', ],
        'isTournamentLegal': true,
        'artFilename': 'adamspam.png',
      },
      'Avis': {
        'buttonName': 'Avis',
        'hasUnimplementedSkill': false,
        'recipe': '(4) (4) (10) (12) (X)',
        'buttonSet': 'Soldiers',
        'dieTypes': [ 'X Swing', ],
        'dieSkills': [ ],
        'isTournamentLegal': true,
        'artFilename': 'avis.png',
      },
      'Jellybean': {
        'buttonName': 'Jellybean',
        'hasUnimplementedSkill': false,
        'recipe': 'p(20) s(20) (V) (X)',
        'buttonSet': 'BROM',
        'dieTypes': [ 'V Swing', 'X Swing', ],
        'dieSkills': [ 'Poison', 'Shadow', ],
        'isTournamentLegal': true,
        'artFilename': 'jellybean.png',
      }
  });
  assert.deepEqual(Env.message, undefined,
            "Api.parseButtonData should not set Env.message");
});

test("test_Api.parseButtonData_failure", function(assert) {
  Api.button = {};
  var retval = Api.parseButtonData({});
  assert.equal(retval, false, "Api.parseButtonData({}) returns false");
});

test("test_Api.getButtonSetData", function(assert) {
  stop();
  expect(5); // number of tests plus 2 for the teardown tests

  Api.getButtonSetData(null, function() {
    assert.equal(Api.buttonSet.load_status, "ok",
      "Api.buttonSet.load_status should be ok");
    assert.equal(typeof Api.buttonSet.list, "object",
      "Api.buttonSet.list should be an object");
    assert.deepEqual(Env.message, undefined,
      "Api.getButtonSetData should not set Env.message");
    start();
  });
});

test("test_Api.parseButtonSetData", function(assert) {
  Api.buttonSet = {};
  Api.parseButtonSetData([
    { 'setName': 'Lunch Money' },
    { 'setName': 'Soldiers' },
    { 'setName': 'The Big Cheese' },
    { 'setName': 'Vampyres' },
  ]);
  assert.deepEqual(
    Api.buttonSet.list,
    {
      'Lunch Money': { 'setName': 'Lunch Money' },
      'Soldiers': { 'setName': 'Soldiers' },
      'The Big Cheese': { 'setName': 'The Big Cheese' },
      'Vampyres': { 'setName': 'Vampyres' },
    },
    "Set list should have correct contents"
  );
});

test("test_Api.parsePlayerData", function(assert) {
  expect(5); // number of tests plus 2 for the teardown tests

  Api.player = {};
  var retval = Api.parsePlayerData({
    'nameArray': ['tester1', 'tester2', 'tester3' ],
    'statusArray': ['ACTIVE', 'ACTIVE', 'ACTIVE' ],
  });
  assert.equal(retval, true, "Api.parsePlayerData() returns true");
  assert.deepEqual(
    Api.player.list,
    { 'tester1': {'status': 'ACTIVE', },
      'tester2': {'status': 'ACTIVE', },
      'tester3': {'status': 'ACTIVE', }
    }
  );
  assert.deepEqual(Env.message, undefined,
            "Api.parseButtonData should not set Env.message");
});

test("test_Api.parsePlayerData_failure", function(assert) {
  Api.player = {};
  var retval = Api.parsePlayerData({});
  assert.equal(retval, false, "Api.parsePlayerData({}) returns false");
});

test("test_Api.getNewGamesData", function(assert) {
  stop();
  Api.getNewGamesData(function() {
    assert.equal(Api.new_games.load_status, 'ok',
         'Successfully loaded new games data');
    assert.equal(Api.new_games.nGames, 0, 'Got expected number of new games');
    start();
  });
});

test("test_Api.getActiveGamesData", function(assert) {
  stop();
  Api.getActiveGamesData(function() {
    assert.equal(Api.active_games.load_status, 'ok',
         'Successfully loaded active games data');
    assert.ok(Api.active_games.nGames > 0, 'Parsed some active games');
    assert.ok(Api.active_games.games.awaitingPlayer.length > 0,
          "Parsed some games as waiting for the active player");
    assert.ok(Api.active_games.nGames > Api.active_games.games.awaitingPlayer.length,
          "Parsed more active games than games waiting for the active player");
    start();
  });
});

test("test_Api.getCompletedGamesData", function(assert) {
  stop();
  Api.getCompletedGamesData(function() {
    assert.equal(Api.completed_games.load_status, 'ok',
         'Successfully loaded completed games data');
    assert.ok(Api.completed_games.nGames > 0, 'Parsed some completed games');
    assert.equal(Api.completed_games.games[0]['status'], 'COMPLETE',
          "Completed game has expected status");
    start();
  });
});

test("test_Api.getCancelledGamesData", function(assert) {
  stop();
  Api.getCancelledGamesData(function() {
    assert.equal(Api.cancelled_games.load_status, 'ok',
         'Successfully loaded cancelled games data');
    assert.ok(Api.cancelled_games.nGames > 0, 'Parsed some cancelled games');
    assert.equal(Api.cancelled_games.games[0]['status'], 'CANCELLED',
          "Cancelled game has expected status");
    start();
  });
});

test("test_Api.getUserPrefsData", function(assert) {
  stop();
  Api.getUserPrefsData(function() {
    assert.equal(Api.user_prefs.load_status, 'ok', "Successfully loaded user data");
    start();
  });
});

test("test_Api.parseUserPrefsData", function(assert) {
  stop();
  Api.getUserPrefsData(function() {
    assert.equal(Api.user_prefs.autopass, true, "Successfully parsed autopass value");
    start();
  });
});

test("test_Api.parseUserPrefsDataFireOvershooting", function(assert) {
  stop();
  Api.getUserPrefsData(function() {
    assert.equal(Api.user_prefs.fire_overshooting, false, "Successfully parsed fire overshooting value");
    start();
  });
});

test("test_Api.getGameData", function(assert) {
  stop();
  var gameId = BMTestUtils.testGameId('frasquito_wiseman_specifydice');
  Game.game = gameId;
  Api.getGameData(Game.game, 10, function() {
    assert.equal(Api.game.gameId, gameId, "parseGameData() parsed gameId from API data");
    assert.equal(Api.game.isParticipant, true, "parseGameData() set isParticipant based on API data");
    assert.equal(Api.game.playerIdx, 0, "parseGameData() set playerIdx based on API data");
    assert.equal(Api.game.opponentIdx, 1, "parseGameData() set opponentIdx based on API data");
    assert.equal(Api.game.activePlayerIdx, null, "parseGameData() parsed activePlayerIdx from API data");
    assert.equal(Api.game.playerWithInitiativeIdx, null, "parseGameData() parsed playerWithInitiativeIdx from API data");
    delete Game.game;
    start();
  });
});

test("test_Api.getGameData_nonplayer", function(assert) {
  stop();
  var gameId = BMTestUtils.testGameId('frasquito_wiseman_specifydice_nonplayer');
  Game.game = gameId;
  Api.getGameData(Game.game, 10, function() {
    assert.equal(Api.game.gameId, gameId,
          "parseGameData() set gameId for nonparticipant");
    delete Game.game;
    start();
  });
});

test("test_Api.getGameData_somelogs", function(assert) {
  stop();
  var gameId = BMTestUtils.testGameId('washu_hooloovoo_cant_win');
  Game.game = gameId;
  Api.getGameData(Game.game, 10, function() {
    assert.equal(Api.game.actionLog.length, 10, "getGameData() passed limited action log length");
    assert.equal(Api.game.chatLog.length, 10, "getGameData() passed limited chat log length");
    delete Game.game;
    start();
  });
});

// Technically, this is a cheat.  It's showing that when the backend
// sends the full logs, the Api object receives them, but it is not
// testing whether Api.getGameData() successfully sends the request
// for full logs, because the API response is canned, so it can't test that.
test("test_Api.getGameData_alllogs", function(assert) {
  stop();
  Game.game = BMTestUtils.testGameId('washu_hooloovoo_cant_win_fulllogs');
  Api.getGameData(Game.game, undefined, function() {
    assert.ok(Api.game.actionLog.length > 10, "getGameData() passed unlimited action log length");
    assert.ok(Api.game.chatLog.length > 10, "getGameData() passed unlimited chat log length");
    delete Game.game;
    start();
  });
});

// N.B. use Api.getGameData() to query dummy_responder, but
// test any details of parsePlayerData()'s processing here
test("test_Api.parseGamePlayerData", function(assert) {
  stop();
  var gameId = BMTestUtils.testGameId('frasquito_wiseman_specifydice');
  Game.game = gameId;
  Api.getGameData(Game.game, 10, function() {
    assert.ok(Api.game.player.playerId,
              "player ID should be set in API response");
    assert.deepEqual(Api.game.player.playerName, 'responder001',
              "player name should be parsed from API response");
    assert.deepEqual(Api.game.player.waitingOnAction, true,
              "'waiting on action' status should be parsed from API response");
    assert.deepEqual(Api.game.player.roundScore, null,
              "round score should be parsed from API response");
    assert.deepEqual(Api.game.player.sideScore, null,
              "side score should be parsed from API response");
    assert.deepEqual(Api.game.player.gameScoreArray, {'W': 0, 'L': 0, 'D': 0, },
              "game score array should be parsed from API response");
    assert.ok(Api.game.player.lastActionTime,
              "last action time is set in API response");
    assert.deepEqual(Api.game.player.hasDismissedGame, false,
              "'has dismissed game' should be parsed from API response");
    assert.deepEqual(Api.game.player.canStillWin, null,
              "'can still win' should be parsed from API response");
    assert.deepEqual(Api.game.player.button, {
                'name': 'Frasquito',
                'recipe': '(4) (6) (8) (12) (2/20)',
                'artFilename': 'frasquito.png',
              }, "recipe data should be parsed from API response");
    assert.deepEqual(Api.game.player.activeDieArray[0].description, '4-sided die',
              "die descriptions should be parsed");
    assert.deepEqual(Api.game.player.activeDieArray[4].recipe, '(2/20)',
              "player die recipe should be parsed correctly");
    assert.deepEqual(Api.game.player.capturedDieArray, [],
              "array of captured dice should be parsed");
    assert.deepEqual(
      Api.game.player.optRequestArray[4],
      ['2', '20'],
      "option request array should contain entry for (2/20)");
    delete Game.game;
    start();
  });
});

test("test_Api.parseGamePlayerData_option", function(assert) {
  stop();
  var gameId = BMTestUtils.testGameId('frasquito_wiseman_specifydice');
  Api.getGameData(gameId, 10, function() {
    assert.deepEqual(Api.game.player.swingRequestArray, {});
    assert.deepEqual(Api.game.player.optRequestArray, {
      4: ["2", "20"],
    });
    start();
  });
});

test("test_Api.disableSubmitButton", function(assert) {
  $('body').append($('<div>', {'id': 'api_page', }));
  $('#api_page').append($('<button>', {
    'id': 'api_action_button',
    'text': 'Submit',
  }));
  Api.disableSubmitButton('#api_action_button');
  var item = document.getElementById('api_action_button');
  assert.equal(item.getAttribute('disabled'), 'disabled',
        "After a submit button has been clicked, it should be disabled");
});

test("test_Api.getNextGameId", function(assert) {
  stop();
  Api.getNextGameId(
    function() {
      assert.equal(Api.gameNavigation.load_status, 'ok',
        'Successfully retrieved next game ID');
      start();
    });
});

test("test_Api.parseNextGameId", function(assert) {
  stop();
  Api.getNextGameId(function() {
    assert.equal(Api.gameNavigation.nextGameId, 7, "Successfully parsed next game ID");
    start();
  });
});

test("test_Api.parseNextGameId_skipping", function(assert) {
  stop();
  Api.game =
    {
      'gameId': 7,
      'isParticipant': true,
      'player': { 'waitingOnAction': true },
    };
  Api.getNextGameId(function() {
    assert.equal(Api.gameNavigation.nextGameId, 4, "Successfully parsed next game ID");
    start();
  });
});

test("test_Api.getNextNewPostId", function(assert) {
  stop();
  Api.getNextNewPostId(
    function() {
      assert.equal(Api.forumNavigation.load_status, 'ok',
        'Successfully retrieved next game ID');
      assert.equal(Api.forumNavigation.nextNewPostId, 3,
        'Retrieved correct next game ID');
      start();
    });
});

test("test_Api.getOpenGamesData", function(assert) {
  stop();
  Api.getOpenGamesData(
    function() {
      assert.equal(Api.open_games.load_status, 'ok',
        'Successfully retrieved open games');
      start();
    });
});

test("test_Api.loadForumOverview", function(assert) {
  stop();
  Api.loadForumOverview(
    function() {
      assert.equal(Api.forum_overview.load_status, 'ok',
        'Successfully loaded forum overview');
      start();
    });
});

test("test_Api.loadForumBoard", function(assert) {
  stop();
  Api.loadForumBoard(1,
    function() {
      assert.equal(Api.forum_board.load_status, 'ok',
        'Successfully loaded forum board');
      start();
    });
});

test("test_Api.loadForumThread", function(assert) {
  stop();
  Api.loadForumThread(1, 2,
    function() {
      assert.equal(Api.forum_thread.load_status, 'ok',
        'Successfully loaded forum overview');
      start();
    });
});

test("test_Api.getActivePlayers", function(assert) {
  stop();
  Api.getActivePlayers(50,
    function() {
      assert.equal(Api.active_players.load_status, 'ok',
        'Successfully retrieved active players');
      start();
    });
});

test("test_Api.parseActivePlayers", function(assert) {
  stop();
  Api.getActivePlayers(50,
    function() {
      assert.ok(Api.active_players.players.length,
        "Successfully parsed active players info");
      start();
    });
});

test("test_Api.loadProfileInfo", function(assert) {
  stop();
  Api.loadProfileInfo('tester',
    function() {
      assert.equal(Api.profile_info.load_status, 'ok',
        'Successfully retrieved profile info');
      start();
    });
});

test("test_Api.searchGameHistory", function(assert) {
  stop();
  var searchParameters = {
            'sortColumn': 'lastMove',
            'sortDirection': 'DESC',
            'numberOfResults': '20',
            'page': '1',
            'playerNameA': 'tester',
            'status': 'COMPLETE',
  };

  Api.searchGameHistory(searchParameters,
    function() {
      assert.equal(Api.game_history.load_status, 'ok',
        'Successfully performed search');
    start();
  });
});

test("test_Api.parseOpenGames", function(assert) {
  stop();
  Api.getOpenGamesData(function() {
    assert.ok(Api.open_games.games.length > 0, "Successfully parsed open games");
    start();
  });
});

test("test_Api.joinOpenGame", function(assert) {
  stop();
  Api.joinOpenGame(4400, 'Avis',
    function() {
      assert.equal(Api.join_game_result.load_status, 'ok',
        'Successfully retrieved open games');
      start();
    },
    function() {
      assert.ok(false, 'Retrieving game data should succeed');
      start();
    });
});

test("test_Api.parseJoinGameResult", function(assert) {
  stop();
  Api.joinOpenGame(4400, 'Avis',
    function() {
      assert.equal(Api.join_game_result.success, true,
        "Successfully parsed join game result");
      start();
    },
    function() {
      assert.ok(false, 'Retrieving game data should succeed');
      start();
    });
});

test("test_Api.parseNextGameId", function(assert) {
  stop();
  Api.loadProfileInfo('tester',
    function() {
      assert.equal(Api.profile_info.name_ingame, 'tester',
        "Successfully parsed profile info");
      start();
    });
});

test("test_Api.parseSearchResults_games", function(assert) {
  stop();
  var searchParameters = {
            'sortColumn': 'lastMove',
            'sortDirection': 'DESC',
            'numberOfResults': '20',
            'page': '1',
            'playerNameA': 'tester',
            'status': 'COMPLETE',
  };

  Api.searchGameHistory(searchParameters, function() {
    assert.ok(Api.game_history.games.length > 0,
      "Successfully parsed search results games list");
    start();
  });
});

test("test_Api.parseSearchResults_summary", function(assert) {
  stop();
  var searchParameters = {
            'sortColumn': 'lastMove',
            'sortDirection': 'DESC',
            'numberOfResults': '20',
            'page': '1',
            'playerNameA': 'tester2',
            'buttonNameA': 'Avis',
  };

  Api.searchGameHistory(searchParameters, function() {
    assert.ok(Api.game_history.summary.matchesFound > 0,
      "Successfully parsed search results summary data");
    start();
  });
});

test("test_Api.getPendingGameCount", function(assert) {
  stop();
  Api.getPendingGameCount(function() {
    assert.equal(Api.pending_games.load_status, 'ok',
      "Successfully retrieved count of pending games");
    assert.ok(typeof Api.pending_games.count === 'number',
      "Successfully retrieved valid count of pending games");
    start();
  });
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Step 2: Design the Application - Google Web Toolkit - Google Code</title>

<link href="/css/codesite.pack.04102009.css" type="text/css" rel="stylesheet">

<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="/osd.xml">

    My favorites ▼
    |

    English ▼

    | Sign in

      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">

      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml">

        <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px">

        <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit">

e.g. "ajax apis" or "open source"

      </form>

Google Web Toolkit

      Home

      Docs

      Blog

      Community

      Terms

      Download

Downloads

Learn More

Overview

Business Apps

SDK

Speed Tracer

Plugin for Eclipse

Examples

Get Started

SDK

Set up Eclipse

Speed Tracer

Tutorials

Get Started

Create a GWT Project

Design the Application

Build the User Interface

Manage Events on the Client

Code Functionality on the Client

Debug a GWT Application

Apply Style

Compile a GWT Application

Internationalization

Client-Server Communication

GWT RPC

JSON

JSON - PHP

Cross-Site

JUnit Testing

Google App Engine

MVP Architecture

Documentation

What's Coming in 2.1?

Release Notes

Organize Projects

Compile & Debug

Coding Basics

Client-Side Code

Compatibility with the Java Language and Libraries

History

Number and Date Formatting

Programming Delayed Logic

Working with JSON

Working with XML

JavaScript Native Interface (JSNI)

JavaScript Overlay Types

Deferred Binding

Build User Interfaces

Cross-Browser Support

Layout Using Panels

Widgets

Creating Custom Widgets

Working with the DOM

Events and Handlers

Working with CSS

Declarative UI with UiBinder

Bundling Image Resources

Accessibility

Internationalization

Locale

Constants

Messages

Plural Forms

UiBinder

Communicate with a Server

Test with JUnit

HtmlUnit

Remote Testing

Code Coverage

Deploy

Optimize

Code Splitting

Compile Report

Client Bundle

Lightweight Metrics

Reference

SDK API Reference (Javadoc)

JRE Emulation Reference

Widget List

FAQ

Get Started

Debug and Compile

Build the User Interface

Develop Client-side Code

Communicate with a Server

Troubleshoot

Glossary

Docs for Previous Versions

Tools

Plugin for Eclipse

SDK Command-line Tools

Speed Tracer

Getting Started

Examples

Hints

Data Dump Format

Logging API

FAQ

GWT Designer

WindowBuilder Pro

WindowTester Pro

CodePro AnalytiX

Resources

Articles

Books

Community

App Gallery

Developer Spotlight

Google API Libraries

Tools & Libraries

Presentations

Making GWT Better

Issue Tracking

Step 2: Design the Application

    At this point, you've created the stub files you need to start coding StockWatcher.

    In this section, you'll review the functional requirements and design the user interface.

Examine the functional requirements.

Identify the elements of the UI design.

1. Examining the functional requirements

Initially you want the StockWatcher application to do six things.

Provide users with the ability to add stocks. (Supply simple validation on input for illegal characters or existing stock.)

Display the following information for each stock: symbol, price, change since last refresh.

Provide users with the ability to delete a stock from the list.

Refresh the stock price.

Calculate the change since the last refresh as both a number and a percentage.

Display a timestamp indicating the last update.

2. Identifying the elements of the UI design

After studying StockWatcher's functional requirements, you decide you need these UI elements:

a table to hold the stock data

two buttons, one to add stocks and one to remove them

an input box to enter the stock code

a timestamp to show the time and date of the last refresh

The design team has suggested the following additions:

a logo

a header

colors to indicate whether the change in price was positive or negative

Including Static Elements

GWT does not dictate how you lay out your HTML page. A GWT application
can take up the entire browser window, as it does in the startup
application, or it can be embedded in an existing page, as it is in the Getting Started page of this tutorial.

The StockWatcher application contains both static and dynamic elements. The Google Code logo and the header "StockWatcher" are static elements in the HTML host page. All the other elements are created programmatically using GWT widgets and panels.

What's Next

At this point you've reviewed StockWatcher's functional requirements. You have a clear idea of what StockWatcher does. You know what UI elements you need to implement and how you want to lay them out.

Now you're ready to build the user interface using GWT widgets and panels.

Step 3: Building the User Interface

  Except as otherwise noted,
  the content of this page is licensed under the Creative Commons
  Attribution 3.0 License.

    ©2010 Google -
    Code Home -
    Terms of Service -
    Privacy Policy -
    Site Directory

    Google Code offered in:
    English -
    Español -
    日本語 -
    한국어 -
    Português -
    Pусский -
    中文(简体) -
    中文(繁體)

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Intacct.SDK.Functions.InventoryControl;
using Intacct.SDK.Functions;
using Intacct.SDK.Tests.Xml;
using Intacct.SDK.Xml;
using Xunit;

namespace Intacct.SDK.Tests.Functions.InventoryControl
{
    public class WarehouseCreateTest : XmlObjectTestHelper
    {
        [Fact]
        public void GetXmlTest()
        {
            string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
    <create>
        <WAREHOUSE>
            <WAREHOUSEID>W1234</WAREHOUSEID>
            <NAME>hello world</NAME>
            <LOC>
                <LOCATIONID>L1234</LOCATIONID>
            </LOC>
        </WAREHOUSE>
    </create>
</function>";

            WarehouseCreate record = new WarehouseCreate("unittest")
            {
                WarehouseId = "W1234",
                WarehouseName = "hello world",
                LocationId = "L1234"
            };
            this.CompareXml(expected, record);
        }
    }
}


text:
package com.github.ambry.named;

import com.github.ambry.frontend.Page;
import java.util.concurrent.CompletableFuture;

/**
 * A layer for interacting with a metadata store that holds mappings between blob names and blob IDs.
 */
public interface NamedBlobDb {

  /**
   * Look up a {@link NamedBlobRecord} by name.
   * @param accountName the name of the account.
   * @param containerName the name of the container.
   * @param blobName the name of the blob.
   * @return a {@link CompletableFuture} that will eventually contain either the {@link NamedBlobRecord} for the named
   *         blob or an exception if an error occurred.
   */
  CompletableFuture<NamedBlobRecord> get(String accountName, String containerName, String blobName);

  /**
   * List blobs that start with a provided prefix in a container. This returns paginated results. If there are
   * additional pages to read, {@link Page#getNextPageToken()} will be non null.
   * @param accountName the name of the account.
   * @param containerName the name of the container.
   * @param blobNamePrefix the name prefix to search for.
   * @param pageToken if {@code null}, return the first page of {@link NamedBlobRecord}s that start with
   *                  {@code blobNamePrefix}. If set, use this as a token to resume reading additional pages
   *                  of records that start with the prefix.
   * @return a {@link CompletableFuture} that will eventually contain a {@link Page} of {@link NamedBlobRecord}s
   *         starting with the specified prefix or an exception if an error occurred.
   */
  CompletableFuture<Page<NamedBlobRecord>> list(String accountName, String containerName, String blobNamePrefix,
      String pageToken);

  /**
   * Persist a {@link NamedBlobRecord} in the database.
   * @param record the {@link NamedBlobRecord}
   * @return a {@link CompletableFuture} that will eventually contain a {@link PutResult} or an exception if an error
   *         occurred.
   */
  CompletableFuture<PutResult> put(NamedBlobRecord record);

  /**
   * Delete a record for a blob in the database.
   * @param accountName the name of the account.
   * @param containerName the name of the container.
   * @param blobName the name of the blob.
   * @return a {@link CompletableFuture} that will eventually contain a {@link DeleteResult} or an exception if an error
   *         occurred.
   */
  CompletableFuture<DeleteResult> delete(String accountName, String containerName, String blobName);
}


text:
package org.jkiss.dbeaver.ui.internal;

import org.eclipse.osgi.util.NLS;

public class UINavigatorMessages extends NLS {
    public static final String BUNDLE_NAME = "org.jkiss.dbeaver.ui.internal.UINavigatorMessages"; //$NON-NLS-1$

    //object properties editor
    public static String obj_editor_properties_control_action_filter_setting;
    public static String obj_editor_properties_control_action_configure_columns;
    public static String obj_editor_properties_control_action_configure_columns_description;
    //object properties editor

    public static String dialog_filter_global_link;
    public static String dialog_filter_list_exclude;
    public static String dialog_filter_list_include;
    public static String dialog_filter_title;
    public static String dialog_filter_save_button;
    public static String dialog_filter_remove_button;
    public static String dialog_filter_save_label;
    public static String dialog_filter_name_label;
    public static String dialog_filter_hint_text;

    public static String actions_navigator__objects;
    public static String actions_navigator_copy_fqn_title;
    public static String actions_navigator_copy_fqn_titles;
    public static String actions_navigator_copy_object_copy_node;
    public static String actions_navigator_copy_object_copy_objects;
    public static String actions_navigator_create_folder_error_message;
    public static String actions_navigator_create_folder_error_title;
    public static String actions_navigator_create_folder_folder_name;
    public static String actions_navigator_create_new;
    public static String actions_navigator_delete_objects;
    public static String actions_navigator_delete_;
    public static String actions_navigator_delete_script;
    public static String actions_navigator_edit;
    public static String actions_navigator_error_dialog_delete_object_title;
    public static String actions_navigator_error_dialog_open_entity_title;
    public static String actions_navigator_error_dialog_open_resource_title;
    public static String actions_navigator_open;
    public static String actions_navigator_view;
    public static String actions_navigator_view_script_button;
    public static String actions_navigator_filter_objects;
    public static String actions_navigator_search_tip;

    public static String dialog_project_create_wizard_error_already_exists;
    public static String dialog_project_create_wizard_error_cannot_create;
    public static String dialog_project_create_wizard_error_cannot_create_message;
    public static String dialog_project_create_wizard_title;
    public static String dialog_project_goto_object_title;

    public static String registry_entity_editor_descriptor_description;
    public static String registry_entity_editor_descriptor_name;
    public static String pref_page_database_general_group_navigator;

    // DatabaseNavigator
    public static String pref_page_database_general_label_expand_navigator_tree;
    public static String pref_page_database_general_label_show_tips_in_tree;
    public static String pref_page_database_general_label_show_tips_in_tree_tip;
    public static String pref_page_database_general_label_order_elements_alphabetically;
    public static String pref_page_database_general_label_folders_first;
    public static String pref_page_database_general_label_folders_first_tip;
    public static String pref_page_database_general_label_group_database_by_driver;
    public static String pref_page_database_general_label_long_list_fetch_size;
    public static String pref_page_database_general_label_long_list_fetch_size_tip;
    public static String pref_page_database_general_label_double_click_node;
    public static String pref_page_database_general_label_double_click_node_open_properties;
    public static String pref_page_database_general_label_double_click_node_expand_collapse;
    public static String pref_page_database_general_label_double_click_connection;
    public static String pref_page_database_general_label_double_click_connection_open_properties;
    public static String pref_page_database_general_label_double_click_connection_conn_disconn;
    public static String pref_page_database_general_label_double_click_connection_open_sqleditor;
    public static String pref_page_database_general_label_double_click_connection_open_new_sqleditor;
    public static String pref_page_database_general_label_double_click_connection_expand_collapse;

    // ProjectSettings
    public static String pref_page_projects_settings_label_resource_location;
    public static String pref_page_projects_settings_label_resource;
    public static String pref_page_projects_settings_label_folder;
    public static String pref_page_projects_settings_label_select;
    public static String pref_page_projects_settings_label_root_folder;
    public static String pref_page_projects_settings_label_not_use_hidden_folders;
    public static String pref_page_projects_settings_label_not_store_resources_in_another_project;
    public static String pref_page_projects_settings_label_restart_require_refresh_global_settings;

    public static String ui_properties_category_information;
    public static String ui_properties_category_information_tip;
    public static String ui_properties_category_properties;
    public static String ui_properties_category_properties_tip;
    public static String ui_properties_category_structure;
    public static String ui_properties_task_add_folder;
    public static String ui_properties_task_add_node;

    public static String CreateLinkHandler_e_create_link_message;
    public static String CreateLinkHandler_e_create_link_title;
    public static String CreateLinkHandler_e_create_link_validation;

    public static String dialog_select_datasource_error_message;
    public static String dialog_select_datasource_error_title;
    public static String dialog_select_datasource_title;

    public static String controls_object_list_job_props_read;
    public static String controls_object_list_message_items;
    public static String controls_object_list_message_no_items;
    public static String controls_object_list_monitor_load_lazy_props;
    public static String controls_object_list_monitor_load_props;
    public static String controls_object_list_status_objects;

    public static String editors_entity_dialog_persist_title;
    public static String editors_entity_dialog_preview_title;
    public static String editors_entity_monitor_add_folder;
    public static String editors_entity_monitor_add_node;
    public static String editors_entity_monitor_preview_changes;
    public static String editors_entity_properties_text;
    public static String editors_entity_properties_tooltip_suffix;

    public static String confirm_entity_delete_title;
    public static String confirm_entity_delete_message;

    public static String confirm_local_folder_delete_title;
    public static String confirm_local_folder_delete_message;

    public static String confirm_entity_reject_title;
    public static String confirm_entity_reject_message;
    public static String confirm_entity_reject_toggleMessage;

    public static String confirm_entity_revert_title;
    public static String confirm_entity_revert_message;
    public static String confirm_entity_revert_toggleMessage;

    public static String confirm_close_editor_edit_title;
    public static String confirm_close_editor_edit_message;

    public static String confirm_close_entity_edit_title;
    public static String confirm_close_entity_edit_message;

    public static String label_configure_columns;

	public static String label_description;

	public static String label_name;

	public static String label_select_columns;

	public static String label_show_all_projects;
	public static String label_show_connected;

	public static String pref_page_target_button_use_datasource_settings;
    public static String pref_page_target_link_show_datasource_settings;
    public static String pref_page_target_link_show_global_settings;

    static {
        // initialize resource bundle
        NLS.initializeMessages(BUNDLE_NAME, UINavigatorMessages.class);
    }

    private UINavigatorMessages() {
    }
}


text:
                       <a href="<?php echo base_url(); ?>" title="Go to Home Page">Home
                       >

                       <?php echo ucfirst($title); ?>

 Your Order was successfully placed.

						Thank you for using our KSA Shopping mall. Press here for more shopping!

				<link href="<?php echo base_url("assets/css/component.css"); ?>" rel='stylesheet' type='text/css' />


text:
using System;
using System.IO;
using System.Linq;
using Prism.Modularity;
// ReSharper disable InheritdocConsiderUsage

namespace Accelerider.Windows.Infrastructure.Modularity
{
    public class RemoteModuleTypeLoader : IModuleTypeLoader, IDisposable
    {
        private readonly IAssemblyResolver _assemblyResolver;

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is disposed of in the Dispose method.")]
        public RemoteModuleTypeLoader() : this(new AssemblyResolver()) { }

        public RemoteModuleTypeLoader(IAssemblyResolver assemblyResolver) => _assemblyResolver = assemblyResolver;

        #region Events

        /// <summary>
        /// Raised repeatedly to provide progress as modules are loaded in the background.
        /// </summary>
        public event EventHandler<ModuleDownloadProgressChangedEventArgs> ModuleDownloadProgressChanged;

        private void RaiseModuleDownloadProgressChanged(IModuleInfo moduleInfo, long bytesReceived, long totalBytesToReceive) => RaiseModuleDownloadProgressChanged(new ModuleDownloadProgressChangedEventArgs(moduleInfo, bytesReceived, totalBytesToReceive));

        private void RaiseModuleDownloadProgressChanged(ModuleDownloadProgressChangedEventArgs e) => ModuleDownloadProgressChanged?.Invoke(this, e);

        /// <summary>
        /// Raised when a module is loaded or fails to load.
        /// </summary>
        public event EventHandler<LoadModuleCompletedEventArgs> LoadModuleCompleted;

        private void RaiseLoadModuleCompleted(IModuleInfo moduleInfo, Exception error) => RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(moduleInfo, error));

        private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e) => LoadModuleCompleted?.Invoke(this, e);

        #endregion

        /// <summary>
        /// Evaluates the <see cref="ModuleInfo.Ref"/> property to see if the current typeloader will be able to retrieve the <paramref name="moduleInfo"/>.
        /// Returns true if the <see cref="ModuleInfo.Ref"/> property starts with "file://", because this indicates that the file
        /// is a local file.
        /// </summary>
        /// <param name="moduleInfo">Module that should have it's type loaded.</param>
        /// <returns>
        /// 	<see langword="true"/> if the current typeloader is able to retrieve the module, otherwise <see langword="false"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="moduleInfo"/> is null.</exception>
        public bool CanLoadModuleType(IModuleInfo moduleInfo)
        {
            if (moduleInfo == null) throw new ArgumentNullException(nameof(moduleInfo));

            return moduleInfo.Ref != null && moduleInfo.Ref.StartsWith(Uri.UriSchemeFile, StringComparison.Ordinal);
        }

        /// <summary>
        /// Retrieves the <paramref name="moduleInfo"/>.
        /// </summary>
        /// <param name="moduleInfo">Module that should have it's type loaded.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is rethrown as part of a completion event")]
        public async void LoadModuleType(IModuleInfo moduleInfo)
        {
            if (moduleInfo == null)
                throw new ArgumentNullException(nameof(moduleInfo));

            if (!(moduleInfo is RemoteModuleInfo remoteModuleInfo))
                throw new ArgumentException($"The type of {nameof(moduleInfo)} must be {nameof(RemoteModuleInfo)}. ", nameof(moduleInfo));

            try
            {
                var missingRemoteRefs = remoteModuleInfo.RemoteRefs.Where(item => !File.Exists(item.LocalPath)).ToArray();
                if (missingRemoteRefs.Any())
                {
                    await new RemoteRefDownloader().StartAsync(
                        missingRemoteRefs,
                        new Progress<(long bytesReceived, long totalBytesToReceive)>(report =>
                            RaiseModuleDownloadProgressChanged(moduleInfo, report.bytesReceived, report.totalBytesToReceive)));

                }

                remoteModuleInfo
                    .RemoteRefs
                    .Where(item => File.Exists(item.LocalPath))
                    .Select(item => item.LocalPath)
                    .ToList()
                    .ForEach(item => _assemblyResolver.LoadAssemblyFrom(item));

                RaiseLoadModuleCompleted(moduleInfo, null);
            }
            catch (Exception ex)
            {
                RaiseLoadModuleCompleted(moduleInfo, ex);
            }
        }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <remarks>Calls <see cref="Dispose(bool)"/></remarks>.
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Disposes the associated <see cref="AssemblyResolver"/>.
        /// </summary>
        /// <param name="disposing">When <see langword="true"/>, it is being called from the Dispose method.</param>
        protected virtual void Dispose(bool disposing)
        {
            var disposableResolver = _assemblyResolver as IDisposable;
            disposableResolver?.Dispose();
        }

        #endregion
    }
}


text:
function Slide(){
	this.html;
	this.active;
	this.needsOwl;
	this.time = 20;

	this.show = function(){
		this.html.addClass("show");
		this.active = true;
	}

	this.hide = function(){
		this.html.removeClass("show");
		this.active = false;
	}

	this.renew = function() {

	}

	this.makeHTML = function(){
		this.html = $("<div>").addClass("slide");
		if(this.needsOwl){
			this.addOwl();
		}
	}

	this.addOwl = function(){
		var h1 = $("<h1>").text(this.title);
		var CHBalk = $("<div>").addClass("CHBalk").append(h1);
		var CHLogo = $("<div>").addClass("CHLogo");
		this.html.html(CHBalk).append(CHLogo);
	}

	this.loadImageAndAppendTo = function(imageUrl, appendTo){
		$('<img src="'+ imageUrl +'">').load(function() {
			$(this).appendTo(appendTo);
		})
	}
}

function PostEventSlide() {
	this.parent.constructor.call(this);

	this.title;
	this.date;
	this.desc;
	this.price;
	this.location;
	this.imageUrl;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var title = $("<H1>").text(this.title),
			date = $("<p>").addClass("time").html(this.date),
			desc = $("<div>").addClass("desc").html(this.desc),
			price = $("<div>").addClass("price").html(this.price),
			location = $("<div>").addClass("location").html(this.location),
			leftColumn = $("<div>").addClass("left-column").html(title).append(date).append(desc).append(price).append(location),
			rightColumn = $("<div>").addClass("right-column");
			poster = this.loadImageAndAppendTo(this.imageUrl, rightColumn),
		this.html.append(leftColumn).append(rightColumn);
		return this; // Chainability, lazy programming :)
	}

}
PostEventSlide.prototype = Object.create(Slide.prototype);
PostEventSlide.prototype.constructor = PostEventSlide;
PostEventSlide.prototype.parent = Slide.prototype;

function PastEventSlide(){
	this.parent.constructor.call(this);

	this.containerDiv;
	this.maxNumberOfImages = 6;

	this.images;
	this.title;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		this.containerDiv = $("<div>").addClass("container");
		this.renewImages();
		this.html.append(this.containerDiv);
		return this;
	}

	var oldRenew = this.renew;
	this.renew = function(){
		oldRenew.call(this);
		this.renewImages();
	}

	this.renewImages = function(){
		if(this.images){
			this.containerDiv.empty();
			this.images.shuffle();
			var maxIndex = Math.min(this.images.length, this.maxNumberOfImages);
			for(var i = 0; i < maxIndex; i++){
				var deg = randomFromInterval(-5,5);
				var left = randomFromInterval(-5,5);
				var top = randomFromInterval(-5,5);
				var cropDiv = $("<div>").addClass("photoCrop");
				var photoDiv = $("<div>").addClass("photo")
					.css({
						"-webkit-transform": "rotate("+deg+"deg", left: left, top: top,
						"-moz-transform": "rotate("+deg+"deg", left: left, top: top
					})
					.html(cropDiv);
				this.loadImageAndAppendTo(this.images[i], cropDiv);
				this.containerDiv.append(photoDiv);
			}
		}
		else {

		}
	}
}
PastEventSlide.prototype = Object.create(Slide.prototype);
PastEventSlide.prototype.constructor = PastEventSlide;
PastEventSlide.prototype.parent = Slide.prototype;

function FullScreenImageSlide(){
	this.parent.constructor.call(this);

	this.fullScreenImage;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var imageContainer = $("<div>").addClass("image-container");
		this.loadImageAndAppendTo(this.fullScreenImage, imageContainer);
		this.html.html(imageContainer);
		return this;
	}

	this.loadImageAndAppendTo = function(fullScreenImage, appendTo){
		$(fullScreenImage).load(function() {
			$(this).appendTo(appendTo);
		})
	}
}

FullScreenImageSlide.prototype = Object.create(Slide.prototype);
FullScreenImageSlide.prototype.constructor = FullScreenImageSlide;
FullScreenImageSlide.prototype.parent = Slide.prototype;

function LoadScreenSlide(){
	this.parent.constructor.call(this);
	this.time = 10000;
	var oldMakeHTML = this.makeHTML;

	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var imageContainer = $("<div>").addClass("loading centerContent");
		var loadText = $("<h1>").addClass("loading center").text("Loading.....");
		this.html.html(imageContainer.html(loadText));

		return this;
	}
}

LoadScreenSlide.prototype = Object.create(Slide.prototype);
LoadScreenSlide.prototype.constructor = LoadScreenSlide;
LoadScreenSlide.prototype.parent = Slide.prototype;

function StatisticsSlide(){
	this.parent.constructor.call(this);

	this.dataArray;
	this.body;
	this.title;
	this.xAxis;
	this.yAxis;
	this.imageUrl;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);

		return this;
	}
}

StatisticsSlide.prototype = Object.create(Slide.prototype);
StatisticsSlide.prototype.constructor = StatisticsSlide;
StatisticsSlide.prototype.parent = Slide.prototype;

function CustomHtmlSlide(){
	this.parent.constructor.call(this);

	this.customHtml;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		this.html.html(this.customHtml);
		return this;
	}

}

function FactSlide(){
	this.parent.constructor.call(this);
	this.fact;
	this.title;
	this.name;

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var container = $("<div>").addClass("randomBackground");
		var anotherContainer = $("<div>").addClass("centerContent fact")
		var fact = $("<H2>").text(this.fact).addClass("fact");
		var factOwl = $("<div>").addClass("image " + (this.name ? "quote" : "factOwl"));
		var name = $("<h3>").addClass("person");
		if(this.name){
			name.text("- " + this.name);
		}
		this.html.append(container.html(anotherContainer.html(factOwl).append(fact).append(name)));

		return this;
	}

	var oldShow = this.show;
	this.show = function(){
		oldShow.call(this);
		this.html.find("div.randomBackground").css({"background-color": "rgb("+randomInteger(216)+","+randomInteger(216)+","+randomInteger(216)+")"});
	}
}

FactSlide.prototype = Object.create(Slide.prototype);
FactSlide.prototype.constructor = FactSlide;
FactSlide.prototype.parent = Slide.prototype;

function WhosThatPokemonSlide(){
	this.parent.constructor.call(this);
	this.time = 15;

	var oldShow = this.show;
	this.show = function(){
		oldShow.call(this);
		document.getElementById("pokemonFrame").contentWindow.postMessage("reveal#10", "http://jgadelange.github.io");
	}

	var oldRenew = this.renew;
	this.renew = function() {
		oldRenew.call(this);
		var url = "http://jgadelange.github.io/whosthatpokemon/#" + Math.floor(Math.random() * 5502);
		this.html.find("#pokemonFrame").attr({"src": url});
	}

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var iframe = $("<iframe id='pokemonFrame'>").width(1920).height(1080);
		this.html.append(iframe);
		this.renew();
		return this;
	}
}

WhosThatPokemonSlide.prototype = Object.create(Slide.prototype);
WhosThatPokemonSlide.prototype.constructor = WhosThatPokemonSlide;
WhosThatPokemonSlide.prototype.parent = Slide.prototype;

function IframeSlide(){
	this.parent.constructor.call(this);
	this.src;
	this.name;
	this.lastUpdated;
	this.renewTime;

	var oldRenew = this.renew;
	this.renew = function() {
		oldRenew.call(this);
		var currentDate = new Date();

		if(this.lastUpdated){
			var difference = Math.abs(currentDate.getTime() - this.lastUpdated.getTime());
			if (difference / ( 3600 * 1000 ) > this.renewTime){
				this.update();
				this.lastUpdated = currentDate;
			}
		} else {
			this.update();
			this.lastUpdated = currentDate;
		}
	}

	this.update = function(){
		this.html.find("#" + this.name).attr({"src": this.src});
	}

	var oldMakeHTML = this.makeHTML;
	this.makeHTML = function(){
		oldMakeHTML.call(this);
		var iframe = $("<iframe id='" + this.name + "'>").width(1920).height(1080);
		this.html.append(iframe);
		this.renew();
		return this;
	}
}

IframeSlide.prototype = Object.create(Slide.prototype);
IframeSlide.prototype.constructor = IframeSlide;
IframeSlide.prototype.parent = Slide.prototype;


text:
package com.google.gdata.model.atom;

import com.google.gdata.util.common.util.Base64;
import com.google.gdata.util.common.util.Base64DecoderException;
import com.google.gdata.data.IContent;
import com.google.gdata.model.Element;
import com.google.gdata.model.ElementCreator;
import com.google.gdata.model.ElementKey;
import com.google.gdata.model.ElementMetadata;
import com.google.gdata.model.MetadataRegistry;
import com.google.gdata.model.ValidationContext;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.XmlBlob;

import java.util.Iterator;

/**
 * Variant of {@link Content} for entries containing miscellaneous
 * inlined content types.
 */
public class OtherContent extends Content {

  /** The kind name for adaptation. */
  public static final String KIND = "other";

  /**
   * The key for this element.
   */
  @SuppressWarnings("hiding")
  public static final ElementKey<String, OtherContent> KEY = ElementKey.of(
      Content.KEY.getId(), String.class, OtherContent.class);

  /**
   * Registers the metadata for this element.
   */
  public static void registerMetadata(MetadataRegistry registry) {
    if (registry.isRegistered(KEY)) {
      return;
    }

    Content.registerMetadata(registry);

    ElementCreator builder = registry.build(KEY);
    builder.addElement(Feed.KEY);
    builder.addElement(Entry.KEY);

    registry.adapt(Content.KEY, KIND, KEY);
  }

  /**
   * Constructs a new instance using the default key.
   */
  public OtherContent() {
    super(KEY);
  }

  /**
   * Constructs a new instance from a more generic {@link Content} type.
   *
   * @param content generic content
   */
  public OtherContent(Content content) {
    super(KEY, content);
  }

  /**
   * Constructs a new instance using the specified element key.
   *
   * @param key the element key for this element.
   */
  protected OtherContent(ElementKey<?, ?> key) {
    super(key);
  }

  /** @return the type of this content */
  @Override
  public int getType() {
    if (getXml() != null || getXmlContent() != null) {
      return IContent.Type.OTHER_XML;
    }
    if (getMimeType().getMediaType().equals("text")) {
      return IContent.Type.OTHER_TEXT;
    }
    return IContent.Type.OTHER_BINARY;
  }

  /** Specifies the MIME type. */
  public void setMimeType(ContentType v) {
    setAttributeValue(TYPE, v.getMediaType());
  }

  /** @return the XML contents */
  public XmlBlob getXml() {
    return null;
  }

  /** Specifies the XML contents. */
  public void setXml(XmlBlob v) {
    throw new UnsupportedOperationException("Not supported yet");
  }

  /**
   * Gets the nested xml content of this element.  This will return the first
   * xml element found inside this content.
   */
  public Element getXmlContent() {
    Iterator<Element> iter = getElementIterator();
    if (iter.hasNext()) {
      return iter.next();
    }
    return null;
  }

  /**
   * Sets the nested xml content of this element.
   */
  public void setXmlContent(Element content) {
    addElement(content);
  }

  /** @return the plain text contents */
  public String getText() {
    return getTextValue(KEY);
  }

  /** Specifies the plain-text contents. */
  public void setText(String v) {
    setTextValue(v);
  }

  /** @return the binary contents */
  public byte[] getBytes() {
    String value = getText();
    try {
      return value == null ? null : Base64.decode(value);
    } catch (Base64DecoderException e) {
      throw new IllegalStateException("Value was not base64 encoded: " + value);
    }
  }

  /** Specifies the binary contents. */
  public void setBytes(byte[] v) {
    setText(Base64.encode(v));
  }

  @Override
  protected void validate(ElementMetadata<?, ?> metadata,
      ValidationContext vc) {
    super.validate(metadata, vc);

    int maximumChildren = hasTextValue() ? 0 : 1;

    if (getElementCount() > maximumChildren) {
      vc.addError(this, "Content cannot contain more than "
          + maximumChildren + " child elements, but contains "
          + getElementCount());
    }
  }
}


text:
from discord.ext import commands

import datetime

from utilities import checks

async def setup(bot):
	await bot.add_cog(WoWS())

API_URLS = {
	"asia": "https://api.worldofwarships.asia/wows/",
	"eu": "https://api.worldofwarships.eu/wows/",
	"na": "https://api.worldofwarships.com/wows/",
	"ru": "https://api.worldofwarships.ru/wows/"
}

class WoWS(commands.Cog):

	async def cog_check(self, ctx):
		return await checks.not_forbidden().predicate(ctx)

	@commands.group(aliases = ["worldofwarships", "world_of_warships"],
					invoke_without_command = True, case_insensitive = True)
	async def wows(self, ctx):
		'''
		World of Warships
		Realms/Regions: Asia, EU, NA, RU (Default: NA)
		'''
		await ctx.send_help(ctx.command)

	@wows.group(invoke_without_command = True, case_insensitive = True)
	async def player(self, ctx, player: str, region: str = "NA"):
		'''Player details'''
		api_url = API_URLS.get(region.lower(), API_URLS["na"])
		params = {"application_id": ctx.bot.WARGAMING_APPLICATION_ID, "search": player, "limit": 1}
		async with ctx.bot.aiohttp_session.get(api_url + "account/list/", params = params) as resp:
			data = await resp.json()
		if data["status"] == "error":
			return await ctx.embed_reply(f":no_entry: Error: {data['error']['message']}")
		if data["status"] != "ok":
			return await ctx.embed_reply(":no_entry: Error")
		if not data["meta"]["count"]:
			return await ctx.embed_reply(":no_entry: Error: Player not found")
		account_id = data["data"][0]["account_id"]
		params = {"application_id": ctx.bot.WARGAMING_APPLICATION_ID, "account_id": account_id}
		async with ctx.bot.aiohttp_session.get(api_url + "account/info/", params = params) as resp:
			data = await resp.json()
		if data["status"] == "error":
			return await ctx.embed_reply(f":no_entry: Error: {data['error']['message']}")
		if data["status"] != "ok":
			return await ctx.embed_reply(":no_entry: Error")
		data = data["data"][str(account_id)]
		# TODO: Handle hidden profile?
		await ctx.embed_reply(title = data["nickname"],
								fields = (("ID", account_id), ("Account Level", data["leveling_tier"]),
											("Account XP", f"{data['leveling_points']:,}"),
											("Battles Fought", data["statistics"]["battles"]),
											("Miles Travelled", data["statistics"]["distance"])),
								footer_text = "Account Created",
								timestamp = datetime.datetime.utcfromtimestamp(data["created_at"]))


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.worshipsongs</groupId>
    <artifactId>worshipsongs-importer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.directory.studio</groupId>
            <artifactId>org.apache.commons.io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.8.11.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>org.worshipsongs.importer.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
<ion-header>
    <ion-toolbar>
        <ion-title>
            Add new list
        </ion-title>
        <ion-buttons start>
            <button ion-button (click)="dismiss()">
                <span ion-text color="primary" showWhen="ios">Cancel</span>
                <ion-icon name="md-close" showWhen="android, windows"></ion-icon>
            </button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>

<ion-content>
    <ion-list>
        <ion-item>
            <ion-label floating>List name</ion-label>
            <ion-input type="text" #listName></ion-input>
        </ion-item>
        <ion-item>
            <button ion-button full (click)="saveList(listName.value)">Save list</button>
        </ion-item>
    </ion-list>
</ion-content>


text:
$LOAD_PATH.unshift('lib')
require 'spyglass'

include Spyglass

window  = GUI::Window.new "Original"
apple   = Image.load File.expand_path('images/apple.jpg', File.dirname(__FILE__))

window.show(apple)

canny = apple.convert(ColorSpace[:BGR => :Gray])
canny.canny!(200, 300)

result = Image.new
result.copy!(apple)
result.draw_contours(canny.contours, Color.new(255, 0, 0))

result_window = GUI::Window.new "Contours"
result_window.show(result)

loop do
  break if GUI::wait_key(10) > 0
end


text:
FROM crystallang/crystal:1.0.0

WORKDIR /grip
COPY views views
COPY run.sh run.sh
COPY grip.cr grip.cr
COPY shard.yml shard.yml

ENV DATABASE_URL postgres://benchmarkdbuser:benchmarkdbpass@tfb-database:5432/hello_world?initial_pool_size=56&max_idle_pool_size=56
ENV GRIP_ENV production

RUN shards install
RUN crystal build  --release --no-debug grip.cr

EXPOSE 8080

CMD bash run.sh


text:
<html>
<body style='margin: 0px'>
<div style='background: red; background-repeat: repeat; -webkit-background-size: 50%; background-image: url(resources/green_rectangle.pdf); height: 100px; width: 100px'>

</div>
</body>
</html>


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#define LOCTEXT_NAMESPACE "SProjectLauncherPlatformListRow"

/**
 * Implements a row widget for map list.
 */
class SProjectLauncherPlatformListRow
	: public SMultiColumnTableRow<TSharedPtr<FString> >
{
public:

	SLATE_BEGIN_ARGS(SProjectLauncherPlatformListRow) { }
		SLATE_ATTRIBUTE(FString, HighlightString)
		SLATE_ARGUMENT(TSharedPtr<STableViewBase>, OwnerTableView)
		SLATE_ARGUMENT(TSharedPtr<FString>, PlatformName)
	SLATE_END_ARGS()

public:

	/**
	 * Constructs the widget.
	 *
	 * @param InArgs The construction arguments.
	 * @param InProfileManager The profile manager to use.
	 */
	void Construct( const FArguments& InArgs, const FProjectLauncherModelRef& InModel )
	{
		HighlightString = InArgs._HighlightString;
		PlatformName = InArgs._PlatformName;
		Model = InModel;

		SMultiColumnTableRow<TSharedPtr<FString> >::Construct(FSuperRowType::FArguments(), InArgs._OwnerTableView.ToSharedRef());
	}

public:

	/**
	 * Generates the widget for the specified column.
	 *
	 * @param ColumnName The name of the column to generate the widget for.
	 * @return The widget.
	 */
	virtual TSharedRef<SWidget> GenerateWidgetForColumn( const FName& ColumnName ) override
	{
		if (ColumnName == "PlatformName")
		{
			return SNew(SCheckBox)
				.IsChecked(this, &SProjectLauncherPlatformListRow::HandleCheckBoxIsChecked)
				.OnCheckStateChanged(this, &SProjectLauncherPlatformListRow::HandleCheckBoxCheckStateChanged)
				.Padding(FMargin(6.0, 2.0))
				[
					SNew(STextBlock)
						.Text(FText::FromString(*PlatformName))
				];
		}

		return SNullWidget::NullWidget;
	}

private:

	// Callback for changing the checked state of the check box.
	void HandleCheckBoxCheckStateChanged( ECheckBoxState NewState )
	{
		ILauncherProfilePtr SelectedProfile = Model->GetSelectedProfile();

		if (SelectedProfile.IsValid())
		{
			if (NewState == ECheckBoxState::Checked)
			{
				SelectedProfile->AddCookedPlatform(*PlatformName);
			}
			else
			{
				SelectedProfile->RemoveCookedPlatform(*PlatformName);
			}
		}
	}

	// Callback for determining the checked state of the check box.
	ECheckBoxState HandleCheckBoxIsChecked( ) const
	{
		ILauncherProfilePtr SelectedProfile = Model->GetSelectedProfile();

		if (SelectedProfile.IsValid())
		{
			SelectedProfile->IsValidForLaunch();
			if (SelectedProfile->GetCookedPlatforms().Contains(*PlatformName))
			{
				return ECheckBoxState::Checked;
			}
		}

		return ECheckBoxState::Unchecked;
	}

private:

	// Holds the highlight string for the log message.
	TAttribute<FString> HighlightString;

	// Holds the platform's name.
	TSharedPtr<FString> PlatformName;

	// Holds a pointer to the data model.
	FProjectLauncherModelPtr Model;
};

#undef LOCTEXT_NAMESPACE


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Mag. nat. Hist. , Ser. 2 9: 378 (1852)

#### Original name
Sphaeria herbarum var. glumarum Berk. & Broome

### Remarks
null


text:
import normalizeHash from './_normalize-hash';
import setHash from './set-hash';

/**
 * Updates the user's history with new hash
 * @param {string} newHash New hash, without `#`
 */
export default function replaceWithHash(newHash) {
  let hash = normalizeHash(newHash);
  if (window.history.replaceState) {
    hash = normalizeHash(hash);

    // If resetting the hash, the whole path is needed. `''` doesn't work.
    if (hash) {
      hash = '#' + hash;
    } else {
      hash = window.location.pathname + window.location.search;
    }

    window.history.replaceState({}, null, hash);
  } else {
    setHash(hash);
  }
}


text:
version: 0.9.0
title: Moduler
---

Vi vet fra erfaring at det er besværlig å ha alle våre funksjoner i samme fil og skop. I denne leksjonen skal vi dekke hvordan vi grupperer funksjoner, og definerer en spesialisert form for map kjent som struct for å kunne organiserer koden vår mer effektivt.

{% include toc.html %}

## Moduler

Moduler er den beste måten å organisere funksjoner inn i egne navnområder. I tillegg til å gruppere funksjoner, tillater det oss å definere våre egne navnkalte og private funksjoner som vi gikk igjennom i forrige leksjon.

La oss se på et enkelt eksempel:

``` elixir
defmodule Example do
  def greeting(name) do
    "Hello #{name}."
  end
end

iex> Example.greeting "Sean"
"Hello Sean."
```

I Elixir så er det mulig å nøste moduler i hverandre:

```elixir
defmodule Example.Greetings do
  def morning(name) do
    "Good morning #{name}."
  end

  def evening(name) do
    "Good night #{name}."
  end
end

iex> Example.Greetings.morning "Sean"
"Good morning Sean."
```

### Modul Attributer

Modul attributer er som oftest brukt som konstanter i Elixir. La oss se på et enkelt eksempel:

```elixir
defmodule Example do
  @greeting "Hello"

  def greeting(name) do
    ~s(#{@greeting} #{name}.)
  end
end
```

Det er viktig å notere at det er reserverte attributer i Elixir. De tre vanligste er:

+ `moduledoc` — Dokumenterer den nåværende modulen.
+ `doc` — Dokumentasjon for funksjoner og makroer.
+ `behaviour` — Bruk en OTP eller bruker-definert atferd.

## Structs

Structs er en spesielle form for map, de definerer en mengde av nøkler og standard verdier. En struct må være definert i en egen modul, som den også får navnet sitt fra. Det er normalt at en struct er det eneste som er definert i en modul.

For å definere en struct bruker vi `defstruct` sammen med en nøkkelord liste av felt og standard verdier.

```elixir
defmodule Example.User do
  defstruct name: "Sean", roles: []
end
```

La oss lage noen structs:

```elixir
iex> %Example.User{}
%Example.User{name: "Sean", roles: []}

iex> %Example.User{name: "Steve"}
%Example.User{name: "Steve", roles: []}

iex> %Example.User{name: "Steve", roles: [:admin, :owner]}
%Example.User{name: "Steve", roles: [:admin, :owner]}
```

Vi kan oppdatere vår struct akkurat som med en map:

```elixir
iex> steve = %Example.User{name: "Steve", roles: [:admin, :owner]}
%Example.User{name: "Steve", roles: [:admin, :owner]}
iex> sean = %{steve | name: "Sean"}
%Example.User{name: "Sean", roles: [:admin, :owner]}
```

Det viktigste er at du kan matche structs mot maps:

```elixir
iex> %{navn: "Sean"} = sean
%Eksempel.Bruker{navn: "Sean", roller: [:admin, :eier]}
```

## Komposisjon

Nå som vi vet hvordan vi lager moduler og structs, la oss lære oss hvordan vi kan legge til eksisterende funksjonalitet til de via komposisjon. Elixir forsyner oss med mange forskjellige måter å integrere med andre moduler.

### `alias`

Tillater oss å gi alias til modulnavn; noe som er veldig ofte brukt i Elixir.

```elixir
defmodule Sayings.Greetings do
  def basic(name), do: "Hi, #{name}"
end

defmodule Example do
  alias Sayings.Greetings

  def greeting(name), do: Greetings.basic(name)
end

# Uten alias

defmodule Example do
  def greeting(name), do: Sayings.Greetings.basic(name)
end
```

Hvis det oppstår en konflikt mellom to alias, eller om vi ønsker å bruke et alias til noe annet, så kan vi bruke `:as`:

```elixir
defmodule Example do
  alias Sayings.Greetings, as: Hi

  def print_message(name), do: Hi.basic(name)
end
```

Det er også mulig å bruke et alias på flere moduler i en tilordning:

```elixir
defmodule Example do
  alias Sayings.{Greetings, Farewells}
end
```

### `import`

Hvis vi har lyst til å importere funksjoner og makroer istedenfor å bruke et alias for modulen kan vi bruke `ìmport/`:

```elixir
iex> last([1, 2, 3])
** (CompileError) iex:9: undefined function last/1
iex> import List
nil
iex> last([1, 2, 3])
3
```

#### Filtrering

Per standard vil alle funksjoner og makroer bli importert, men vi kan filtrere dem ved å bruke `:only` og `:except`.

For å importere spesifikke funksjoner og makroer, må vi bruke navn/aritet paret med `:only` og `:except`. La oss starte med å kun importere `last/1` funksjonen:

```elixir
iex> import List, only: [last: 1]
iex> first([1, 2, 3])
** (CompileError) iex:13: undefined function first/1
iex> last([1, 2, 3])
3
```

Hvis vi importerer alt untatt `last/1` og prøver med den samme funksjonen som tidligere:

```elixir
iex> import List, except: [last: 1]
nil
iex> first([1, 2, 3])
1
iex> last([1, 2, 3])
** (CompileError) iex:3: undefined function last/1
```

I tillegg til navn/aritet paret så er det to spesielle atomer, `:functions` og `:macros`, som importerer kun de funksjonene eller makroene:

```elixir
import List, only: :functions
import List, only: :macros
```

### `require`

Brukt sjeldnere, men fortsatt viktig er `require/2`. Å kreve en modul forsikrer at den er kompilert og lastet.
Dette er mest brukbart når vi trenger å aksessere en modul sine makroer:

```elixir
defmodule Eksempel do
  require SuperMacros

  SuperMacros.do_stuff
end
```

Hvis vi prøver å kalle en makro som ikke er lastet, så vil Elixir heve en feil.

### `use`

use makroen kaller en spesiell makro, kalt `__using__/1`, i den spesifiserte modulen. Her er et eksempel:

```elixir
# lib/use_import_require/use_me.ex
defmodule UseImportRequire.UseMe do
  defmacro __using__(_) do
    quote do
      def use_test do
        IO.puts "use_test"
      end
    end
  end
end
```

og vi legger denne linjen til UseImportRequire:

```elixir
use UseImportRequire.UseMe
```

Å bruke UseImportRequire.UseMe definerer en use_test/0 funksjon gjennom invokasjon av `__using__/1` makroen.

Det er alt det use gjør. Men, det er vanlig at `__using__` makroen kaller på alias, require eller import. Dette vil lage aliaser eller importere det som kreves i using modulen. Dette tillater modulen til å bli brukt til å definere en retningslinje for hvordan deres funksjoner og makroer burde bli referert til. Dette kan være svært fleksibelt i det at `__using__/1` kan sette opp referanser til andre moduler, spesielt submoduler.

Phoenix rammeverket bruker use og `__using__/1` for å kutte ned bruken av repetitive alias og import kall i bruker definerte moduler.

Her er et godt eksempel fra Ecto.Migration modulen:

```elixir
defmacro __using__(_) do
  quote location: :keep do
    import Ecto.Migration
    @disable_ddl_transaction false
    @before_compile Ecto.Migration
  end
end
```

`Ecto.Migration.__using__/1` makroen inkluderer et importkall slik at når du bruker `use Ecto.Migration` så vil den også kalle `import Ecto.Migration`. Den setter også opp modul attributer som vi kan anta kontrollerer Ecto sin atferd.

For å oppsumere: use invokerer `__using__/1` i den spesifiserte modulen. For å virkelig forstå hva den gjør så anbefales det at du leser om `__using__/1` makroen.


text:
package j2html.tags.attributes;

import j2html.tags.IInstance;
import j2html.tags.Tag;

public interface IOnvolumechanged<T extends Tag<T>> extends IInstance<T> {
    default T withOnvolumechanged(final String onvolumechanged_) {
        return self().attr("onvolumechanged", onvolumechanged_);
    }

    default T withCondOnvolumechanged(final boolean enable, final String onvolumechanged_) {
        if (enable) {
            self().attr("onvolumechanged", onvolumechanged_);
        }
        return self();
    }
}


text:
CVE-2022-36015

### Impact
When [`RangeSize`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/math_ops.cc) receives values that do not fit into an `int64_t`, it crashes.
```cpp
  auto size = (std::is_integral<T>::value
                   ? ((Eigen::numext::abs(limit - start) +
                       Eigen::numext::abs(delta) - T(1)) /
                      Eigen::numext::abs(delta))
                   : (Eigen::numext::ceil(
                         Eigen::numext::abs((limit - start) / delta))));

  // This check does not cover all cases.
  if (size > std::numeric_limits<int64_t>::max()) {
    return errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
                                   std::numeric_limits<int64_t>::max());
  }

  c->set_output(0, c->Vector(static_cast<int64_t>(size)));
  return OkStatus();
}
```

### Patches
We have patched the issue in GitHub commit [37e64539cd29fcfb814c4451152a60f5d107b0f0](https://github.com/tensorflow/tensorflow/commit/37e64539cd29fcfb814c4451152a60f5d107b0f0).
The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range.

### For more information
Please consult [our security guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for more information regarding the security model and how to contact us with issues and questions.


text:
module.exports = function test1() {
	return 123;
};


text:
<?php

final class PonderQuestionViewController extends PonderController {

  private $questionID;

  public function willProcessRequest(array $data) {
    $this->questionID = $data['id'];
  }

  public function processRequest() {

    $request = $this->getRequest();
    $user = $request->getUser();

    $question = PonderQuestionQuery::loadSingle($user, $this->questionID);
    if (!$question) {
      return new Aphront404Response();
    }
    $question->attachRelated();
    $question->attachVotes($user->getPHID());
    $object_phids = array($user->getPHID(), $question->getAuthorPHID());

    $answers = $question->getAnswers();
    $comments = $question->getComments();
    foreach ($comments as $comment) {
      $object_phids[] = $comment->getAuthorPHID();
    }

    foreach ($answers as $answer) {
      $object_phids[] = $answer->getAuthorPHID();

      $comments = $answer->getComments();
      foreach ($comments as $comment) {
        $object_phids[] = $comment->getAuthorPHID();
      }
    }

    $subscribers = PhabricatorSubscribersQuery::loadSubscribersForPHID(
      $question->getPHID());

    $object_phids = array_merge($object_phids, $subscribers);

    $this->loadHandles($object_phids);
    $handles = $this->getLoadedHandles();

    $detail_panel = new PonderQuestionDetailView();
    $detail_panel
      ->setQuestion($question)
      ->setUser($user)
      ->setHandles($handles);

    $responses_panel = new PonderAnswerListView();
    $responses_panel
      ->setQuestion($question)
      ->setHandles($handles)
      ->setUser($user)
      ->setAnswers($answers);

    $answer_add_panel = new PonderAddAnswerView();
    $answer_add_panel
      ->setQuestion($question)
      ->setUser($user)
      ->setActionURI("/ponder/answer/add/");

    $header = id(new PhabricatorHeaderView())
      ->setHeader($question->getTitle());

    $actions = $this->buildActionListView($question);
    $properties = $this->buildPropertyListView($question, $subscribers);

    $crumbs = $this->buildApplicationCrumbs($this->buildSideNavView());
    $crumbs->setActionList($actions);
    $crumbs->addCrumb(
        id(new PhabricatorCrumbView())
          ->setName('Q'.$this->questionID)
          ->setHref('/Q'.$this->questionID));

    $nav = $this->buildSideNavView($question);
    $nav->appendChild(
      array(
        $crumbs,
        $header,
        $actions,
        $properties,
        $detail_panel,
        $responses_panel,
        $answer_add_panel
      ));
    $nav->selectFilter(null);

    return $this->buildApplicationPage(
      $nav,
      array(
        'device' => true,
        'title' => 'Q'.$question->getID().' '.$question->getTitle(),
        'dust' => true,
      ));
  }

  private function buildActionListView(PonderQuestion $question) {
    $request = $this->getRequest();
    return id(new PhabricatorActionListView())
      ->setUser($request->getUser())
      ->setObject($question)
      ->setObjectURI($request->getRequestURI());
  }

  private function buildPropertyListView(
    PonderQuestion $question,
    array $subscribers) {

    $viewer = $this->getRequest()->getUser();
    $view = id(new PhabricatorPropertyListView())
      ->setUser($viewer)
      ->setObject($question);
    $view->addProperty(
      pht('Author'),
      $this->getHandle($question->getAuthorPHID())->renderLink());

    $view->addProperty(
      pht('Created'),
      phabricator_datetime($question->getDateCreated(), $viewer));

    if ($subscribers) {
      $subscribers = $this->renderHandlesForPHIDs($subscribers);
    }

    $view->addProperty(
      pht('Subscribers'),
      nonempty($subscribers, phutil_tag('em', array(), pht('None'))));

    return $view;
  }
}


text:
module Sand
  class RequestMethods
    attr_accessor :env
    include Sand::Helpers

    def initialize(env)
      @env = env
    end
  end

  class Middleware
    attr_reader :app, :options, :response

    DEFAULT_OPTIONS = {
      pass: []
    }.freeze

    def initialize(app, options = {})
      @app = app
      @options = DEFAULT_OPTIONS.merge(options)
    end

    def passed?(env)
      return true if options[:pass].any? { |r| r =~ env['PATH_INFO'] }
      return true if env['sand.pass'] == true || env['sand.scoped'] || env['sand.authorized'] == true # rubocop:disable Metrics/LineLength
      false
    end

    def call(env)
      env['sand'] = RequestMethods.new(env)

      result = app.call(env)

      return result if passed?(env)
      raise Sand::AuthorizationNotPerformed
    end
  end
end


text:
require 'faraday'
require 'faraday_middleware'

module Dota
  module API
    class Client
      def configuration
        @configuration ||= Configuration.new
      end

      def configure
        yield configuration
      end

      def heroes(id = nil)
        id ? Hero.new(id) : Hero.all
      end

      def items(id = nil)
        id ? Item.new(id) : Item.all
      end

      def matches(options = {})
        if options.is_a?(Integer)
          id = options
          response = get("IDOTA2Match_570", "GetMatchDetails", match_id: id)["result"]
          Match.new(response) if response
        else
          options[:game_mode]             = options.delete(:mode_id) if options[:mode_id]
          options[:skill]                 = options.delete(:skill_level) if options[:skill_level]
          options[:date_min]              = options.delete(:from) if options[:from]
          options[:date_max]              = options.delete(:to) if options[:to]
          options[:account_id]            = options.delete(:player_id) if options[:player_id]
          options[:start_at_match_id]     = options.delete(:after) if options[:after]
          options[:matches_requested]     = options.delete(:limit) if options[:limit]
          options[:tournament_games_only] = options.delete(:league_only) if options[:league_only]

          response = get("IDOTA2Match_570", "GetMatchHistory", options)["result"]
          if response && (matches = response["matches"])
            matches.map { |match| Match.new(match) }
          end
        end
      end

      def leagues
        response = get("IDOTA2Match_570", "GetLeagueListing", language: "en")["result"]
        if response && (leagues = response["leagues"])
          leagues.map { |league| League.new(league) }
        end
      end

      def cosmetic_rarities
        response = get("IEconDOTA2_570", "GetRarities", language: "en")["result"]
        if response && (rarities = response["rarities"])
          rarities.map { |rarity| Cosmetic::Rarity.new(rarity) }
        end
      end

      def friends(user_id)
        response = get("ISteamUser", "GetFriendList", steamid: user_id)["friendslist"]
        if response && (friends = response["friends"])
          friends.map { |friend| Friend.new(friend) }
        end
      end

      def get(interface, method, params = {}, *args)
        do_request(method, params, interface, *args)
      end

      private

      def do_request(method, params, interface = "IDOTA2Match_570", method_version = "V001")
        url = "https://api.steampowered.com/#{interface}/#{method}/#{method_version}/"

        @faraday = Faraday.new(url) do |faraday|
          faraday.response :json
          faraday.adapter Faraday.default_adapter
        end

        response = @faraday.get do |request|
          request.url(url, params.merge(key: configuration.api_key))
        end
        response.body
      end
    end
  end
end


text:
{% extends "base-documentation.html" %}

{% block documentation %}

Metrics

Liftpass is designed to track up to 32 metrics that reflect the progress and profile of the user. The metrics are subdivided into 8 string values metrics and 24 numeric values. Metrics are represented as part of an array of 32 elements, and consequently the 32 metrics Liftpass can track have integer index values. Once the metrics for the application are defined for the application they can be referenced in the code by their index value - the first 8 index values represent the 8 string values, followed by the 24 numeric values. This means the 9th metric is the first numeric progress metric.

		Index
		1
		2
		3
		4
		5
		6
		7
		8
		9
		10
		11
		12
		13
		14
		15
		16
		17
		18
		19
		20
		21
		22
		23
		24
		25
		26
		27
		28
		29
		30
		31
		32

		Type

			String

			Number

Metrics are propagated as a series of 32 elements through all other events that are trigered in the game. This means that even when a virtual good is purchased, information about the 32 progress metrics is also contained with the virtual goods purchase event.

Not all 32 progress metrics must be defined for the application. Non-defined metrics take the value of Null and are ignored by the SDK and Liftpass, however the array representation of the 32 progress metrics always contains 32 elements.

Metric Pipes

Certain commonly used metrics are automatically tracked by Liftpass SDK. It is up to the developer however to choose to use them in the analytics. This is done by directing the internally tracked metrics to an index position of the metrics registered by the application. Whenever another progress metric is updated, or purchase event is triggered, the piped metrics will automatically update themselves.

The currently supported metric pipes are:

Operating system name

Operating system version

Device name

Timezone

Device language

Total number of sessions

Total number of seconds played

Number of virtual goods purchased

Number of in-app purchases

Total virtual currency spent (broken down into the individual 8 currencies Liftpass tracks)

Total Dollars spent by the user in the game

In order to use one of these pipes, they must be configured in the code at the time the SDK is first initialized. This involves registering with the SDK where the value of the pipe should be directed to, more specifically which metric the value should be recorded to.

In the native iOS SDK this is how to direct the total number of virtual goods purchased to the 14th progress metric:

{% highlight 'objective-c' %}
[[Liftpass sharedInstance] setNumberPipe:LiftpassTotalVirtualPurchases toMetric:14];
{% endhighlight %}

In Liftpass the developer should also record the fact that progress metric 14 represents the total number of virtual goods purchased.

{% endblock %}


text:
package org.sourcepit.common.utils.io.handles.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.sourcepit.common.utils.io.handles.InputStreamHandle;

public class ClassPathInputStreamHandleImpl implements InputStreamHandle
{
   private ClassLoader classLoader;
   private String name;

   public ClassPathInputStreamHandleImpl(ClassLoader classLoader, String name)
   {
      this.classLoader = classLoader;
      this.name = name;
   }

   public InputStream open() throws IOException
   {
      final InputStream resourceAsStream = classLoader.getResourceAsStream(name);
      if (resourceAsStream == null)
      {
         throw new FileNotFoundException(name);
      }
      return resourceAsStream;
   }

}