text:
using base::ASCIIToUTF16;
using content::WebContents;

namespace {

static const char kSimplePage[] = "/find_in_page/simple.html";

class FindInPageTest : public InProcessBrowserTest {
 public:
  FindInPageTest() {
    FindBarHost::disable_animations_during_testing_ = true;
  }

  base::string16 GetFindBarText() {
    FindBar* find_bar = browser()->GetFindBarController()->find_bar();
    return find_bar->GetFindText();
  }

  base::string16 GetFindBarSelectedText() {
    FindBarTesting* find_bar =
        browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
    return find_bar->GetFindSelectedText();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(FindInPageTest);
};

}  // namespace

// Flaky because the test server fails to start? See: http://crbug.com/96594.
IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = embedded_test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  chrome::Find(browser());

  // Open another tab (tab B).
  chrome::AddSelectedTabWithURL(browser(), url, ui::PAGE_TRANSITION_TYPED);

  chrome::Find(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Select tab A.
  browser()->tab_strip_model()->ActivateTabAt(0, true);

  // Close tab B.
  browser()->tab_strip_model()->CloseWebContentsAt(1,
                                                   TabStripModel::CLOSE_NONE);

  // Click on the location bar so that Find box loses focus.
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_OMNIBOX));
  // Check the location bar is focused.
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));

  // This used to crash until bug 1303709 was fixed.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, NavigationByKeyEvent) {
  ASSERT_TRUE(embedded_test_server()->Start());
  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  // First we navigate to any page.
  ui_test_utils::NavigateToURL(browser(),
                               embedded_test_server()->GetURL(kSimplePage));
  // Show the Find bar.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("a"),
      true, false, NULL, NULL);

  // The previous button should still be focused after pressing [Enter] on it.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_TAB, false,
                                              false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_RETURN, false,
                                              false, false, false));
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(),
      VIEW_ID_FIND_IN_PAGE_PREVIOUS_BUTTON));

  // The next button should still be focused after pressing [Enter] on it.
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("b"),
      true, false, NULL, NULL);
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_TAB, false,
                                              false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_RETURN, false,
                                              false, false, false));
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(),
      VIEW_ID_FIND_IN_PAGE_NEXT_BUTTON));
}

// TODO(mpistrich): Enable again when ui_test_utils::ClickOnView works with find
// bar view IDs.
// http://crbug.com/584043
IN_PROC_BROWSER_TEST_F(FindInPageTest, DISABLED_NavigationByMouse) {
  ASSERT_TRUE(embedded_test_server()->Start());
  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  // First we navigate to any page.
  ui_test_utils::NavigateToURL(browser(),
                               embedded_test_server()->GetURL(kSimplePage));
  // Show the Find bar.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(), ASCIIToUTF16("a"),
      true, false, NULL, NULL);

  // The textfield should be focused after clicking on any button.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_FIND_IN_PAGE_PREVIOUS_BUTTON);
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(),
      VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // The textfield should be focused after clicking on any button.
  ui_test_utils::ClickOnView(browser(), VIEW_ID_FIND_IN_PAGE_NEXT_BUTTON);
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(),
      VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, ButtonsDisabledWithoutText) {
  ASSERT_TRUE(embedded_test_server()->Start());
  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  // First we navigate to any page.
  ui_test_utils::NavigateToURL(browser(),
                               embedded_test_server()->GetURL(kSimplePage));
  // Show the Find bar.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(
      ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // The buttons should be disabled as there is no text entered in the find bar
  // and no search has been issued yet.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_TAB, false,
                                              false, false, false));
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_CLOSE_BUTTON));
}

#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
// TODO(erg): linux_aura bringup: http://crbug.com/163931
#define MAYBE_FocusRestore DISABLED_FocusRestore
#else
#define MAYBE_FocusRestore FocusRestore
#endif

// Flaky because the test server fails to start? See: http://crbug.com/96594.
IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_FocusRestore) {
  ASSERT_TRUE(embedded_test_server()->Start());

  GURL url = embedded_test_server()->GetURL("/title1.html");
  ui_test_utils::NavigateToURL(browser(), url);

  // Focus the location bar, open and close the find-in-page, focus should
  // return to the location bar.
  chrome::FocusLocationBar(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));
  // Ensure the creation of the find bar controller.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelectionOnPage,
      FindBarController::kKeepResultsInFindBox);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));

  // Focus the location bar, find something on the page, close the find box,
  // focus should go to the page.
  chrome::FocusLocationBar(browser());
  chrome::Find(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ASCIIToUTF16("a"), true, false, NULL, NULL);
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelectionOnPage,
      FindBarController::kKeepResultsInFindBox);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));

  // Focus the location bar, open and close the find box, focus should return to
  // the location bar (same as before, just checking that http://crbug.com/23599
  // is fixed).
  chrome::FocusLocationBar(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelectionOnPage,
      FindBarController::kKeepResultsInFindBox);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));
}

// TODO(phajdan.jr): Disabling due to possible timing issues on XP
// interactive_ui_tests.
// http://crbug.com/311363
IN_PROC_BROWSER_TEST_F(FindInPageTest, DISABLED_SelectionRestoreOnTabSwitch) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // First we navigate to any page in the current tab (tab A).
  GURL url = embedded_test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  // Search for "abc".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_B, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_C, false, false, false, false));
  EXPECT_EQ(ASCIIToUTF16("abc"), GetFindBarText());

  // Select "bc".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_LEFT, false, true, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_LEFT, false, true, false, false));
  EXPECT_EQ(ASCIIToUTF16("bc"), GetFindBarSelectedText());

  // Open another tab (tab B).
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  chrome::AddSelectedTabWithURL(browser(), url, ui::PAGE_TRANSITION_TYPED);
  observer.Wait();

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  // Search for "def".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_D, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_E, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F, false, false, false, false));
  EXPECT_EQ(ASCIIToUTF16("def"), GetFindBarText());

  // Select "de".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_HOME, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_RIGHT, false, true, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_RIGHT, false, true, false, false));
  EXPECT_EQ(ASCIIToUTF16("de"), GetFindBarSelectedText());

  // Select tab A. Find bar should select "bc".
  browser()->tab_strip_model()->ActivateTabAt(0, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  EXPECT_EQ(ASCIIToUTF16("bc"), GetFindBarSelectedText());

  // Select tab B. Find bar should select "de".
  browser()->tab_strip_model()->ActivateTabAt(1, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  EXPECT_EQ(ASCIIToUTF16("de"), GetFindBarSelectedText());
}

#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
// TODO(erg): linux_aura bringup: http://crbug.com/163931
#define MAYBE_FocusRestoreOnTabSwitch DISABLED_FocusRestoreOnTabSwitch
#else
#define MAYBE_FocusRestoreOnTabSwitch FocusRestoreOnTabSwitch
#endif

// Flaky because the test server fails to start? See: http://crbug.com/96594.
IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_FocusRestoreOnTabSwitch) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = embedded_test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  chrome::Find(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for 'a'.
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ASCIIToUTF16("a"), true, false, NULL, NULL);
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());

  // Open another tab (tab B).
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  chrome::AddSelectedTabWithURL(browser(), url, ui::PAGE_TRANSITION_TYPED);
  observer.Wait();

  // Make sure Find box is open.
  chrome::Find(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for 'b'.
  ui_test_utils::FindInPage(
      browser()->tab_strip_model()->GetActiveWebContents(),
      ASCIIToUTF16("b"), true, false, NULL, NULL);
  EXPECT_EQ(ASCIIToUTF16("b"), GetFindBarSelectedText());

  // Set focus away from the Find bar (to the Location bar).
  chrome::FocusLocationBar(browser());
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));

  // Select tab A. Find bar should get focus.
  browser()->tab_strip_model()->ActivateTabAt(0, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());

  // Select tab B. Location bar should get focus.
  browser()->tab_strip_model()->ActivateTabAt(1, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_OMNIBOX));
}

// FindInPage on Mac doesn't use prepopulated values. Search there is global.
#if !defined(OS_MACOSX) && !defined(USE_AURA)
// Flaky because the test server fails to start? See: http://crbug.com/96594.
// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121. For Aura see bug http://crbug.com/292299.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // First we navigate to any page.
  GURL url = embedded_test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  // Delete "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_BACK, false, false, false, false));

  // Validate we have cleared the text.
  EXPECT_EQ(base::string16(), GetFindBarText());

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  // After the Find box has been reopened, it should not have been prepopulated
  // with "a" again.
  EXPECT_EQ(base::string16(), GetFindBarText());

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  // Press F3 to trigger FindNext.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F3, false, false, false, false));

  // After the Find box has been reopened, it should still have no prepopulate
  // value.
  EXPECT_EQ(base::string16(), GetFindBarText());
}
#endif

// Flaky on Win. http://crbug.com/92467
// Flaky on ChromeOS. http://crbug.com/118216
// Flaky on linux aura. http://crbug.com/163931
#if defined(TOOLKIT_VIEWS)
#define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange
#else
#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange
#endif

IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {
  ASSERT_TRUE(embedded_test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // First we navigate to any page.
  GURL url = embedded_test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  // Reload the page to clear the matching result.
  chrome::Reload(browser(), CURRENT_TAB);

  // Focus the Find bar again to make sure the text is selected.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // "a" should be selected.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());

  // Press Ctrl-C to copy the content.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_C, true, false, false, false));

  base::string16 str;
  ui::Clipboard::GetForCurrentThread()->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE,
                                                 &str);

  // Make sure the text is copied successfully.
  EXPECT_EQ(ASCIIToUTF16("a"), str);

  // Press Ctrl-V to paste the content back, it should start finding even if the
  // content is not changed.
  content::Source<WebContents> notification_source(
      browser()->tab_strip_model()->GetActiveWebContents());
  ui_test_utils::WindowedNotificationObserverWithDetails
      <FindNotificationDetails> observer(
          chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_V, true, false, false, false));

  ASSERT_NO_FATAL_FAILURE(observer.Wait());
  FindNotificationDetails details;
  ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));
  EXPECT_TRUE(details.number_of_matches() > 0);
}

#if defined(OS_WIN)
// TODO(phajdan.jr): Disabling due to possible timing issues on XP
// interactive_ui_tests.
// http://crbug.com/311363
IN_PROC_BROWSER_TEST_F(FindInPageTest, DISABLED_CtrlEnter) {
  ui_test_utils::NavigateToURL(browser(),
                               GURL("data:text/html,This is some text with a "
                                    "link."));

  browser()->GetFindBarController()->Show();

  // Search for "link".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_L, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_I, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_N, false, false, false, false));
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_K, false, false, false, false));
  EXPECT_EQ(ASCIIToUTF16("link"), GetFindBarText());

  ui_test_utils::UrlLoadObserver observer(
      GURL("about:blank"), content::NotificationService::AllSources());

  // Send Ctrl-Enter, should cause navigation to about:blank.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_RETURN, true, false, false, false));

  observer.Wait();
}
#endif


text:
/**
 * @jsx React.DOM
 */
'use strict';

var React = require('react'),
  GreatestHitsTable = require('./GreatestHitsTable'),
  RecordApi = require('../helpers/RecordApi');

RecordApi.receiveRecords();

React.render(
  <GreatestHitsTable />,
  document.getElementById('facebook')
);

redpajama_set_name: RedPajamaGithub


text:
'use strict';
angular.module('eccApp')
	.factory('ShoeFactory', ['$http', '$q',
		function ($http, $q) {
			var SHOES_JSON = '/models/shoes/shoes.json';

			return {
				getAll: function () {
					var deferred = $q.defer();
					$http.get(SHOES_JSON)
						.then(
							function (response) {
								deferred.resolve(response.data);
							},
							function (error) {
								deferred.reject(error);
							});
					return deferred.promise;
				},
				getById: function (shoeId) {
					var deferred = $q.defer();
					$http.get(SHOES_JSON)
						.then(
							function (response) {
								for (var i = 0; i < response.data.length; i++) {
									if (response.data[i].nameUrl === shoeId) {
										deferred.resolve(response.data[i]);
									}
								}
								deferred.reject({
									error: 'Unable to find selected shoe.',
									shoeId: shoeId
								});
							},
							function (error) {
								deferred.reject(error);
							});
					return deferred.promise;
				}
			};
		}
	]);


text:
/** 466. Count The Repetitions
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, ¡°abc¡±  can be obtained from ¡°abdbec¡± based on our definition, but it can not be obtained from ¡°acbbe¡±.
You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.

Example:

Input:
s1="acb", n1=4
s2="ab", n2=2

Return:
2

**/

#include <iostream>
#include "../utils.h"
using namespace std;

class Solution {
public:
    int getMaxRepetitions(string s1, int n1, string s2, int n2) {

    }
};

int main() {
    Solution s;
    return 0;
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <link rel="icon" href="favicons/favicon.ico">
  <title>PARA</title>

  <link href="css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/para.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/cards.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/main.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/social.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/spin.css" type="text/css" rel="stylesheet" >
  <link href="css/font-awesome.min.css" rel="stylesheet">

	Ben Collins

First Sidebar Link

Second Sidebar Link

          Projects

Project 1

Project 2

Project 3

Project 4

Project 5

Project 6

Project 7

Divided

First Sidebar Link

Second Sidebar Link

Projects

Project 1

Project 2

Project 3

Project 4

Project 5

Project 6

Project 7

Divided

Ben Collins Front End Developer

Project 1: Build a Portfolio Site

Build a Portfolio Site

                                        Email {{u.user.email}}

                                        Password {{u.user.password}}

                                        Phone {{u.user.phone}}

                                        Location {{u.user.location.city}}, {{u.user.location.state}}

Project 2: Online Resume

Online Resume

                                        Email {{u.user.email}}

                                        Password {{u.user.password}}

                                        Phone {{u.user.phone}}

                                        Location {{u.user.location.city}}, {{u.user.location.state}}

Project 1: Build a Portfolio Site

Build a Portfolio Site

											For now this is just my template for the future projects I will be creating while completing my Udacity Nanodegree. This portfolio was built using the Bootstrap framework and Font Awesome. I've added some additional customizations too! My main focus is on mobility. This page will be endlessly modified and updated as I learn more throughout this program. Please don't consider this a "finished" product at this point. Take a look at my projects below.

                                        Password {{u.user.password}}

                                        Phone {{u.user.phone}}

                                        Location {{u.user.location.city}}, {{u.user.location.state}}

Project 2: Online Resume

Build a Portfolio Site

											For now this is just my template for the future projects I will be creating while completing my Udacity Nanodegree. This portfolio was built using the Bootstrap framework and Font Awesome. I've added some additional customizations too! My main focus is on mobility. This page will be endlessly modified and updated as I learn more throughout this program. Please don't consider this a "finished" product at this point. Take a look at my projects below.

                                        Password {{u.user.password}}

                                        Phone {{u.user.phone}}

                                        Location {{u.user.location.city}}, {{u.user.location.state}}

Lorem ipsum dolor sit amet.

Developer

Lorem ipsum dolor sit amet.

Video Editor

Lorem ipsum dolor sit amet.

Support Asst.

Lorem ipsum dolor sit amet.

      Title

First Line

         Second Line

      web

      folder
      Title

First Line

         Second Line

      grade

      insert_chart
      Title

First Line

         Second Line

      grade

      play_arrow
      Title

First Line

         Second Line

      grade

Projects

Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling.

              Project 1

Build a Portfolio Site

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

              Project 2

Online Resume

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

            Project 3

Classic Arcade Game Clone

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

              Project 4

Website Optimization

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

              Project 5

Neighborhood Map Project

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

            Project 6

Feed Reader Testing

I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.

Company Bio

We are a team of college students working on this project like it's our full time job. Any amount would help support and continue development on this project and is greatly appreciated.

Social Connect

Connect

Link 1

Link 2

Link 3

Link 4

    Made by Ben Collins


text:
class CVehicleModificationParams
{
public:
	CVehicleModificationParams();
	CVehicleModificationParams( XmlNodeRef xmlVehicleData, const char* modificationName );
	virtual ~CVehicleModificationParams();

	template< typename T >
	void ApplyModification( const char* nodeId, const char* attrName, T& attrValueOut ) const
	{
		XmlNodeRef modificationNode = GetModificationNode( nodeId, attrName );
		if ( modificationNode )
		{
			modificationNode->getAttr( "value", attrValueOut );
		}
	}

private:
	void InitModification( XmlNodeRef xmlModificationData );

	static XmlNodeRef FindModificationNodeByName( const char* name, XmlNodeRef xmlModificationsGroup );

	void InitModificationElem( XmlNodeRef xmlElem );

	virtual XmlNodeRef GetModificationNode( const char* nodeId, const char* attrName ) const;

private:
	struct Implementation;
	Implementation* m_pImpl;
};

#endif


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	protected $_endpoint_list = array (
			'installation' => '/install',
			'access_token' => '/access_token',
			'whoami' => '/whoami',
			'echome' => '/echome',
			'list' => '/list',
			'map' => '/map',
			'computing' => '/computing',
		);

	public function index() {
		$this->output->set_content_type('application/json; charset=utf-8');
		$data['usage'] = $this->_endpoint_list;
		$this->load->view('usage', $data);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/blue_wood_background">

    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/movieContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lvMovies"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>


text:
package org.apache.drill.exec.udfs;

import org.apache.drill.categories.SqlFunctionTest;
import org.apache.drill.categories.UnlikelyTest;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.physical.rowSet.RowSet;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.rpc.RpcException;
import org.apache.drill.test.ClusterFixture;
import org.apache.drill.test.ClusterFixtureBuilder;
import org.apache.drill.test.ClusterTest;
import org.apache.drill.test.QueryBuilder;
import org.apache.drill.test.rowSet.RowSetComparison;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.apache.drill.test.rowSet.RowSetUtilities.mapArray;
import static org.apache.drill.test.rowSet.RowSetUtilities.strArray;
import static org.junit.Assert.assertEquals;

@Category({UnlikelyTest.class, SqlFunctionTest.class})
public class TestComplexSchemaFunctions extends ClusterTest {

  @BeforeClass
  public static void setup() throws Exception {
    ClusterFixtureBuilder builder = ClusterFixture.builder(dirTestWatcher);
    startCluster(builder);
  }

  @Test
  public void testMapSchemaFunction() throws RpcException {
    String sql = "SELECT getMapSchema(record) AS schema FROM cp.`json/nestedSchema.json`";

    QueryBuilder q = client.queryBuilder().sql(sql);
    RowSet results = q.rowSet();
    assertEquals(results.rowCount(), 1);

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addMap("schema")
          .addNullable("int_field", MinorType.VARCHAR)
          .addNullable("double_field", MinorType.VARCHAR)
          .addNullable("string_field", MinorType.VARCHAR)
          .addNullable("boolean_field", MinorType.VARCHAR)
          .addNullable("int_list", MinorType.VARCHAR)
          .addNullable("double_list", MinorType.VARCHAR)
          .addNullable("boolean_list", MinorType.VARCHAR)
          .addNullable("map", MinorType.VARCHAR)
          .addNullable("repeated_map", MinorType.VARCHAR)
        .resumeSchema()
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow((Object)strArray("BIGINT", "FLOAT8", "VARCHAR", "BIT", "REPEATED_BIGINT", "REPEATED_FLOAT8", "REPEATED_BIT", "MAP", "REPEATED_MAP"))
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testMapSchemaFunctionWithInnerMap() throws RpcException {
    String sql = "SELECT getMapSchema(t1.record.map) AS schema FROM cp.`json/nestedSchema.json` AS t1";

    QueryBuilder q = client.queryBuilder().sql(sql);
    RowSet results = q.rowSet();
    assertEquals(results.rowCount(), 1);

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addMap("schema")
          .addNullable("nested_int_field", MinorType.VARCHAR)
          .addNullable("nested_double_field", MinorType.VARCHAR)
          .addNullable("nested_string_field", MinorType.VARCHAR)
        .resumeSchema()
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow((Object)strArray("BIGINT", "FLOAT8", "VARCHAR"))
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testMapSchemaFunctionWithNull() throws RpcException {
    String sql = "SELECT getMapSchema(null) AS schema FROM cp.`json/nestedSchema.json` AS t1";

    QueryBuilder q = client.queryBuilder().sql(sql);
    RowSet results = q.rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("schema", MinorType.MAP)
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow((Object) mapArray())
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }
}


text:
require "pry"

module Guard
  module Commands
    class Pause
      def self.import
        Pry::Commands.create_command "pause" do
          group "Guard"
          description "Toggles the file listener."

          banner <<-BANNER
          Usage: pause

          Toggles the file listener on and off.

          When the file listener is paused, the default Guard Pry
          prompt will show the pause sign `[p]`.
          BANNER

          def engine # rubocop:disable Lint/NestedMethodDefinition
            Thread.current[:engine]
          end

          def process # rubocop:disable Lint/NestedMethodDefinition
            engine.async_queue_add([:pause])
          end
        end
      end
    end
  end
end


text:
package org.gluu.oxtrust.model.scim2.provider.config;

import org.gluu.oxtrust.model.scim2.annotations.Attribute;
import org.gluu.oxtrust.model.scim2.AttributeDefinition;

/**
 * This class represents the authenticationSchemes complex attribute in the Service Provider Config
 * (see section 5 of RFC 7643).
 */
/*
 * Updated by jgomer on 2017-10-21
 */
public class AuthenticationScheme {

    @Attribute(description = "The authentication scheme.",
            isRequired = true,
            canonicalValues = {"oauth", "oauth2", "oauthbearertoken", "httpbasic", "httpdigest", "uma"},
            mutability = AttributeDefinition.Mutability.READ_ONLY)
    private String type;

    @Attribute(description = "The common authentication scheme name, e.g., HTTP Basic.",
            isRequired = true,
            mutability = AttributeDefinition.Mutability.READ_ONLY)
	private String name;

    @Attribute(description = "A description of the authentication scheme.",
            isRequired = true,
            mutability = AttributeDefinition.Mutability.READ_ONLY)
	private String description;

    @Attribute(description = "An HTTP-addressable URL pointing to the authentication scheme's specification.",
            mutability = AttributeDefinition.Mutability.READ_ONLY)
	private String specUri;

    @Attribute(description = "An HTTP-addressable URL pointing to the authentication scheme's usage documentation.",
            mutability = AttributeDefinition.Mutability.READ_ONLY)
	private String documentationUri;

    @Attribute(description = "Whether it's the preferred authentication scheme for service usage",
            mutability = AttributeDefinition.Mutability.READ_ONLY,
            type = AttributeDefinition.Type.BOOLEAN)
    private boolean primary;

    /**
     * Creates an instance of AuthenticationScheme with all its fields unassigned.
     */
    public AuthenticationScheme(){}

	/**
	 * Creates an instance of AuthenticationScheme using the parameter values passed.
	 * @param name The common authentication scheme name.
	 * @param description The description of the authentication scheme.
	 * @param specUri An HTTP addressable URL pointing to the authentication scheme's specification.
	 * @param documentationUri An HTTP addressable URL pointing to the authentication scheme's usage documentation.
	 * @param type The type of authentication scheme, e.g. "oauthbearertoken", "httpbasic", etc.
     * @param primary A boolean value specifying if current scheme is the preference
	 */
	public AuthenticationScheme(String name, String description, String specUri,
                                String documentationUri, String type, boolean primary) {
		this.name = name;
		this.description = description;
		this.specUri = specUri;
		this.documentationUri = documentationUri;
		this.type = type;
		this.primary=primary;
	}

	/**
	 * Retrieves the name of the authentication scheme.
	 * @return The name of the authentication scheme.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Retrieves the description of the authentication scheme.
	 * @return The description of the Authentication Scheme.
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * Retrieves the HTTP URL of the authentication scheme's specification.
	 * @return A string representing a URL
	 */
	public String getSpecUri() {
		return specUri;
	}

	/**
	 * Retrieves the HTTP URL pointing of the authentication scheme's usage documentation.
     * @return A string representing a URL
	 */
	public String getDocumentationUri() {
		return documentationUri;
	}

	/**
	 * Retrieves the type of authentication scheme.
	 * @return The type of authentication scheme.
	 */
	public String getType() {
		return type;
	}

    /**
     * Whether this AuthenticationScheme is the preferred authentication scheme for service usage
     * @return A boolean value
     */
    public boolean isPrimary() {
        return primary;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setSpecUri(String specUri) {
        this.specUri = specUri;
    }

    public void setDocumentationUri(String documentationUri) {
        this.documentationUri = documentationUri;
    }

    public void setPrimary(boolean primary) {
        this.primary = primary;
    }

    /**
	 * Convenience method that creates a new AuthenticationScheme instance of type HTTP BASIC.
     * @param primary A boolean value for the "primary" field of object
	 * @return An AuthenticationScheme object
	 */
	public static AuthenticationScheme createBasic(boolean primary) {
		return new AuthenticationScheme(
				"Http Basic",
				"The HTTP Basic Access Authentication scheme. This scheme is not "
						+ "considered to be a secure method of user authentication (unless "
						+ "used in conjunction with some external secure system such as "
						+ "SSL), as the user name and password are passed over the network "
						+ "as cleartext.",
				"http://www.ietf.org/rfc/rfc2617.txt",
				"http://en.wikipedia.org/wiki/Basic_access_authentication",
				"httpbasic", primary);
	}

	/**
	 * Convenience method that creates a new AuthenticationScheme instances of type OAuth 2.
     * @param primary A boolean value for the "primary" field of object
     * @return An AuthenticationScheme object
	 */
	public static AuthenticationScheme createOAuth2(boolean primary) {
		return new AuthenticationScheme(
				"OAuth 2.0", "OAuth2 Access Token Authentication Scheme. Enabled only on 'SCIM Test Mode'.",
				"http://tools.ietf.org/html/rfc6749", "https://www.gluu.org/docs/ce/admin-guide/user-scim/",
				"oauth2", primary);
	}

	/*
	public static AuthenticationScheme createOAuth2(boolean primary) {
		return new AuthenticationScheme(
				"OAuth 2.0",
				"The OAuth 2.0 Bearer Token Authentication scheme. OAuth enables "
						+ "clients to access protected resources by obtaining an access "
						+ "token, which is defined in RFC 6750 as \"a string "
						+ "representing an access authorization issued to the client\", "
						+ "rather than using the resource owner's credentials directly.",
				"http://tools.ietf.org/html/rfc6750", "http://oauth.net/2/",
				"oauth2", primary);
	}
	*/

    /**
     * Convenience method that creates a new AuthenticationScheme instances of type UMA 2.
     * @param primary A boolean value for the "primary" field of object
     * @return An AuthenticationScheme object
     */
	public static AuthenticationScheme createUma(boolean primary) {
		return new AuthenticationScheme(
				"UMA 2.0", "UMA Authentication Scheme",
				"https://docs.kantarainitiative.org/uma/ed/oauth-uma-grant-2.0-06.html", "https://www.gluu.org/docs/ce/admin-guide/uma/",
				"uma", primary);
	}

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;

namespace PartsUnlimited.WebsiteConfiguration
{
    public interface IContentDeliveryNetworkConfiguration
    {
        string Images { get; }
        ILookup<string, string> Scripts { get; }
        ILookup<string, string> Styles { get; }
    }
}


text:
import argparse
import os.path
import functools
import numpy as np
from pyspark.mllib.linalg import SparseVector
from pyspark import SparkContext, SparkConf

import text_helpers

#TODO: implement
def getHashFunctions(n=200):
    """ generates n number of hash functions
    """
    pass

#TODO: implement
def getStopWords():
    """ returns a list of stop words
    """
    #TODO: use NLTK to get a list of stopwords
    pass

#TODO: implement
def minHash(text, hash):
    """ Returns min hash value of all hashes for a given text

    Args:
        data (RDD)
        hash (function)

    Returns:
        int: min hash value for entire data set
    """
    pass

def run(fileName, n_hashes, n_buckets):
    """ Starts the main LSH process.

    Args:
        fileName (string): path of text file to read
        n_hashes (int): number of hash functions to generate
        n_buckets (int): number of buckets to use

    Returns:
        Vector: buckets of minhash values
    """
    sc = SparkContext(conf = SparkConf())
    hashes = sc.broacast(getHashFunctions(n_hashes))

    text = sc.textFile(fileName)
    stopWords = sc.textFile('path/to/stopwords')  # Test
    cleanData = text.map(removePunctuation).subtract(stopWords).cache()

    #TODO: convert to n-grams
    #TODO: get min-hash values -> total of n_hashes runs. Implement using a
    #       partial function from functools
    #TODO: return a vector representing buckets of minhash values

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description = 'Spark LSH',
        epilog = 'LSH', add_help = 'How to use',
        prog = 'python spark-driver.py <arguments>')
    parser.add_argument("-i", "--input", required = True,
        help = "Input directory of text files.")

    # Optional parameters.
    parser.add_argument("-h", "--hashes", type = int, default = 200,
        help = "Number of hash functions to use. [DEFAULT: 200]")
    parser.add_argument("-b", "--buckets", type = int, default = 1000,
        help = "Number of buckets to use. [DEFAULT: 1000]")

    args = vars(parser.parse_args())
    n_hashes,n_buckets = args['hashes'], args['buckets']

    baseDir = os.path.join(args['input'])
    inputPath = os.path.join('<path/to/document>')  # Test
    fileName = os.path.join(baseDir, inputPath)

    run(fileName, n_hashes, n_buckets)


text:
package com.pangu.fristapp.logic;

import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;

import java.io.IOException;
import java.util.Map;

/**
 * Created by oyh on 15/12/22.
 */
public class HttpUtil {

    private static final String TAG = HttpUtil.class.getSimpleName();

    public static void post(final RequestType type, Object tag, Map<String, String> params, final HttpUtilInterface httpInterface) {

        OkHttpUtils.post()
                .url("")
                .params(params)
                .addParams("key1", "value1")
                .tag(tag)
                .build()
                .connTimeOut(30000)
                .readTimeOut(30000)
                .writeTimeOut(30000)
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response) throws IOException {
                        String string = response.body().string();
                        return string;
                    }

                    @Override
                    public void onError(Request request, Exception e) {
                        if(httpInterface != null) {
                            ResultObject resultObject = new ResultObject();
                            httpInterface.httpFinish(resultObject);
                        }
                    }

                    @Override
                    public void onResponse(Object response) {
                        String responseString = (String)response;
                        if(httpInterface != null) {
                            ResultObject resultObject = null;
                            try {
                                resultObject = JsonParse.parseData(responseString, type);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            httpInterface.httpFinish(resultObject);
                        }
                    }
                });
    }

    public static void cancel(Object tag) {
        OkHttpUtils.getInstance().cancelTag(tag);
    }
}


text:
using System;
using System.Collections.Generic;

	public interface IUserHookPayloadHandler
	{

	void handlePayload(Dictionary<string,string> payload);
	}


text:
/**
 * @ngdoc controller
 * @name Umbraco.Editors.MacroParameterPickerController
 * @function
 *
 * @description
 * The controller for the content type editor macro parameter dialog
 */

(function() {
    "use strict";

    function MacroParameterController($scope, $filter, macroResource, localizationService, editorService) {

        var vm = this;

        vm.searchTerm = "";
        vm.parameterEditors = [];
        vm.loading = false;
        vm.labels = {};

        vm.filterItems = filterItems;
        vm.showDetailsOverlay = showDetailsOverlay;
        vm.hideDetailsOverlay = hideDetailsOverlay;
        vm.pickParameterEditor = pickParameterEditor;
        vm.close = close;

        function init() {
            setTitle();
            getGroupedParameterEditors();
        }

        function setTitle() {
            if (!$scope.model.title) {
                localizationService.localize("defaultdialogs_selectEditor")
                    .then(function(data){
                        $scope.model.title = data;
                    });
            }
        }

        function getGroupedParameterEditors() {

            vm.loading = true;

            macroResource.getGroupedParameterEditors().then(function (data) {
                vm.parameterEditors = data;
                vm.loading = false;
            }, function () {
                vm.loading = false;
            });

        }

        function filterItems() {
            // clear item details
            $scope.model.itemDetails = null;

            if (vm.searchTerm) {

                var regex = new RegExp(vm.searchTerm, "i");

                var parameterEditors = filterCollection(vm.parameterEditors, regex);

                var totalResults = _.reduce(_.pluck(parameterEditors, 'count'), (m, n) => m + n, 0);

                vm.filterResult = {
                    parameterEditors: parameterEditors,
                    totalResults: totalResults
                };
            } else {
                vm.filterResult = null;
            }
        }

        function filterCollection(collection, regex) {
            return _.map(_.keys(collection), function (key) {

                var filteredEditors = $filter('filter')(collection[key], function (editor) {
                    return regex.test(editor.name) || regex.test(editor.alias);
                });

                return {
                    group: key,
                    count: filteredEditors.length,
                    parameterEditors: filteredEditors
                }
            });
        }

        function showDetailsOverlay(property) {

            var propertyDetails = {};
            propertyDetails.icon = property.icon;
            propertyDetails.title = property.name;

            $scope.model.itemDetails = propertyDetails;
        }

        function hideDetailsOverlay() {
            $scope.model.itemDetails = null;
        }

        function pickParameterEditor(selectedParameterEditor) {

            console.log("pickParameterEditor", selectedParameterEditor);
            console.log("$scope.model", $scope.model);

            $scope.model.parameter.editor = selectedParameterEditor.alias;
            $scope.model.parameter.dataTypeName = selectedParameterEditor.name;
            $scope.model.parameter.dataTypeIcon = selectedParameterEditor.icon;

            $scope.model.submit($scope.model);
        }

        function close() {
            if ($scope.model.close) {
                $scope.model.close();
            }
        }

        init();
    }

    angular.module("umbraco").controller("Umbraco.Editors.MacroParameterPickerController", MacroParameterController);

})();


text:
@interface PearsonDictionaryResponseObject : NSObject

-(id)initWithDictionary:(NSDictionary *)dictionary;

@property (nonatomic, strong) NSArray *results;
@property (nonatomic, assign) NSInteger total;

@end


text:
package com.orientechnologies.orient.server.distributed.impl.lock;

import java.util.List;

public interface OnLocksAcquired {
  void execute(List<OLockGuard> guards);
}


text:
namespace Machete.Slices
{
    public class RangeTextSlice :
        TextSlice
    {
        readonly TextSlice _slice;
        readonly int _offset;

        public RangeTextSlice(TextSlice slice, int offset)
        {
            _slice = slice;
            _offset = offset;
        }

        public ParseText Text => throw new System.NotImplementedException();

        public TextSpan SourceSpan => throw new System.NotImplementedException();
        public ParseText SourceText => throw new System.NotImplementedException();

        public bool TryGetSlice(int index, out TextSlice slice)
        {
            return _slice.TryGetSlice(_offset + index, out slice);
        }
    }
}


text:
@interface PIDemoBlogPost : NSObject <PIDemoModelProtocol>

@property(nonatomic, copy, readonly) NSString *title;
@property(nonatomic, strong, readonly) NSURL *url;

@end


text:
// Copyright (C) 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.caja.plugin;

import com.google.caja.util.CajaTestCase;
import com.google.caja.util.RhinoTestBed;

/**
 * @author mikesamuel@gmail.com (Mike Samuel)
 */
public class CssParserTest extends CajaTestCase {
  public final void testCssParser() throws Exception {
    RhinoTestBed.runJsUnittestFromHtml(html(
        fromResource("cssparser_test.html")));
  }
}


text:
.. Copyright (c) 2015-2018, Exa Analytics Development Team
.. Distributed under the terms of the Apache License 2.0

#######################################
Common Orbital Integrals
#######################################
.. automodule:: exatomic.algorithms.overlap
    :members:


text:
var pkg = require('./package');
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = require("./webpack.config.js");

delete config.entry.demo;
delete config.entry[pkg.name];

module.exports = config;


text:
namespace Caching
{
    using System;
    using System.Web;
    using System.Web.Optimization;
    using System.Web.Routing;

    public class Global : HttpApplication
    {
        internal void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

        internal void Application_End(object sender, EventArgs e)
        {
            // Code that runs on application shutdown
        }

        internal void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
        }
    }
}


text:
<?php

namespace Orchestra\Notifier\Tests\Feature;

use Illuminate\Container\Container;
use Illuminate\Queue\SerializableClosure;
use Mockery as m;
use Psr\Log\LoggerInterface;

class MailerTest extends TestCase
{
    /** @test */
    public function it_can_push_mail()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->twice()->with('email.queue', false)->twice()->andReturn(false)
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->twice()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->push('foo.bar', ['foo' => 'foobar'], ''));
        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->push('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_push_mail_using_queue()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));
        $this->app->instance('queue', $queue = m::mock('Illuminate\Contracts\Queue\Factory'));

        $manager->shouldReceive('driver')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->once()->with('email.queue', false)->once()->andReturn(true)
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $with = [
            'view' => 'foo.bar',
            'data' => ['foo' => 'foobar'],
            'callback' => function () {
                //
            },
        ];

        $queue->shouldReceive('push')->once()
            ->with('orchestra.postal@handleQueuedMessage', m::type('Array'), m::any())->andReturn(true);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturnNull();

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->push($with['view'], $with['data'], $with['callback']));
    }

    /** @test */
    public function it_can_send_mail()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_send_mail_via_mail()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->with('mail')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_send_mail_via_sendmail()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->with('sendmail')->andReturn($mailer);

        $memory->shouldReceive('get')->with('email.sendmail', null)->once()->andReturn('/bin/sendmail -t')
            ->shouldReceive('has')->with('email.driver')->andReturn(true)
            ->shouldReceive('get')->with('email.driver')->twice()->andReturn('sendmail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_send_mail_via_smtp()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->with('smtp')->andReturn($mailer);

        $memory->shouldReceive('get')->with('email', [])->once()->andReturn([
                'host' => 'smtp.mailgun.org',
                'port' => 587,
                'encryption' => 'tls',
                'username' => 'hello@orchestraplatform.com',
            ])
            ->shouldReceive('secureGet')->with('email.password', null)->once()->andReturn(123456)
            ->shouldReceive('has')->with('email.driver')->andReturn(true)
            ->shouldReceive('get')->with('email.driver')->twice()->andReturn('smtp')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_send_mail_via_mailgun()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->with('mailgun')->andReturn($mailer);

        $memory->shouldReceive('secureGet')->with('email.secret', null)->once()->andReturn('auniquetoken')
            ->shouldReceive('has')->with('email.driver')->andReturn(true)
            ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mailgun')
            ->shouldReceive('get')->with('email.domain', null)->once()->andReturn('mailer.mailgun.org')
            ->shouldReceive('get')->with('email.guzzle', [])->once()->andReturn([])
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_can_send_mail_via_log()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));
        $this->app->instance(LoggerInterface::class, $logger = m::mock(LoggerInterface::class));

        $manager->shouldReceive('driver')->with('log')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('log')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()->with('foo.bar', ['foo' => 'foobar'], '')->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->send('foo.bar', ['foo' => 'foobar'], ''));
    }

    /** @test */
    public function it_cant_send_mail_via_invalid_transport()
    {
        $this->expectException('InvalidArgumentException');

        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->once()->andReturn('invalid')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $stub->send('foo.bar', ['foo' => 'foobar'], '');
    }

    /** @test */
    public function it_can_queue_mail()
    {
        $app = new Container();

        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));
        $this->app->instance('queue', $queue = m::mock('Illuminate\Contracts\Queue\Factory'));

        $manager->shouldReceive('driver')->with('mail')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $with = [
            'view' => 'foo.bar',
            'data' => ['foo' => 'foobar'],
            'callback' => function () {
                //
            },
        ];

        $queue->shouldReceive('push')->once()
            ->with('orchestra.postal@handleQueuedMessage', m::type('Array'), m::any())->andReturn(true);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturnNull();

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->queue($with['view'], $with['data'], $with['callback']));
    }

    /** @test */
    public function it_can_queue_mail_using_custom_class_name()
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));
        $this->app->instance('queue', $queue = m::mock('Illuminate\Contracts\Queue\Factory'));

        $manager->shouldReceive('driver')->with('mail')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $with = [
            'view' => 'foo.bar',
            'data' => ['foo' => 'foobar'],
            'callback' => 'FooMailHandler@foo',
        ];

        $queue->shouldReceive('push')->once()
            ->with('orchestra.postal@handleQueuedMessage', $with, '')
            ->andReturn(true);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturnNull();

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $this->assertInstanceOf('Orchestra\Notifier\Receipt', $stub->queue($with['view'], $with['data'], $with['callback']));
    }

    /**
     * @test
     * @dataProvider queueMessageDataProvdier
     */
    public function it_can_handle_queued_mail($view, $data, $callback)
    {
        $this->app->instance('orchestra.platform.memory', $memory = m::mock('Orchestra\Contracts\Memory\Provider'));
        $this->app->instance('mail.manager', $manager = m::mock('Illuminate\Mail\MailManager'));
        $this->app->instance('mailer', $mailer = m::mock('Illuminate\Contracts\Mail\Mailer'));

        $manager->shouldReceive('driver')->with('mail')->andReturn($mailer);

        $memory->shouldReceive('has')->with('email.driver')->andReturn(true)
        ->shouldReceive('get')->with('email.driver')->twice()->andReturn('mail')
            ->shouldReceive('get')->with('email.from')->once()->andReturn([
                'address' => 'hello@orchestraplatform.com',
                'name' => 'Orchestra Platform',
            ]);

        $job = m::mock('Illuminate\Contracts\Queue\Job');

        $job->shouldReceive('delete')->once()->andReturn(null);

        $mailer->shouldReceive('setSwiftMailer')->once()->andReturn(null)
            ->shouldReceive('send')->once()
                ->with($view, $data, m::any())->andReturn(true);

        $stub = $this->app['orchestra.postal'];
        $stub->configureIlluminateMailer($this->app['mail.manager']);

        $stub->handleQueuedMessage($job, compact('view', 'data', 'callback'));
    }

    /**
     * Data provider.
     *
     * @return array
     */
    public function queueMessageDataProvdier()
    {
        SerializableClosure::setSecretKey('AckfSECXIvnK5r28GVIWUAxmbBSjTsmF');

        $callback = new SerializableClosure(function () {
            //
        });

        return [
            [
                'view' => 'foo.bar',
                'data' => ['foo' => 'foobar'],
                'callback' => serialize($callback),
            ],
            [
                'view' => 'foo.bar',
                'data' => ['foo' => 'foobar'],
                'callback' => 'hello world',
            ],
        ];
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorAccent">#FF4081</color>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <string name="app_name">AndroidUnityPlugin</string>
    <style name="AppTheme" parent="android:Theme.Light">
    </style>
</resources>


text:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>examples-users-service</artifactId>

  <parent>
    <groupId>ws.epigraph.examples</groupId>
    <artifactId>examples-users</artifactId>
    <version>${revision}</version>
  </parent>

  <dependencies>

    <!-- main dependencies -->

    <dependency>
      <groupId>${project.parent.groupId}</groupId>
      <artifactId>examples-users-schema-java</artifactId>
      <version>${project.parent.version}</version>
    </dependency>

    <!-- test dependencies -->

  </dependencies>

</project>


text:
package Problem3;
import java.util.Iterator;

/**
 * Simple linear structures, which let you add and remove items one at a time.
 *
 * @author Samuel A. Rebelsky
 */
public interface LinearStructure<T>
    extends
      Iterable<T>
{
  /**
   * Add an element to the structure.
   *
   * @param val
   *          the value to add.
   * @pre !this.isFull()
   * @post The element has been added to the structure. At some point, a call to
   *       get() will remove the element.
   * @exception Exception
   *              If the structure is full.
   */
  public void
    put (T val)
      throws Exception;

  /**
   * Remove an element from the structure according to the underlying policy.
   *
   * @return val, a value.
   * @pre !this.isEmpty()
   * @post The structure contains one fewer copy of val.
   * @exception Exception
   *              If the structure is empty.
   */
  public T
    get ()
      throws Exception;

  /**
   * Determine what element will next be removed by get.
   *
   * @return val, a value.
   * @pre !this.isEmpty()
   * @post The next call to this.get() returns val.
   * @exception Exception
   *              If the structure is empty.
   */
  public T
    peek ()
      throws Exception;

  /**
   * Determine if the structure is empty.
   */
  public boolean
    isEmpty ();

  /**
   * Determine if the structure is full.
   */
  public boolean
    isFull ();

  /**
   * Get an iterator that returns all of the elements in some order.
   */
  public Iterator<T>
    iterator ();
} // interface LinearStructure


text:
package com.blazebit.security.impl.interceptor;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import org.apache.commons.lang3.StringUtils;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.type.Type;

import com.blazebit.annotation.AnnotationUtils;
import com.blazebit.reflection.ReflectionUtils;
import com.blazebit.security.entity.EntityFeatures;
import com.blazebit.security.entity.EntityResourceFactory;
import com.blazebit.security.entity.Parent;
import com.blazebit.security.entity.EntityResourceType;
import com.blazebit.security.entity.UserContext;
import com.blazebit.security.exception.PermissionActionException;
import com.blazebit.security.model.Action;
import com.blazebit.security.model.Permission;
import com.blazebit.security.service.PermissionService;
import com.blazebit.security.spi.ActionFactory;

/**
 *
 * @author cuszk
 */
public class ChangeInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1L;

	/**
	 *
	 *
	 * @param entity
	 * @param id
	 * @param currentState
	 * @param previousState
	 * @param propertyNames
	 * @param types
	 * @return true if given entity is permitted to be flushed
	 */
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (!EntityFeatures.isInterceptorActive()) {
			return super.onFlushDirty(entity, id, currentState, previousState,
					propertyNames, types);
		}
		if (AnnotationUtils.findAnnotation(entity.getClass(),
				EntityResourceType.class) == null) {
			return super.onFlushDirty(entity, id, currentState, previousState,
					propertyNames, types);
		}
		List<String> changedPropertyNames = new ArrayList<String>();
		if (previousState != null) {
			for (int i = 0; i < currentState.length; i++) {

				// we dont check collections here, there is a separate method
				// for it See: {@link #onCollectionUpdate(collection,
				// key) onCollectionUpdate}
				if (!types[i].isCollectionType()) {
					if ((currentState[i] != null && !currentState[i]
							.equals(previousState[i]))
							|| (currentState[i] == null && previousState[i] != null)) {
						changedPropertyNames.add(propertyNames[i]);
					}
				}
			}
		}
		UserContext userContext = BeanProvider
				.getContextualReference(UserContext.class);
		ActionFactory actionFactory = BeanProvider
				.getContextualReference(ActionFactory.class);
		EntityResourceFactory resourceFactory = BeanProvider
            .getContextualReference(EntityResourceFactory.class);
		PermissionService permissionService = BeanProvider
				.getContextualReference(PermissionService.class);
		boolean isGranted = changedPropertyNames.isEmpty();
		for (String propertyName : changedPropertyNames) {
			isGranted = permissionService.isGranted(actionFactory
					.createAction(Action.UPDATE), resourceFactory
					.createResource(entity, propertyName));
			if (!isGranted) {
				break;
			}
		}
		if (isGranted) {
			return super.onFlushDirty(entity, id, currentState, previousState,
					propertyNames, types);
		} else {
			throw new PermissionActionException("Entity " + entity
					+ " is not permitted to be flushed by "
					+ userContext.getUser());
		}
	}

	/**
    *
    */
	@Override
	public void onCollectionUpdate(Object collection, Serializable key)
			throws CallbackException {
		if (!EntityFeatures.isInterceptorActive()) {
			super.onCollectionUpdate(collection, key);
			return;
		}
		if (collection instanceof PersistentCollection) {
			PersistentCollection newValuesCollection = (PersistentCollection) collection;
			Object entity = newValuesCollection.getOwner();
			if (AnnotationUtils.findAnnotation(entity.getClass(),
					EntityResourceType.class) == null) {
				super.onCollectionUpdate(collection, key);
				return;
			}
			// copy new values and old values
			@SuppressWarnings({ "unchecked", "rawtypes" })
			Collection<?> newValues = new HashSet(
					(Collection<?>) newValuesCollection.getValue());
			@SuppressWarnings({ "unchecked", "rawtypes" })
			Set<?> oldValues = new HashSet(
					((Map<?, ?>) newValuesCollection.getStoredSnapshot())
							.keySet());

			String fieldName = StringUtils.replace(
					newValuesCollection.getRole(), entity.getClass().getName()
							+ ".", "");
			UserContext userContext = BeanProvider
					.getContextualReference(UserContext.class);
			ActionFactory actionFactory = BeanProvider
					.getContextualReference(ActionFactory.class);
	        EntityResourceFactory resourceFactory = BeanProvider
	            .getContextualReference(EntityResourceFactory.class);
			PermissionService permissionService = BeanProvider
					.getContextualReference(PermissionService.class);

			// find all objects that were added
			boolean isGrantedToAdd = true;
			boolean isGrantedToRemove = true;

			@SuppressWarnings({ "unchecked", "rawtypes" })
			Set<?> retained = new HashSet(oldValues);
			retained.retainAll(newValues);

			oldValues.removeAll(retained);
			// if there is a difference between oldValues and newValues
			if (!oldValues.isEmpty()) {
				// if something remained
				isGrantedToRemove = permissionService.isGranted(actionFactory
						.createAction(Action.REMOVE),
						resourceFactory.createResource(entity,
								fieldName));
			}
			newValues.removeAll(retained);
			if (!newValues.isEmpty()) {
				isGrantedToAdd = permissionService.isGranted(actionFactory
						.createAction(Action.ADD), resourceFactory
						.createResource(entity, fieldName));
			}

			if (!isGrantedToAdd) {
				throw new PermissionActionException(
						"Element cannot be added to entity " + entity
								+ "'s collection " + fieldName + " by "
								+ userContext.getUser());
			} else {
				if (!isGrantedToRemove) {
					throw new PermissionActionException(
							"Element cannot be removed from entity " + entity
									+ "'s collection " + fieldName + " by "
									+ userContext.getUser());
				} else {
					super.onCollectionUpdate(collection, key);
					return;
				}
			}
		} else {
			// not a persistent collection?
		}
	}

	/**
 *
 */
	@Override
	public void onCollectionRecreate(Object collection, Serializable key)
			throws CallbackException {
		// TODO newly created entities with collections should be checked here
		// for permission but collection cannot give back
		// its
		// role in the parent entity. BUG? Workaround: it can be checked in the
		// #onSave(...) method
		// if (!ChangeInterceptor.active) {
		// super.onCollectionRecreate(collection, key);
		// }
		// if (collection instanceof PersistentCollection) {
		// PersistentCollection newValuesCollection = (PersistentCollection)
		// collection;
		// Object entity = newValuesCollection.getOwner();
		// if (AnnotationUtils.findAnnotation(entity.getClass(),
		// ResourceName.class) == null) {
		// super.onCollectionRecreate(collection, key);
		// }
		// if (ReflectionUtils.isSubtype(entity.getClass(), Permission.class)) {
		// throw new
		// IllegalArgumentException("Permission cannot be persisted by this persistence unit!");
		// }
		// @SuppressWarnings({ "unchecked", "rawtypes" })
		// Collection<?> newValues = new HashSet((Collection<?>)
		// newValuesCollection.getValue());
		// String fieldName = StringUtils.replace(newValuesCollection.getRole(),
		// entity.getClass().getName() + ".", "");
		// if (!newValues.isEmpty()) {
		// // element has been added to the collection - check Add permission
		// UserContext userContext =
		// BeanProvider.getContextualReference(UserContext.class);
		// ActionFactory actionFactory =
		// BeanProvider.getContextualReference(ActionFactory.class);
		// EntityResourceFactory entityFieldFactory =
		// BeanProvider.getContextualReference(EntityResourceFactory.class);
		// PermissionService permissionService =
		// BeanProvider.getContextualReference(PermissionService.class);
		// boolean isGranted =
		// permissionService.isGranted(userContext.getUser(),
		// actionFactory.createAction(Action.ADD),
		// entityFieldFactory.createResource(entity, fieldName));
		// if (!isGranted) {
		// // throw new PermissionException("Element cannot be added to Entity "
		// + entity + "'s collection " +
		// // fieldName + " by " + userContext.getUser());
		// }
		// }
		// }
		super.onCollectionRecreate(collection, key);
	}

	// it is invoked after deleting an entity with oneToMany children. method is
	// invoked after onDelete the respective child entity. kinda useless
	@Override
	public void onCollectionRemove(Object collection, Serializable key)
			throws CallbackException {
		// if (!ChangeInterceptor.active) {
		// super.onCollectionRemove(collection, key);
		// }
		// if (collection instanceof PersistentCollection) {
		// PersistentCollection newValuesCollection = (PersistentCollection)
		// collection;
		// Object entity = newValuesCollection.getOwner();
		// if (AnnotationUtils.findAnnotation(entity.getClass(),
		// ResourceName.class) == null) {
		// super.onCollectionRecreate(collection, key);
		// }
		// if (ReflectionUtils.isSubtype(entity.getClass(), Permission.class)) {
		// throw new IllegalArgumentException(
		// "Permission cannot be persisted by this persistence unit!");
		// }
		// @SuppressWarnings({ "unchecked", "rawtypes" })
		// Collection<?> newValues = new HashSet(
		// (Collection<?>) newValuesCollection.getValue());
		// String fieldName = StringUtils.replace(
		// newValuesCollection.getRole(), entity.getClass().getName()
		// + ".", "");
		// if (!newValues.isEmpty()) {
		// // element has been added to the collection - check Add
		// // permission
		// UserContext userContext = BeanProvider
		// .getContextualReference(UserContext.class);
		// ActionFactory actionFactory = BeanProvider
		// .getContextualReference(ActionFactory.class);
		// EntityResourceFactory entityFieldFactory = BeanProvider
		// .getContextualReference(EntityResourceFactory.class);
		// PermissionService permissionService = BeanProvider
		// .getContextualReference(PermissionService.class);
		// boolean isGranted = permissionService.isGranted(userContext
		// .getUser(), actionFactory
		// .createAction(Action.REMOVE),
		// entityFieldFactory.createResource(entity,
		// fieldName));
		// if (!isGranted) {
		// throw new PermissionException(
		// "Element cannot be added to Entity " + entity
		// + "'s collection " + fieldName + " by "
		// + userContext.getUser());
		// }
		// }
		// }
		super.onCollectionRemove(collection, key);
	}

	// add
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (!EntityFeatures.isInterceptorActive()) {
			return super.onSave(entity, id, state, propertyNames, types);
		}
		if (AnnotationUtils.findAnnotation(entity.getClass(),
				EntityResourceType.class) == null) {
			return super.onSave(entity, id, state, propertyNames, types);
		}
		if (ReflectionUtils.isSubtype(entity.getClass(), Permission.class)) {
			throw new IllegalArgumentException(
					"Permission cannot be persisted by this persistence unit!");
		}
		UserContext userContext = BeanProvider
				.getContextualReference(UserContext.class);
		ActionFactory actionFactory = BeanProvider
				.getContextualReference(ActionFactory.class);
        EntityResourceFactory resourceFactory = BeanProvider
            .getContextualReference(EntityResourceFactory.class);
		PermissionService permissionService = BeanProvider
				.getContextualReference(PermissionService.class);

		// check if collection relations have permission
		boolean isGrantedAddEntity = true;
		boolean isGrantedCreateRelatedEntity = true;
		boolean foundNotEmptyField = false;

		// check every field for create permission, if no field is filled out,
		// check for entity create permission
		for (int i = 0; i < state.length; i++) {
			String fieldName = propertyNames[i];
			if (types[i].isCollectionType()) {
				Collection<?> collection = (Collection<?>) state[i];
				if (!collection.isEmpty()) {
					// elements have been added
					isGrantedAddEntity = permissionService.isGranted(
							actionFactory.createAction(Action.CREATE),
							resourceFactory.createResource(
									entity, fieldName, id != null));
					if (!isGrantedAddEntity) {
						throw new PermissionActionException(
								"Element to Entity " + entity
										+ "'s collection " + fieldName
										+ " cannot be added by "
										+ userContext.getUser());
					}
				}
			} else {
				if (state[i] != null) {
					foundNotEmptyField = true;
					boolean isGranted = permissionService.isGranted(userContext
							.getUser(), actionFactory
							.createAction(Action.CREATE),
							resourceFactory.createResource(
									entity, fieldName, id != null));
					if (!isGranted) {
						throw new PermissionActionException("Entity " + entity
								+ "'s field " + fieldName
								+ " is not permitted to be persisted by "
								+ userContext.getUser());
					}
					// check relations
					if (types[i].isAssociationType()) {
						isGrantedCreateRelatedEntity = permissionService
								.isGranted(userContext.getUser(), actionFactory
										.createAction(Action.CREATE),
										resourceFactory.createResource(
												entity, fieldName, id != null));
						if (!isGrantedCreateRelatedEntity) {
							throw new PermissionActionException("Entity "
									+ entity + "'s field " + fieldName
									+ " cannot be updated by "
									+ userContext.getUser());
						}
						checkAssociation(entity, fieldName, types[i],
								Action.ADD, userContext,
								permissionService, resourceFactory,
								actionFactory);
					}

				}
			}
		}

		if (!foundNotEmptyField) {
			boolean isGranted = permissionService.isGranted(
					userContext.getUser(),
					actionFactory.createAction(Action.CREATE),
					resourceFactory.createResource(entity, id != null));
			if (!isGranted) {
				throw new PermissionActionException("Entity " + entity
						+ " is not permitted to be persisted by "
						+ userContext.getUser());
			}
		}
		return super.onSave(entity, id, state, propertyNames, types);

	}

	private void checkAssociation(Object entity, String propertyName,
			Type type, String action, UserContext userContext,
			PermissionService permissionService,
			EntityResourceFactory resourceFactory, ActionFactory actionFactory) {
		Map<Class<?>, Tuple> toBeChecked = new HashMap<Class<?>, Tuple>();
		// it can only be on collection types
		ManyToOne manyToOne;
		// look for annotation on getter level
		manyToOne = ReflectionUtils.getGetter(entity.getClass(), propertyName)
				.getAnnotation(ManyToOne.class);
		if (manyToOne == null) {
			// on field level
			manyToOne = ReflectionUtils.getField(entity.getClass(),
					propertyName).getAnnotation(ManyToOne.class);
		}

		if (manyToOne != null) {
			Object val = null;

			try {
				val = ReflectionUtils
						.getGetter(entity.getClass(), propertyName).invoke(
								entity);
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}

			if (val != null) {
				toBeChecked.put(type.getReturnedClass(), new Tuple(val,
						propertyName));
			}

		}

		for (Map.Entry<Class<?>, Tuple> entry : toBeChecked.entrySet()) {
			Class<?> c = entry.getKey();

			// TODO: We do this complicated stuff to retrieve the inverse mapping, this can be simplified
			for (Field f : ReflectionUtils.getInstanceFields(c)) {
				OneToMany oneToMany;
				if ((oneToMany = ReflectionUtils.getGetter(c, f.getName())
						.getAnnotation(OneToMany.class)) != null) {
					if (entity
							.getClass()
							.isAssignableFrom(
									ReflectionUtils
											.getResolvedFieldTypeArguments(c, f)[0])
							&& (oneToMany.mappedBy().isEmpty() ? true
									: oneToMany.mappedBy().equals(
											entry.getValue().fieldName))) {
						if (!permissionService.isGranted(userContext.getUser(),
								actionFactory.createAction(action),
								resourceFactory.createResource(
										entry.getValue().o,
										f.getName()))) {
							throw new PermissionActionException("Entity " + c
									+ "'s field " + f.getName() + " cannot be "
									+ action + "(e)d by "
									+ userContext.getUser());
						}
					}
				}
			}
		}

	}

	private Object getParent(Object entity, String propertyName) {
		Parent parent;
		// look for annotation on getter level
		parent = ReflectionUtils.getGetter(entity.getClass(), propertyName)
				.getAnnotation(Parent.class);
		if (parent == null) {
			// on field level
			parent = ReflectionUtils.getField(entity.getClass(), propertyName)
					.getAnnotation(Parent.class);
		}

		if (parent != null) {
			try {
				return ReflectionUtils
						.getGetter(entity.getClass(), propertyName).invoke(
								entity);
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
		return null;
	}

	// delete

	private static class Tuple {

		Object o;
		String fieldName;

		public Tuple(Object o, String fieldName) {
			super();
			this.o = o;
			this.fieldName = fieldName;
		}
	}

	@Override
	public void onDelete(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (!EntityFeatures.isInterceptorActive()) {
			super.onDelete(entity, id, state, propertyNames, types);
		}
		if (AnnotationUtils.findAnnotation(entity.getClass(),
				EntityResourceType.class) == null) {
			super.onDelete(entity, id, state, propertyNames, types);
		}
		if (ReflectionUtils.isSubtype(entity.getClass(), Permission.class)) {
			throw new IllegalArgumentException(
					"Permission cannot be deleted by this persistence unit!");
		}
		UserContext userContext = BeanProvider
				.getContextualReference(UserContext.class);
		ActionFactory actionFactory = BeanProvider
				.getContextualReference(ActionFactory.class);
        EntityResourceFactory resourceFactory = BeanProvider
            .getContextualReference(EntityResourceFactory.class);
		PermissionService permissionService = BeanProvider
				.getContextualReference(PermissionService.class);
		boolean isGranted = permissionService.isGranted(userContext.getUser(),
				actionFactory.createAction(Action.DELETE),
				resourceFactory.createResource(entity));
		if (!isGranted) {
			// try parent permission
			for (int i = 0; i < propertyNames.length; i++) {
				String propertyName = propertyNames[i];
				// it can only be on collection types
				if (types[i].isAssociationType()) {
					Object parent = getParent(entity, propertyName);
					if (parent != null) {
						isGranted = permissionService.isGranted(userContext
								.getUser(), actionFactory
								.createAction(Action.DELETE),
								resourceFactory
										.createResource(parent));
						break;
					}
				}
			}
		}
		if (!isGranted)
			throw new PermissionActionException("Entity " + entity
					+ " is not permitted to be deleted by "
					+ userContext.getUser());

		for (int i = 0; i < propertyNames.length; i++) {
			String propertyName = propertyNames[i];
			// it can only be on collection types
			if (types[i].isAssociationType()) {
                Object parent = getParent(entity, propertyName);
                boolean isParentGranted = false;

                // We skip associations that are annotated as our parents and provide us inherited permissions
                if (parent != null) {
                    isParentGranted = permissionService.isGranted(userContext
                                                            .getUser(), actionFactory
                                                            .createAction(Action.DELETE),
                                                            resourceFactory
                                                                    .createResource(parent));
                }

                if (!isParentGranted) {
                    checkAssociation(entity, propertyName, types[i],
						Action.REMOVE, userContext, permissionService,
						resourceFactory, actionFactory);
                }
			}
		}

		super.onDelete(entity, id, state, propertyNames, types);
	}
}


text:
/*
 * Test Reply Tracking
 */

#undef NDEBUG
#include <c-stdaux.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "bus/reply.h"

static void test_basic(void) {
        ReplyRegistry registry;
        ReplyOwner owner;
        ReplySlot *slot1, *slot2;
        int r;

        reply_registry_init(&registry);
        reply_owner_init(&owner);

        r = reply_slot_new(&slot1, &registry, &owner, NULL, NULL, 1, 1);
        c_assert(!r);

        r = reply_slot_new(&slot1, &registry, &owner, NULL, NULL, 1, 1);
        c_assert(r == REPLY_E_EXISTS);

        slot2 = reply_slot_get_by_id(&registry, 1, 1);
        c_assert(slot2 == slot1);

        slot2 = reply_slot_get_by_id(&registry, 1, 2);
        c_assert(!slot2);

        slot2 = reply_slot_get_by_id(&registry, 2, 1);
        c_assert(!slot2);

        reply_slot_free(slot1);
        reply_owner_deinit(&owner);
        reply_registry_deinit(&registry);
}

int main(int argc, char **argv) {
        test_basic();

        return 0;
}


text:
package gophercloud

import (
	"errors"
	"fmt"
	"github.com/racker/perigee"
)

func (gsp *genericServersProvider) ListFloatingIps() ([]FloatingIp, error) {
	var fips []FloatingIp

	err := gsp.context.WithReauth(gsp.access, func() error {
		url := gsp.endpoint + "/os-floating-ips"
		return perigee.Get(url, perigee.Options{
			CustomClient: gsp.context.httpClient,
			Results: &struct {
				FloatingIps *[]FloatingIp `json:"floating_ips"`
			}{&fips},
			MoreHeaders: map[string]string{
				"X-Auth-Token": gsp.access.AuthToken(),
			},
		})
	})
	return fips, err
}

func (gsp *genericServersProvider) CreateFloatingIp(pool string) (FloatingIp, error) {
	fip := new(FloatingIp)

	err := gsp.context.WithReauth(gsp.access, func() error {
		url := gsp.endpoint + "/os-floating-ips"
		return perigee.Post(url, perigee.Options{
			CustomClient: gsp.context.httpClient,
			ReqBody: map[string]string{
				"pool": pool,
			},
			Results: &struct {
				FloatingIp **FloatingIp `json:"floating_ip"`
			}{&fip},
			MoreHeaders: map[string]string{
				"X-Auth-Token": gsp.access.AuthToken(),
			},
		})
	})

	if fip.Ip == "" {
		return *fip, errors.New("Error creating floating IP")
	}

	return *fip, err
}

func (gsp *genericServersProvider) AssociateFloatingIp(serverId string, ip FloatingIp) error {
	return gsp.context.WithReauth(gsp.access, func() error {
		ep := fmt.Sprintf("%s/servers/%s/action", gsp.endpoint, serverId)
		return perigee.Post(ep, perigee.Options{
			CustomClient: gsp.context.httpClient,
			ReqBody: map[string](map[string]string){
				"addFloatingIp": map[string]string{"address": ip.Ip},
			},
			MoreHeaders: map[string]string{
				"X-Auth-Token": gsp.access.AuthToken(),
			},
			OkCodes: []int{202},
		})
	})
}

func (gsp *genericServersProvider) DeleteFloatingIp(ip FloatingIp) error {
	return gsp.context.WithReauth(gsp.access, func() error {
		ep := fmt.Sprintf("%s/os-floating-ips/%d", gsp.endpoint, ip.Id)
		return perigee.Delete(ep, perigee.Options{
			CustomClient: gsp.context.httpClient,
			MoreHeaders: map[string]string{
				"X-Auth-Token": gsp.access.AuthToken(),
			},
			OkCodes: []int{202},
		})
	})
}

type FloatingIp struct {
	Id         int    `json:"id"`
	Pool       string `json:"pool"`
	Ip         string `json:"ip"`
	FixedIp    string `json:"fixed_ip"`
	InstanceId string `json:"instance_id"`
}