text:
(function () {
	var _scope = null;

	var _options = JSON.parse(document.querySelector('body').dataset.options);
	var EJS_URL = _options.baseUrl + 'dependencies/ejs/ejs.min.js';

	_init();
	window.addEventListener('load', _init);
	document.addEventListener('voe.gridRendered', _init);

	function _init() {
		_scope = document.querySelector('.IterationTracking_DetailTracking_Grid, .TeamRoom_ListView, .WorkitemPlanning_TaskTestList_Grid');
		if (!_scope) { return; }

		var appendButtons = _scope.classList.contains('WorkitemPlanning_TaskTestList_Grid') ? _appendBacklogCopyButtons : _appendTeamsCopyButtons
		if (!document.querySelector('link[href*="copyListOfStories/styles.css"]')) {
			injectStyle(_options.componentsUrl + 'copyListOfStories/styles.css', appendButtons);
		} else {
			appendButtons();
		}
	}

	function _appendTeamsCopyButtons() {
		if (document.querySelector('.voe-btn')) { return; }

		var filters = _scope.querySelector('.filters');
		var copyForReleaseBtn = _createButton('Copy For Release');
		var copyForReviewBtn = _createButton('Copy For Review');

		filters.appendChild(copyForReleaseBtn);
		filters.appendChild(copyForReviewBtn);

		copyForReleaseBtn.addEventListener('click', function(event) {
			_handleButton('release');

			event.preventDefault();
		});
		copyForReviewBtn.addEventListener('click', function(event) {
			_handleButton('review');

			event.preventDefault();
		});
	}

	function _appendBacklogCopyButtons() {
		if (document.querySelector('.voe-btn')) { return; }

		var filters = _scope.querySelector('.filters');
		var copyBacklogBtn = _createButton('Copy Backlog');

		filters.appendChild(copyBacklogBtn);

		copyBacklogBtn.addEventListener('click', function(event) {
			_handleButton('backlog');
			event.preventDefault();
		});

	}

	function _createButton(text) {
		var button = document.createElement('div');

		button.classList.add('grid-row-btn');
		button.classList.add('voe-btn');
		button.innerText = text;

		return button;
	}

	function _handleButton(type) {
		var team = _getTeam();
		var assets = _getAssetsData().map(function(asset) {
			asset.team = team;

			return asset;
		});
		var template = _options['templateFor' + _capitalizeFirstLetter(type)];
		if (!document.querySelector('script[src="' + EJS_URL + '"]')) {
			injectScript(EJS_URL, function() {
				_copyToClipboard(_generateReport({ team: team, assets: assets }, template));
			});
		} else {
			_copyToClipboard(_generateReport({ team: team, assets: assets }, template));
		}
	}

	function _capitalizeFirstLetter(string) {
		return string.charAt(0).toUpperCase() + string.slice(1);
	}

	function _generateReport(data, template) {
		return ejs.render(template, data);
	}

	function _getAssetsData() {
		var data = [];

		document.querySelectorAll('.gridtable .nest-0').forEach(function(row) {
			data.push(_parseAsset(row));
		});

		return data;
	}

	function _parseAsset(row) {
		var assetNameLink = row.querySelector('.asset-name-link');
		var assetNumberLink = row.querySelector('.asset-number-link');
		var owners = _findByName('Owner', row);
		var status = _findByName('Status', row);
		var points = _findByName('Estimate Pts.', row);
		var priority = _findByName('Priority', row);
		var epic = _findByName('Epic', row);

		return {
			id: assetNumberLink ? assetNumberLink.innerText : '',
			type: row.getAttribute('_v1_type').toLowerCase(),
			name: assetNameLink ? assetNameLink.innerText : '',
			link: assetNameLink ? document.location.origin + assetNameLink.getAttribute('href') : '',
			owners: owners ? _parseOwners(owners) : [],
			status: status ? _parseStatus(status) : '',
			points: points ? parseFloat(points.innerText) : null,
			priority: priority ? priority.innerText.trim() : '',
			epic: epic ? epic.innerText : '',
		}
	}

	function _parseStatus(statusElement) {
		if (statusElement.querySelector('.dropdown')) {
			return statusElement.querySelector('.ddtext').innerText.trim();
		}

		return statusElement.innerText.trim();
	}

	function _parseOwners(ownersElement) {
		var owners = [];

		if (ownersElement.querySelector('.items')) {
			owners = Array.prototype.map.call(ownersElement.querySelectorAll('.item'), function(owner) {
				return owner.innerText;
			});
		} else if (ownersElement.innerText.trim()) {
			owners = ownersElement.innerText.split(',').map(v => v.trim());
		}

		return owners;
	}

	function _findByName(name, row) {
		var tableHead = row.closest('table').querySelector('thead');
		var header = tableHead.querySelector('[title*="' + name + '"]');

		if (!header) { return null; }

		return row.children[_getIndex(header)];
	}

	function _getIndex(element) {
		var i = 0;

		while((element = element.previousSibling) != null) {
			i++;
		}

		return i;
	}

	function _getTeam() {
		var h1 = document.querySelector('[data-assettype="TeamRoom"]');
		var select = document.querySelector('select[_v1_updater*="Team"]');

		if (h1) {
			return h1.innerText;
		}

		if (select) {
			var selectedIndex = select.selectedIndex;

			return select.options[selectedIndex].innerText;
		}

		return '';
	}

	function _copyToClipboard(str) {
		var element = document.createElement('textarea');

		element.value = str;
		element.setAttribute('readonly', '');
		element.style.position = 'absolute';
		element.style.left = '-9999px';
		document.body.appendChild(element);
		element.select();
		document.execCommand('copy');
		document.body.removeChild(element);
	}
}());


text:
{-# LANGUAGE ScopedTypeVariables #-}

module DH where

import Control.Monad
import Control.Applicative
import Data.Word

import qualified Data.Digest.Pure.SHA as SHA

import NumberTheory
import DuplexChannel
import Bytes
import Ciphers
import CryptoRandom
import OpenSSL.Random

-- (using 'n' in place of 'p', consistent with #36-#38)
data Params = Params { getN :: Integer, getG :: Integer }

-- concurrent threads communicating through binary channels
-- see DuplexChannel.hs

alice (Params n g) channel = do
  a <- cryptoRandomInteger 1 (n-1)
  let aa = modexp g a n     -- aa = A (not a valid identifier)
  send channel (aa :: Integer)
  (bb :: Integer) <- receive channel
  let s = modexp bb a n
      sh = decode s :: [Word8]
      key = sha256 sh
  return key

bob = alice

p33 = do
  putStrLn "\n\n==Problem 33==\n"

  let params = Params nistPrime 2
  (a,b) <- runServerClient (alice params) (bob params)
  putStrLn $ "Alice's key: " ++ show (encode a :: Hex)
  putStrLn $ "Bob's key: " ++ show (encode b :: Hex)

p34 = do
  putStrLn "\n\n==Problem 34==\n"

  let msg = decode "'test string'"

  (a,b,[a',b']) <- runMITM (alice2 msg) bob2 eve2
  putStrLn $ "Eve intercepted: " ++ encode a'
  putStrLn $ "Bob received: " ++ encode b
  putStrLn $ "Eve intercepted again: " ++ encode b'
  putStrLn $ "Alice received back: " ++ encode a

p35 = do
  putStrLn "\n\n==Problem 35==\n"

  let p = nistPrime
      msg = decode "'test string'"

  let output (a,b,[a',b']) = do
        putStrLn $ "Eve intercepted: " ++ encode a
        putStrLn $ "Bob received: " ++ encode b
        putStrLn $ "Eve intercepted again: " ++ encode b'
        putStrLn $ "Alice received back: " ++ encode a

  putStrLn "g=1"
  output =<< runMITM (alice3 msg) bob3 (eve3 1)

  putStrLn "\ng=p"
  output =<< runMITM (alice3 msg) bob3 (eve3 p)

  putStrLn "\ng=p-1"
  output =<< runMITM (alice3 msg) bob3 (eve3 (p-1))

alice2 msg channel = do
  let n = nistPrime
      g = 2

  a <- cryptoRandomInteger 1 (n-1)
  let aa = modexp g a n

  send channel (n,g,aa)
  (bb :: Integer) <- receive channel

  let s = modexp bb a n
      sh = decode s :: [Word8]
      key = take 16 $ sha1 sh

  iv <- decode <$> cryptoRandomBytes 16
  send channel =<< encrypt CBC aes key iv msg
  (msg' :: [Word8]) <- receive channel

  decrypt CBC aes key msg'

bob2 channel = do
  (n :: Integer,
   g :: Integer,
   aa :: Integer) <- receive channel

  b <- cryptoRandomInteger 1 (n-1)
  let bb = modexp g b n

  send channel bb

  let s = modexp aa b n
      sh = decode s :: [Word8]
      key = take 16 $ sha1 sh

  (ciphertext :: [Word8]) <- receive channel
  plaintext <- decrypt CBC aes key ciphertext
  iv <- decode <$> cryptoRandomBytes 16
  send channel =<< encrypt CBC aes key iv plaintext
  return plaintext

eve2 chAlice chBob = do
  (n :: Integer,
   g :: Integer,
   aa :: Integer) <- receive chAlice

  -- substitute aa -> n
  send chBob (n,g,n)

  (bb :: Integer) <- receive chBob

  -- substitute bb -> n
  send chAlice n

  (msg1 :: [Word8]) <- receive chAlice
  send chBob msg1

  (msg2 :: [Word8]) <- receive chBob
  send chAlice msg2

  let key = take 16 $ sha1 $ decode (0 :: Integer)

  sequence [decrypt CBC aes key msg1,
            decrypt CBC aes key msg2]

alice3 msg channel = do
  let n_a = nistPrime
      g_a = 2 :: Integer

  send channel (n_a, g_a)

  -- accept Bob's DH group:
  (n :: Integer,
   g :: Integer) <- receive channel

  a <- cryptoRandomInteger 1 (n-1)
  let aa = modexp g a n
  send channel (aa)
  (bb :: Integer) <- receive channel

  let s = modexp bb a n
      sh = decode s :: [Word8]
      key = take 16 $ sha1 sh

  iv <- decode <$> cryptoRandomBytes 16
  send channel =<< encrypt CBC aes key iv msg
  (msg' :: [Word8]) <- receive channel

  decrypt CBC aes key msg'

bob3 channel = do
  (n_a :: Integer,
   g_a :: Integer) <- receive channel

  -- ACK
  let (n, g) = (n_a, g_a)
  send channel (n, g)

  (aa :: Integer) <- receive channel
  b <- cryptoRandomInteger 1 (n-1)
  let bb = modexp g b n
  send channel (bb)

  let s = modexp aa b n
      sh = decode s :: [Word8]
      key = take 16 $ sha1 sh

  (ciphertext :: [Word8]) <- receive channel
  plaintext <- decrypt CBC aes key ciphertext
  iv <- decode <$> cryptoRandomBytes 16
  send channel =<< encrypt CBC aes key iv plaintext
  return plaintext

eve3 g_e chAlice chBob = do
  (n_a :: Integer,
   g_a :: Integer) <- receive chAlice

  let n = n_a

  -- substitute g_a -> g_e
  send chBob (n, g_e)
  (n_b :: Integer,
   g_b :: Integer) <- receive chBob  -- ACK
  send chAlice (n_b, g_b)

  (aa :: Integer) <- receive chAlice
  send chBob aa

  (bb :: Integer) <- receive chBob
  send chAlice bb

  (msg1 :: [Word8]) <- receive chAlice
  send chBob msg1

  (msg2 :: [Word8]) <- receive chBob
  send chAlice msg2

  let s
        | g_e == 1    = 1
        | g_e == n    = 0
        | g_e == n-1  = if (aa == n-1) && (bb == n-1)
                        then n-1
                        else 1

  let key = take 16 $ sha1 $ decode (s :: Integer)

  sequence [decrypt CBC aes key msg1,
            decrypt CBC aes key msg2]

sha1 :: [Word8] -> [Word8]
sha1 s = let (SHA.Digest bs) = SHA.sha1 $ encode s in decode bs

sha256 :: [Word8] -> [Word8]
sha256 s = let (SHA.Digest bs) = SHA.sha256 $ encode s in decode bs

redpajama_set_name: RedPajamaGithub


text:
export { default as GlobalConfig } from './global';
export { default as DatabaseConfig } from './database';
export { default as MiddlewareConfig } from './middlewares';
export { default as RouteConfig } from './routes';
export { default as RenderEngineConfig } from './render-engine';
export { default as Const } from './params/consts';
export { default as DetailCode } from './params/detail-codes';
export { default as ErrorCode } from './params/error-codes';


text:
'use strict';

var Promise = require('bluebird');
var crypto = require('crypto');
var debug = require('debug')('oada-conformance:bookmarks.spec');

var test = require('./test');

var auth = require('./auth.js');
var resources = require('./resources.js');
var config = require('../config.js').get('bookmarks');

var Formats = require('oada-formats');
var formats = new Formats();
var packs = require('../config.js').get('options:oadaFormatsPackages') || [];
packs.forEach(function(pack) {
    formats.use(require(pack));
});

test.describe('bookmarks', function(t) {
    // Have to get token corrensponding to config.login user
    return auth.getAuth(config.login).then(function(token) {

        t.test('is valid', function(t) {
            var bookmarks = resources.get('bookmarks', token);

            return formats
                .model('application/vnd.oada.bookmarks.1+json')
                .call('validate', bookmarks.get('body'))
                .nodeify(function(err) {
                    t.error(err, 'should match schema');
                })
                .catch(function() {});

        });

        // TODO: Is this required? Maybe the previous test handles this?
        t.todo('is a resource', function(t) {
            var bookmarks = resources.get('bookmarks', token).get('body');
            var id = bookmarks.get('_id');

            return id
                .tap(function(id) {
                    t.ok(id, '/bookmarks should have an `_id` field');
                })
                .tap(function(id) {
                    var resource = resources.get(id, token).get('body');

                    return Promise.join(bookmarks, resource,
                        function(bookmarks, resource) {
                            t.deepEqual(resource, bookmarks,
                                '/bookmarks should equal source resource');
                        });
                });
        });

        // TODO: Rewrite to run tests as documents are retrieved
        // currently gets *all* documents and then tests them
        t.test('has valid subdocuments', function(t) {
            return resources.getAll('bookmarks', token, function(id, res) {
                t.notEqual(res.body, undefined, 'should have a body: ' + id);

                if (res.body && res.body._id) {
                    // TODO: _meta schema?
                    t.ok(res.body._meta, 'should have _meta: ' + id);
                    t.ok(res.body._meta._metaid,
                         'should have have _metaid: ' + id);

                    var skip = false;
                    return formats
                        .model(res.type)
                        .call('validate', res.body)
                        .catch(Formats.MediaTypeNotFoundError, function(e) {
                            debug('Model for ' + e.message + ' not found');
                            skip = e.message;
                        })
                        .nodeify(function(err) {
                            t.error(err, 'should match schema: ' + id, {
                                skip: skip
                            });
                        })
                        .catch(function() {})
                        .then(function() {
                            return resources.get(res.body._id, token);
                        })
                        .get('body')
                        .nodeify(function(err, body) {
                            var bKeys = Object.keys(res.body);
                            var rKeys = Object.keys(body);
                            t.deepEqual(bKeys, rKeys,
                                    'should match /resources doc: ' + id);
                        })
                        .catch(function() {});
                }
            });
        });

        t.todo('has CORS enabled');
    });
});

test.describe('error responses', function(t) {
    return auth.getAuth(config.login).then(function(token) {
        t.test('GET with bad token', function(t) {
            return resources.get('bookmarks', token + 'foo')
                .catch(function(err) { return err; })
                .then(function(res) {
                    t.equal(res.status, 401, 'should respond 401 Unathorized');
                    t.todo('check OADA error'); // TODO: OADA error schema?
                });
        });

        t.test('GET on non-existent resource', function(t) {
            var bytes = Promise.fromNode(function(done) {
                return crypto.randomBytes(16, done);
            });

            return resources.get(bytes.call('toString', 'hex'), token)
                .catch(function(err) { return err; })
                .then(function(res) {
                    // TODO: Does the status code matter?
                    t.is.within(res.status, 399, 500,
                                'should respond with 4xx code');
                    //t.equal(res.status, 404, 'responds 404 Not Found');
                    t.todo('check OADA error'); // TODO: OADA error schema?
                });
        });
    });
});


text:
package server

import (
	"context"
	"crypto/rand"
	"crypto/rsa"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"gopkg.in/square/go-jose.v2"

	"github.com/dexidp/dex/storage"
	"github.com/dexidp/dex/storage/memory"
)

func TestParseAuthorizationRequest(t *testing.T) {
	tests := []struct {
		name                   string
		clients                []storage.Client
		supportedResponseTypes []string

		usePOST bool

		queryParams map[string]string

		wantErr bool
	}{
		{
			name: "normal request",
			clients: []storage.Client{
				{
					ID:           "foo",
					RedirectURIs: []string{"https://example.com/foo"},
				},
			},
			supportedResponseTypes: []string{"code"},
			queryParams: map[string]string{
				"client_id":     "foo",
				"redirect_uri":  "https://example.com/foo",
				"response_type": "code",
				"scope":         "openid email profile",
			},
		},
		{
			name: "POST request",
			clients: []storage.Client{
				{
					ID:           "foo",
					RedirectURIs: []string{"https://example.com/foo"},
				},
			},
			supportedResponseTypes: []string{"code"},
			queryParams: map[string]string{
				"client_id":     "foo",
				"redirect_uri":  "https://example.com/foo",
				"response_type": "code",
				"scope":         "openid email profile",
			},
			usePOST: true,
		},
		{
			name: "invalid client id",
			clients: []storage.Client{
				{
					ID:           "foo",
					RedirectURIs: []string{"https://example.com/foo"},
				},
			},
			supportedResponseTypes: []string{"code"},
			queryParams: map[string]string{
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/foo",
				"response_type": "code",
				"scope":         "openid email profile",
			},
			wantErr: true,
		},
		{
			name: "invalid redirect uri",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code"},
			queryParams: map[string]string{
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/foo",
				"response_type": "code",
				"scope":         "openid email profile",
			},
			wantErr: true,
		},
		{
			name: "implicit flow",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code", "id_token", "token"},
			queryParams: map[string]string{
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "code id_token",
				"scope":         "openid email profile",
			},
		},
		{
			name: "unsupported response type",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code"},
			queryParams: map[string]string{
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "code id_token",
				"scope":         "openid email profile",
			},
			wantErr: true,
		},
		{
			name: "only token response type",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code", "id_token", "token"},
			queryParams: map[string]string{
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "token",
				"scope":         "openid email profile",
			},
			wantErr: true,
		},
		{
			name: "choose connector_id",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code", "id_token", "token"},
			queryParams: map[string]string{
				"connector_id":  "mock",
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "code id_token",
				"scope":         "openid email profile",
			},
		},
		{
			name: "choose second connector_id",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code", "id_token", "token"},
			queryParams: map[string]string{
				"connector_id":  "mock2",
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "code id_token",
				"scope":         "openid email profile",
			},
		},
		{
			name: "choose invalid connector_id",
			clients: []storage.Client{
				{
					ID:           "bar",
					RedirectURIs: []string{"https://example.com/bar"},
				},
			},
			supportedResponseTypes: []string{"code", "id_token", "token"},
			queryParams: map[string]string{
				"connector_id":  "bogus",
				"client_id":     "bar",
				"redirect_uri":  "https://example.com/bar",
				"response_type": "code id_token",
				"scope":         "openid email profile",
			},
			wantErr: true,
		},
	}

	for _, tc := range tests {
		func() {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			httpServer, server := newTestServerMultipleConnectors(ctx, t, func(c *Config) {
				c.SupportedResponseTypes = tc.supportedResponseTypes
				c.Storage = storage.WithStaticClients(c.Storage, tc.clients)
			})
			defer httpServer.Close()

			params := url.Values{}
			for k, v := range tc.queryParams {
				params.Set(k, v)
			}
			var req *http.Request
			if tc.usePOST {
				body := strings.NewReader(params.Encode())
				req = httptest.NewRequest("POST", httpServer.URL+"/auth", body)
				req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			} else {
				req = httptest.NewRequest("GET", httpServer.URL+"/auth?"+params.Encode(), nil)
			}
			_, err := server.parseAuthorizationRequest(req)
			if err != nil && !tc.wantErr {
				t.Errorf("%s: %v", tc.name, err)
			}
			if err == nil && tc.wantErr {
				t.Errorf("%s: expected error", tc.name)
			}
		}()
	}
}

const (
	// at_hash value and access_token returned by Google.
	googleAccessTokenHash = "piwt8oCH-K2D9pXlaS1Y-w"
	googleAccessToken     = "ya29.CjHSA1l5WUn8xZ6HanHFzzdHdbXm-14rxnC7JHch9eFIsZkQEGoWzaYG4o7k5f6BnPLj"
	googleSigningAlg      = jose.RS256
)

func TestAccessTokenHash(t *testing.T) {
	atHash, err := accessTokenHash(googleSigningAlg, googleAccessToken)
	if err != nil {
		t.Fatal(err)
	}
	if atHash != googleAccessTokenHash {
		t.Errorf("expected %q got %q", googleAccessTokenHash, atHash)
	}
}

func TestValidRedirectURI(t *testing.T) {
	tests := []struct {
		client      storage.Client
		redirectURI string
		wantValid   bool
	}{
		{
			client: storage.Client{
				RedirectURIs: []string{"http://foo.com/bar"},
			},
			redirectURI: "http://foo.com/bar",
			wantValid:   true,
		},
		{
			client: storage.Client{
				RedirectURIs: []string{"http://foo.com/bar"},
			},
			redirectURI: "http://foo.com/bar/baz",
		},
		{
			client: storage.Client{
				Public: true,
			},
			redirectURI: "urn:ietf:wg:oauth:2.0:oob",
			wantValid:   true,
		},
		{
			client: storage.Client{
				Public: true,
			},
			redirectURI: "http://localhost:8080/",
			wantValid:   true,
		},
		{
			client: storage.Client{
				Public: true,
			},
			redirectURI: "http://localhost:991/bar",
			wantValid:   true,
		},
		{
			client: storage.Client{
				Public: true,
			},
			redirectURI: "http://localhost",
			wantValid:   true,
		},
		{
			client: storage.Client{
				Public: true,
			},
			redirectURI: "http://localhost.localhost:8080/",
			wantValid:   false,
		},
	}
	for _, test := range tests {
		got := validateRedirectURI(test.client, test.redirectURI)
		if got != test.wantValid {
			t.Errorf("client=%#v, redirectURI=%q, wanted valid=%t, got=%t",
				test.client, test.redirectURI, test.wantValid, got)
		}
	}
}

func TestStorageKeySet(t *testing.T) {
	s := memory.New(logger)
	if err := s.UpdateKeys(func(keys storage.Keys) (storage.Keys, error) {
		keys.SigningKey = &jose.JSONWebKey{
			Key:       testKey,
			KeyID:     "testkey",
			Algorithm: "RS256",
			Use:       "sig",
		}
		keys.SigningKeyPub = &jose.JSONWebKey{
			Key:       testKey.Public(),
			KeyID:     "testkey",
			Algorithm: "RS256",
			Use:       "sig",
		}
		return keys, nil
	}); err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		name           string
		tokenGenerator func() (jwt string, err error)
		wantErr        bool
	}{
		{
			name: "valid token",
			tokenGenerator: func() (string, error) {
				signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: testKey}, nil)
				if err != nil {
					return "", err
				}

				jws, err := signer.Sign([]byte("payload"))
				if err != nil {
					return "", err
				}

				return jws.CompactSerialize()
			},
			wantErr: false,
		},
		{
			name: "token signed by different key",
			tokenGenerator: func() (string, error) {
				key, err := rsa.GenerateKey(rand.Reader, 2048)
				if err != nil {
					return "", err
				}

				signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key}, nil)
				if err != nil {
					return "", err
				}

				jws, err := signer.Sign([]byte("payload"))
				if err != nil {
					return "", err
				}

				return jws.CompactSerialize()
			},
			wantErr: true,
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			jwt, err := tc.tokenGenerator()
			if err != nil {
				t.Fatal(err)
			}

			keySet := &storageKeySet{s}

			_, err = keySet.VerifySignature(context.Background(), jwt)
			if (err != nil && !tc.wantErr) || (err == nil && tc.wantErr) {
				t.Fatalf("wantErr = %v, but got err = %v", tc.wantErr, err)
			}
		})
	}
}


text:
__docformat__='restructuredtext'
from popserver.tests import *

from popserver.model import User
from formencode.api import set_stdtranslation
import paste.fixture

class TestUsersController(TestController):

    def setUp(self):
        super(self.__class__, self).setUp()
        self.mail = 'mcortesi@gmail.com'
        self.values = dict(
            displayname='Mariano Cortesi',
            email=self.mail,
            username='mariano',
            password='pwd',
            password_confirm='pwd')

        # force language (en) for tests where validation message
        # might be translated with gettext; see: http://formencode.org/
        # Validator.html#localization-of-error-messages-i18n
        set_stdtranslation(domain="FormEncode", languages=["en"])

        # check no user in db
        assert User.query.filter_by(email=self.mail).count() == 0
        self.response = self.app.get(url_for(controller='website/users'))

    def tearDown(self):
        self.app.get(url_for(controller='auth',action='signout'))
        super(self.__class__, self).tearDown()

    def test_register(self):
        self._registerUser()
        assert User.query.filter_by(email=self.mail).count() == 1

    def _registerUser(self):
        self.fillForm(self.response.forms['profile'], self.values)
        return self.response.forms['profile'].submit()

    def test_registerUppercaseUsername(self):
        self.values['username'] = 'MariAno'
        self._registerUser()
        assert User.query.filter_by(email=self.mail).count() == 1

    def test_registerSameUsernameWithDifferentCase(self):
        self._registerUser()
        self.values['username'] = 'MarIano'
        self.values['email'] = 'another@email.com'

        self.app = paste.fixture.TestApp(self.wsgiapp)
        self.app.extra_environ['REMOTE_ADDR'] = '127.0.0.1' # Hack needed for testing things like AuthKit

        self.response = self.app.get(url_for(controller='website/users'))
        self.response = self._registerUser()
        assert User.query.filter_by(username='mariano').count() == 1
        assert 'username already exists' in self.response

    def test_register_InvalidEmail(self):
        self.mail = 'invalidEmail'
        self.values['email'] = self.mail

        self.fillForm(self.response.forms['profile'], self.values)
        r2 = self.response.forms['profile'].submit()
        assert User.query.filter_by(email=self.mail).count() == 0
        assert 'An email address must contain a single @' in r2

    def test_register_NoUsername(self):
        del self.values['username']
        self.fillForm(self.response.forms['profile'], self.values)
        r2 = self.response.forms['profile'].submit()

        assert 'class="error"' in r2
        assert User.query.filter_by(email=self.mail).count() == 0

    def test_register_InvalidUsername(self):
        self.values['username']= 'Mariano?'
        self.fillForm(self.response.forms['profile'], self.values)
        r2 = self.response.forms['profile'].submit()

        assert User.query.filter_by(email=self.mail).count() == 0
        assert 'class="error"' in r2

    def fillForm(self,form,values):
        for name,value in values.items():
            form[name]=value


text:
import { app, BrowserWindow } from 'electron';
import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';
import { enableLiveReload } from 'electron-compile';

let mainWindow: Electron.BrowserWindow | null = null;

const isDevMode = process.execPath.match(/[\\/]electron/);

if (isDevMode) {
	enableLiveReload({strategy: 'react-hmr'});
}

const createWindow = async () => {
	mainWindow = new BrowserWindow({
		width: 1280,
		height: 720,
		title: "Freckles Editor"
	});

	mainWindow.loadURL(`file://${__dirname}/ui/index.html`);

	if (isDevMode) {
		await installExtension(REACT_DEVELOPER_TOOLS);
		mainWindow.webContents.openDevTools();
	}

	mainWindow.on('closed', () => {
		mainWindow = null;
	});
};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate', () => {
	if (mainWindow === null) {
		createWindow();
	}
});


text:
<!DOCTYPE HTML>

Test for crbug.com/370136: event targets should not be nodes in the shadow tree.

FAIL
<template id="template">
    <svg width="100" height="100">
        <rect id="FAIL" width="100" height="100" fill="green" />
    </svg>
</template>


text:
@class TLViewController;

@interface TLAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) TLViewController *viewController;

@end


text:
'use strict';

angular.module('adminApp')
.controller('BooksBookidCtrl', function ($scope, Users, Rents, $routeParams, $location, book, BookCopy) {
  $scope.book = book;

  $scope.openRent = function (bookCopy) {
    $scope.rentBook = true;
    $scope.rentUsers = $scope.rentUsers || Users.query();
    $scope.rentCopy = {
      'bookId': $scope.book.bookId,
      'bookCopyId': bookCopy.bookCopyId,
      'limit': 1000
    };

    $scope.reservations = $scope.reservations || Rents.query({status: 'reserved', book: $scope.book.bookId, 'limit': 1000});
  };

  $scope.clearRent = function(rent) {
    rent.rentId = undefined;
  };

  $scope.closeRent = function () {
    $scope.rentBook = false;
  };

  $scope.save = function () {
    Rents.create($scope.rentCopy, function(rent){
      console.log(rent);
      $scope.rentBook = false;
      $location.path('/rents/' + rent.rentId);
    });
  };

  $scope.returnBook = function(bookCopy) {
    var rentId = bookCopy.rents[bookCopy.rents.length - 1];
    Rents.returnBook({'rentId': rentId}, function(){
      $location.path('/rents');
    });
  };

  $scope.openEdit = function (book) {
    $scope.editBook = true;
    $scope.edit = angular.copy(book);
    delete $scope.edit.copies;
    console.log($scope.edit);
  };

  $scope.closeEdit = function () {
    $scope.editBook = false;
  };

  $scope.saveEdit = function(edit) {
    console.log(edit);
    edit.$update(function(book){
      $scope.book = book;
      $scope.closeEdit();
    });
  };

  $scope.minDate = new Date().setDate(new Date().getDate() + 1);

  $scope.updateCopy = function(copy){

    BookCopy.update(copy, function(){
      copy.changed = false;
    });
  };

});


text:
package batfish.representation.cisco;

import java.io.Serializable;

public class Edge implements Serializable {

   private static final long serialVersionUID = 1L;

   private String _host1;
   private String _host2;
   private String _int1;
   private String _int2;

   public Edge(String host1, String int1, String host2, String int2) {
      _host1 = host1;
      _host2 = host2;
      _int1 = int1;
      _int2 = int2;
   }

   public String getHost1() {
      return _host1;
   }

   public String getHost2() {
      return _host2;
   }

   public String getInt1() {
      return _int1;
   }

   public String getInt2() {
      return _int2;
   }

}


text:
#region Imported Types

using DeviceSQL.Device.MODBUS.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;

#endregion

namespace DeviceSQL.Device.MODBUS.Message
{
    internal class ReadDiscreteInputRegistersRequest : MODBUSMessage, IMODBUSRequestMessage
    {

        #region Properties

        public Device.DataType DataType
        {
            get
            {
                return Device.DataType.Boolean;
            }
        }

        public List<DiscreteInputRegister> DiscreteInputRegisters
        {
            get;
            set;
        }

        public override int MinimumFrameSize
        {
            get
            {
                return 7;
            }
        }

        public override byte[] Data
        {
            get
            {
                var data = new List<byte>();

                data.AddRange(DiscreteInputRegisters.First().Address.ToArray());
                data.AddRange(BitConverter.GetBytes(IPAddress.NetworkToHostOrder((short)DiscreteInputRegisters.Count)));

                return data.ToArray();
            }
        }

        #endregion

        #region Constructor(s)

        public ReadDiscreteInputRegistersRequest()
        {
        }

        public ReadDiscreteInputRegistersRequest(ushort unitId, List<DiscreteInputRegister> discreteInputRegisters, bool isExtendedUnitId)
            : base(unitId, Device.ReadDiscreteInputs)
        {
            this.DiscreteInputRegisters = discreteInputRegisters;
            this.IsExtendedUnitId = isExtendedUnitId;
        }

        #endregion

        #region Helper Methods

        public void ValidateResponse(IMODBUSResponseMessage response)
        {
            var readDiscreteInputRegistersResponse = response as ReadDiscreteInputRegistersResponse;
            Debug.Assert(readDiscreteInputRegistersResponse != null, "Argument response should be of type ReadDiscreteInputRegistersResponse.");

            var discreteInputCount = this.DiscreteInputRegisters.Count();

            var expectedByteCount = (discreteInputCount / 8) + (discreteInputCount % 8) > 0 ? 1 : 0;

            if (expectedByteCount != readDiscreteInputRegistersResponse.Data[0])
            {
                throw new FormatException("Number of discrete input registers recieved does not equal number of discrete input registers requested.");
            }
        }

        #endregion

    }
}


text:
class Search
  attr_reader :keyword

  def initialize(keyword)
    @keyword = keyword
  end

  def exact
    Word.find_by(name: keyword)
  end

  def fuzzy
    Word.where("name LIKE ?", "%#{keyword}%")
  end
end


text:
package de.craftolution.craftoplugin.module.village;

import de.craftolution.craftoplugin.core.annotations.Dependencies;
import de.craftolution.craftoplugin.service.command.CommandService;
import de.craftolution.craftoplugin.service.command.annotation.CommandHandler;
import de.craftolution.craftoplugin.service.command.annotation.Permission;
import de.craftolution.craftoplugin.service.command.args.Args;
import de.craftolution.craftoplugin.service.module.Component;
import de.craftolution.craftoplugin.service.module.annotation.Parent;
import de.craftolution.craftoplugin.service.task.TaskService;
import de.craftolution.craftoplugin.service.task.annotations.TaskHandler;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;

@Dependencies({CommandService.class, TaskService.class})
public class MyComponent extends Component {

	@Parent
	private VillageModule module;

	@Override
	protected void onEnable() throws Exception {
		info("MyComponent enabled");
	}

	@CommandHandler("mycmd")
	@Permission("craftoplugin.mymodule.mycmd")
	public void onCommand(CommandSender cs, Args args) {
		// ...
	}

	@TaskHandler(name = "MyTask", delay = 20 * 60)
	public void onTask() {
		// ...
	}

	@EventHandler
	public void onPlayerJoin(PlayerJoinEvent event) {
		try {
			// ...
		}
		catch (Exception e) { // Always surround event handlers with try/catch
			report(e, "Failed to handle PlayerJoinEvent");
		}
	}

}


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

{% block page_title %}Sync your accounts{% endblock %}

{% block show_content %}

                                         Sign in with Foursquare

    By clicking on the button above you confirm you have read and accepted the Privacy Terms

{% endblock %}

{% block extra_script %}

{% endblock %}


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

<title>Group</title>
<meta name="date" content="2015-12-30">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

io.gearpump.streaming.state.api

Interface Group<T>

All Superinterfaces:

Monoid<T>, java.io.Serializable

public interface Group<T>
extends Monoid<T>

Method Summary

Methods

Modifier and Type
Method and Description

T
minus(T l,
     T r)

Methods inherited from interface io.gearpump.streaming.state.api.Monoid

plus, zero

Method Detail

minus

T minus(T l,
      T r)

Overview

Package

Class

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
package security;

import java.security.MessageDigest;

public class Authentificator {

	public static String hashPassword(String password){
		String hashedString="";
		try {
			MessageDigest md;
			md = MessageDigest.getInstance("MD5");
			byte[] hashedBytes=md.digest(password.getBytes("UTF-8"));
			for (byte b : hashedBytes) {
				hashedString+=String.format("%02x", b);
			}
		}
		catch(Exception e){

		}
		return hashedString;
	}
}


text:
layout:     post
title:      "Privacy-Preserving Machine Learning"
subtitle:   "And How It Mitigates Bottlenecks"
date:       2018-08-29 12:00:00
author:     "Morten Dahl"
header-img: "assets/bottlenecks/impact.jpg"
summary:    "The need for privacy-enhancing techniques in machine learning can be understood in the light of bottlenecks that may otherwise exist. We here review some of those bottlenecks together with concrete technologies available to mitigate and create new opportunities.
"
---

TL;DR: TODO.

Entering the field of privacy-preserving machine learning can be confusing, not least because of the many different techniques that may be new to most. In this post I give a quick overview of some of these, and illustrate which ones compliment each other and which ones solve the same problem but have different characteristics.

The techniques I want to talk about are *secure computation*, *differential privacy*, and *federated learning*. There are other [privacy-enhancing technologies](https://en.wikipedia.org/wiki/Privacy-enhancing_technologies), such as encrypted search, private information retrieval, and private set intersection, that may also in one form or another be used as part of privacy-preserving machine learning; however, these are more specialised tools where the utility depends more strongly on the concrete use cases.

Much of this post is based on [recent talks](/talks/) and some of the work have been done as part of my work as a research scientist at [Dropout Labs](https://dropoutlabs.com/).

- SGX
- HE
- SS
- GC
- PATE
- FL
- DP

# The Machine Learning Process

It is useful to use the typical machine learning process to frame

# Bottlenecks

## Access to Training Data

liability

price

(consumers)

## Holding Training Data

Data as a toxic assest

## Incentivizing Use


text:
import { color, typography } from '../base';
import { ThemeVars } from '../types';

const theme: ThemeVars = {
  base: 'dark',

  // Storybook-specific color palette
  colorPrimary: '#FF4785', // coral
  colorSecondary: '#1EA7FD', // ocean

  // UI
  appBg: '#2f2f2f',
  appContentBg: color.darkest,
  appBorderColor: 'rgba(255,255,255,.1)',
  appBorderRadius: 4,

  // Fonts
  fontBase: typography.fonts.base,
  fontCode: typography.fonts.mono,

  // Text colors
  textColor: color.lightest,
  textInverseColor: color.darkest,
  textMutedColor: color.mediumdark,

  // Toolbar default and active colors
  barTextColor: '#999999',
  barSelectedColor: color.secondary,
  barBg: color.darkest,

  // Form colors
  inputBg: '#3f3f3f',
  inputBorder: 'rgba(0,0,0,.3)',
  inputTextColor: color.lightest,
  inputBorderRadius: 4,
};

export default theme;


text:
% WAVELET_FACTORY_3D_PYRAMID Build roto-translation wavelet operators
%
% Usage
%   [Wop, filters, filters_rot] = WAVELET_FACTORY_3D_PYRAMID(filt_opt, filt_rot_opt, scat_opt)
%
% Input
%    filt_opt (struct): the filter options, same as for MORLET_FILTER_BANK_2D_PYRAMID
%    filt_rot_opt (struct): the filter options for the
%		filters along angular parameter, same as for MORLET_FILTER_BANK_1D
%	 scat_opt (struct): the scattering and wavelet options, same as
%		WAVELET_LAYER_3D_PYRAMID
%
% Output
%    Wop: A cell array of wavelet transforms needed for the scattering trans-
%       form.
%    filters: A cell array of the filters used in defining the wavelets.
%
% Description
%   This function builds the wavelet operators used to compute the
%   roto-translation scattering. The first operator is a 2d wavelet
%   transform obtained with WAVELET_LAYER_2D_PYRAMID. The second operator and third
%   operators are roto-translation wavelet transform obtained with
%   WAVELET_LAYER_3D_PYRAMID.
%   Compared to WAVELET_FACTORY_3D this function is faster because it uses
%   a pyramid algorithm and spatial convolution whereas WAVELET_FACTORY_3D
%   uses FFT-based convolution
%
% See also
%   SCAT, WAVELET_2D_PYRAMID, WAVELET_LAYER_2D_PYRAMID, WAVELET_3D_PYRAMID,
%   WAVELET_3D_LAYER_PYRAMID
%

function [Wop, filters, filters_rot] = wavelet_factory_3d_pyramid(filt_opt, filt_rot_opt, scat_opt)
    if (nargin < 3)
        scat_opt = struct();
    end
    if (nargin < 2)
        filt_rot_opt = struct();
    end
    if (nargin < 1)
        filt_opt = struct();
    end
    scat_opt = fill_struct(scat_opt, 'M', 2);
    wavelet_opt = rmfield(scat_opt, 'M');

    precision = getoptions(scat_opt, 'precision', 'single');
    % filters :
    filters = morlet_filter_bank_2d_pyramid(filt_opt);

    % filters along angular variable
    sz = filters.meta.L * 2; % L orientations between 0 and pi
    % periodic convolutions along angles
    filt_rot_opt.boundary = 'per';
    filt_rot_opt.filter_format = 'fourier_multires';
    filt_rot_opt.J = 3;
    filt_rot_opt.P = 0;
    filt_rot_opt.Q = 1;
    filt_rot_opt.precision = precision;
    filters_rot = morlet_filter_bank_1d(sz, filt_rot_opt);

    % first layer : usual 2d wavelet transform
    Wop{1} = @(x)(wavelet_layer_2d_pyramid(x, filters, wavelet_opt));
    Wop{2} = @(x)(wavelet_layer_3d_pyramid(x, filters, filters_rot, wavelet_opt));
    Wop{3} = @(x)(wavelet_layer_3d_pyramid(x, filters, filters_rot, wavelet_opt));

end


text:
#include "rsync.h"

int remote_protocol = 0;
int file_extra_cnt = 0; /* count of file-list extras that everyone gets */
int inc_recurse = 0;
int use_safe_inc_flist = 0;

extern int verbose;
extern int am_server;
extern int am_sender;
extern int local_server;
extern int inplace;
extern int recurse;
extern int use_qsort;
extern int allow_inc_recurse;
extern int append_mode;
extern int fuzzy_basis;
extern int read_batch;
extern int delay_updates;
extern int checksum_seed;
extern int basis_dir_cnt;
extern int prune_empty_dirs;
extern int protocol_version;
extern int protect_args;
extern int preserve_uid;
extern int preserve_gid;
extern int preserve_acls;
extern int preserve_xattrs;
extern int need_messages_from_generator;
extern int delete_mode, delete_before, delete_during, delete_after;
extern char *shell_cmd;
extern char *partial_dir;
extern char *dest_option;
extern char *files_from;
extern char *filesfrom_host;
extern struct filter_list_struct filter_list;
extern int need_unsorted_flist;
#ifdef ICONV_OPTION
extern iconv_t ic_send, ic_recv;
extern char *iconv_opt;
#endif

/* These index values are for the file-list's extra-attribute array. */
int uid_ndx, gid_ndx, acls_ndx, xattrs_ndx, unsort_ndx;

int receiver_symlink_times = 0; /* receiver can set the time on a symlink */
int sender_symlink_iconv = 0;	/* sender should convert symlink content */

#ifdef ICONV_OPTION
int filesfrom_convert = 0;
#endif

#define CF_INC_RECURSE	 (1<<0)
#define CF_SYMLINK_TIMES (1<<1)
#define CF_SYMLINK_ICONV (1<<2)
#define CF_SAFE_FLIST	 (1<<3)

static const char *client_info;

/* The server makes sure that if either side only supports a pre-release
 * version of a protocol, that both sides must speak a compatible version
 * of that protocol for it to be advertised as available. */
static void check_sub_protocol(void)
{
	char *dot;
	int their_protocol, their_sub;
#if SUBPROTOCOL_VERSION != 0
	int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
#else
	int our_sub = 0;
#endif

	/* client_info starts with VER.SUB string if client is a pre-release. */
	if (!(their_protocol = atoi(client_info))
	 || !(dot = strchr(client_info, '.'))
	 || !(their_sub = atoi(dot+1))) {
#if SUBPROTOCOL_VERSION != 0
		if (our_sub)
			protocol_version--;
#endif
		return;
	}

	if (their_protocol < protocol_version) {
		if (their_sub)
			protocol_version = their_protocol - 1;
		return;
	}

	if (their_protocol > protocol_version)
		their_sub = 0; /* 0 == final version of older protocol */
	if (their_sub != our_sub)
		protocol_version--;
}

void set_allow_inc_recurse(void)
{
	client_info = shell_cmd ? shell_cmd : "";

	if (!recurse || use_qsort)
		allow_inc_recurse = 0;
	else if (!am_sender
	 && (delete_before || delete_after
	  || delay_updates || prune_empty_dirs))
		allow_inc_recurse = 0;
	else if (am_server && !local_server
	 && (strchr(client_info, 'i') == NULL))
		allow_inc_recurse = 0;
}

void setup_protocol(int f_out,int f_in)
{
	if (am_sender)
		file_extra_cnt += PTR_EXTRA_CNT;
	else
		file_extra_cnt++;
	if (preserve_uid)
		uid_ndx = ++file_extra_cnt;
	if (preserve_gid)
		gid_ndx = ++file_extra_cnt;
	if (preserve_acls && !am_sender)
		acls_ndx = ++file_extra_cnt;
	if (preserve_xattrs)
		xattrs_ndx = ++file_extra_cnt;

	if (am_server)
		set_allow_inc_recurse();

	if (remote_protocol == 0) {
		if (am_server && !local_server)
			check_sub_protocol();
		if (!read_batch)
			write_int(f_out, protocol_version);
		remote_protocol = read_int(f_in);
		if (protocol_version > remote_protocol)
			protocol_version = remote_protocol;
	}
	if (read_batch && remote_protocol > protocol_version) {
		rprintf(FERROR, "The protocol version in the batch file is too new (%d > %d).\n",
			remote_protocol, protocol_version);
		exit_cleanup(RERR_PROTOCOL);
	}

	if (verbose > 3) {
		rprintf(FINFO, "(%s) Protocol versions: remote=%d, negotiated=%d\n",
			am_server? "Server" : "Client", remote_protocol, protocol_version);
	}
	if (remote_protocol < MIN_PROTOCOL_VERSION
	 || remote_protocol > MAX_PROTOCOL_VERSION) {
		rprintf(FERROR,"protocol version mismatch -- is your shell clean?\n");
		rprintf(FERROR,"(see the rsync man page for an explanation)\n");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (remote_protocol < OLD_PROTOCOL_VERSION) {
		rprintf(FINFO,"%s is very old version of rsync, upgrade recommended.\n",
			am_server? "Client" : "Server");
	}
	if (protocol_version < MIN_PROTOCOL_VERSION) {
		rprintf(FERROR, "--protocol must be at least %d on the %s.\n",
			MIN_PROTOCOL_VERSION, am_server? "Server" : "Client");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (protocol_version > PROTOCOL_VERSION) {
		rprintf(FERROR, "--protocol must be no more than %d on the %s.\n",
			PROTOCOL_VERSION, am_server? "Server" : "Client");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (read_batch)
		check_batch_flags();

	if (protocol_version < 30) {
		if (append_mode == 1)
			append_mode = 2;
		if (preserve_acls && !local_server) {
			rprintf(FERROR,
			    "--acls requires protocol 30 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
		if (preserve_xattrs && !local_server) {
			rprintf(FERROR,
			    "--xattrs requires protocol 30 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
	}

	if (delete_mode && !(delete_before+delete_during+delete_after)) {
		if (protocol_version < 30)
			delete_before = 1;
		else
			delete_during = 1;
	}

	if (protocol_version < 29) {
		if (fuzzy_basis) {
			rprintf(FERROR,
			    "--fuzzy requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (basis_dir_cnt && inplace) {
			rprintf(FERROR,
			    "%s with --inplace requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    dest_option, protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (basis_dir_cnt > 1) {
			rprintf(FERROR,
			    "Using more than one %s option requires protocol"
			    " 29 or higher (negotiated %d).\n",
			    dest_option, protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (prune_empty_dirs) {
			rprintf(FERROR,
			    "--prune-empty-dirs requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
	} else if (protocol_version >= 30) {
		int compat_flags;
		if (am_server) {
			compat_flags = allow_inc_recurse ? CF_INC_RECURSE : 0;
#if defined HAVE_LUTIMES && defined HAVE_UTIMES
			compat_flags |= CF_SYMLINK_TIMES;
#endif
#ifdef ICONV_OPTION
			compat_flags |= CF_SYMLINK_ICONV;
#endif
			if (local_server || strchr(client_info, 'f') != NULL)
				compat_flags |= CF_SAFE_FLIST;
			write_byte(f_out, compat_flags);
		} else
			compat_flags = read_byte(f_in);
		/* The inc_recurse var MUST be set to 0 or 1. */
		inc_recurse = compat_flags & CF_INC_RECURSE ? 1 : 0;
		if (am_sender) {
			receiver_symlink_times = am_server
			    ? strchr(client_info, 'L') != NULL
			    : !!(compat_flags & CF_SYMLINK_TIMES);
		}
#if defined HAVE_LUTIMES && defined HAVE_UTIMES
		else
			receiver_symlink_times = 1;
#endif
#ifdef ICONV_OPTION
		sender_symlink_iconv = iconv_opt && (am_server
		    ? local_server || strchr(client_info, 's') != NULL
		    : !!(compat_flags & CF_SYMLINK_ICONV));
#endif
		if (inc_recurse && !allow_inc_recurse) {
			/* This should only be able to happen in a batch. */
			fprintf(stderr,
			    "Incompatible options specified for inc-recursive %s.\n",
			    read_batch ? "batch file" : "connection");
			exit_cleanup(RERR_SYNTAX);
		}
		use_safe_inc_flist = !!(compat_flags & CF_SAFE_FLIST);
		need_messages_from_generator = 1;
#if defined HAVE_LUTIMES && defined HAVE_UTIMES
	} else if (!am_sender) {
		receiver_symlink_times = 1;
#endif
	}

	if (need_unsorted_flist && (!am_sender || inc_recurse))
		unsort_ndx = ++file_extra_cnt;

	if (partial_dir && *partial_dir != '/' && (!am_server || local_server)) {
		int flags = MATCHFLG_NO_PREFIXES | MATCHFLG_DIRECTORY;
		if (!am_sender || protocol_version >= 30)
			flags |= MATCHFLG_PERISHABLE;
		parse_rule(&filter_list, partial_dir, flags, 0);
	}

#ifdef ICONV_OPTION
	if (protect_args && files_from) {
		if (am_sender)
			filesfrom_convert = filesfrom_host && ic_send != (iconv_t)-1;
		else
			filesfrom_convert = !filesfrom_host && ic_recv != (iconv_t)-1;
	}
#endif

	if (am_server) {
		if (!checksum_seed)
			checksum_seed = time(NULL);
		write_int(f_out, checksum_seed);
	} else {
		checksum_seed = read_int(f_in);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;

namespace LibGit2Sharp
{
    /// <summary>
    /// Provides helper overloads to a <see cref="ReferenceCollection"/>.
    /// </summary>
    public static class ReferenceCollectionExtensions
    {
        private enum RefState
        {
            Exists,
            DoesNotExistButLooksValid,
            DoesNotLookValid,
        }

        private static RefState TryResolveReference(out Reference reference, ReferenceCollection refsColl, string canonicalName)
        {
            if (!Reference.IsValidName(canonicalName))
            {
                reference = null;
                return RefState.DoesNotLookValid;
            }

            reference = refsColl[canonicalName];

            return reference != null ? RefState.Exists : RefState.DoesNotExistButLooksValid;
        }

        /// <summary>
        /// Creates a direct or symbolic reference with the specified name and target
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="name">The name of the reference to create.</param>
        /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param>
        /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> when adding the <see cref="Reference"/></param>
        /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, string logMessage, bool allowOverwrite = false)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish");

            Reference reference;
            RefState refState = TryResolveReference(out reference, refsColl, canonicalRefNameOrObjectish);

            var gitObject = refsColl.repo.Lookup(canonicalRefNameOrObjectish, GitObjectType.Any, LookUpOptions.None);

            if (refState == RefState.Exists)
            {
                return refsColl.Add(name, reference, logMessage, allowOverwrite);
            }

            if (refState == RefState.DoesNotExistButLooksValid && gitObject == null)
            {
                using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_create(refsColl.repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite,
                    logMessage))
                {
                    return Reference.BuildFromPtr<Reference>(handle, refsColl.repo);
                }
            }

            Ensure.GitObjectIsNotNull(gitObject, canonicalRefNameOrObjectish);

            if (logMessage == null)
            {
                logMessage = string.Format(CultureInfo.InvariantCulture, "{0}: Created from {1}",
                    name.LooksLikeLocalBranch() ? "branch" : "reference", canonicalRefNameOrObjectish);
            }

            refsColl.EnsureHasLog(name);
            return refsColl.Add(name, gitObject.Id, logMessage, allowOverwrite);
        }

        /// <summary>
        /// Creates a direct or symbolic reference with the specified name and target
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="name">The name of the reference to create.</param>
        /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param>
        /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false)
        {
            return Add(refsColl, name, canonicalRefNameOrObjectish, null, allowOverwrite);
        }

        /// <summary>
        /// Updates the target of a direct reference.
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="directRef">The direct reference which target should be updated.</param>
        /// <param name="objectish">The revparse spec of the target.</param>
        /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish, string logMessage)
        {
            Ensure.ArgumentNotNull(directRef, "directRef");
            Ensure.ArgumentNotNull(objectish, "objectish");

            GitObject target = refsColl.repo.Lookup(objectish);

            Ensure.GitObjectIsNotNull(target, objectish);

            return refsColl.UpdateTarget(directRef, target.Id, logMessage);
        }

        /// <summary>
        /// Updates the target of a direct reference
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="directRef">The direct reference which target should be updated.</param>
        /// <param name="objectish">The revparse spec of the target.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish)
        {
            return UpdateTarget(refsColl, directRef, objectish, null);
        }

        /// <summary>
        /// Rename an existing reference with a new name
        /// </summary>
        /// <param name="currentName">The canonical name of the reference to rename.</param>
        /// <param name="newName">The new canonical name.</param>
        /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param>
        /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference Rename(this ReferenceCollection refsColl, string currentName, string newName,
            string logMessage = null, bool allowOverwrite = false)
        {
            Ensure.ArgumentNotNullOrEmptyString(currentName, "currentName");

            Reference reference = refsColl[currentName];

            if (reference == null)
            {
                throw new LibGit2SharpException(
                    string.Format(CultureInfo.InvariantCulture,
                        "Reference '{0}' doesn't exist. One cannot move a non existing reference.", currentName));
            }

            return refsColl.Rename(reference, newName, logMessage, allowOverwrite);
        }

        /// <summary>
        /// Updates the target of a reference
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="name">The canonical name of the reference.</param>
        /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param>
        /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> of the <paramref name="name"/> reference.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, string logMessage)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish");

            if (name == "HEAD")
            {
                return refsColl.UpdateHeadTarget(canonicalRefNameOrObjectish, logMessage);
            }

            Reference reference = refsColl[name];

            var directReference = reference as DirectReference;
            if (directReference != null)
            {
                return refsColl.UpdateTarget(directReference, canonicalRefNameOrObjectish, logMessage);
            }

            var symbolicReference = reference as SymbolicReference;
            if (symbolicReference != null)
            {
                Reference targetRef;

                RefState refState = TryResolveReference(out targetRef, refsColl, canonicalRefNameOrObjectish);

                if (refState == RefState.DoesNotLookValid)
                {
                    throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The reference specified by {0} is a Symbolic reference, you must provide a reference canonical name as the target.", name), "canonicalRefNameOrObjectish");
                }

                return refsColl.UpdateTarget(symbolicReference, targetRef, logMessage);
            }

            throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, reference.GetType()));
        }

        /// <summary>
        /// Updates the target of a reference
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="name">The canonical name of the reference.</param>
        /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param>
        /// <returns>A new <see cref="Reference"/>.</returns>
        public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish)
        {
            return UpdateTarget(refsColl, name, canonicalRefNameOrObjectish, null);
        }

        /// <summary>
        /// Delete a reference with the specified name
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="name">The canonical name of the reference to delete.</param>
        public static void Remove(this ReferenceCollection refsColl, string name)
        {
            Ensure.ArgumentNotNullOrEmptyString(name, "name");

            Reference reference = refsColl[name];

            if (reference == null)
            {
                return;
            }

            refsColl.Remove(reference);
        }

        /// <summary>
        /// Find the <see cref="Reference"/>s among <paramref name="refSubset"/>
        /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>.
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="refSubset">The set of <see cref="Reference"/>s to examine.</param>
        /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param>
        /// <returns>A subset of <paramref name="refSubset"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns>
        public static IEnumerable<Reference> ReachableFrom(
            this ReferenceCollection refsColl,
            IEnumerable<Reference> refSubset,
            IEnumerable<Commit> targets)
        {
            Ensure.ArgumentNotNull(refSubset, "refSubset");
            Ensure.ArgumentNotNull(targets, "targets");

            var refs = new List<Reference>(refSubset);
            if (refs.Count == 0)
            {
                return Enumerable.Empty<Reference>();
            }

            List<ObjectId> targetsSet = targets.Select(c => c.Id).Distinct().ToList();
            if (targetsSet.Count == 0)
            {
                return Enumerable.Empty<Reference>();
            }

            var result = new List<Reference>();

            foreach (var reference in refs)
            {
                var peeledTargetCommit = reference
                                            .ResolveToDirectReference()
                                            .Target.DereferenceToCommit(false);

                if (peeledTargetCommit == null)
                {
                    continue;
                }

                var commitId = peeledTargetCommit.Id;

                foreach (var potentialAncestorId in targetsSet)
                {
                    if (potentialAncestorId == commitId)
                    {
                        result.Add(reference);
                        break;
                    }

                    if (Proxy.git_graph_descendant_of(refsColl.repo.Handle, commitId, potentialAncestorId))
                    {
                        result.Add(reference);
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Find the <see cref="Reference"/>s
        /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>.
        /// </summary>
        /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param>
        /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param>
        /// <returns>The list of <see cref="Reference"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns>
        public static IEnumerable<Reference> ReachableFrom(
            this ReferenceCollection refsColl,
            IEnumerable<Commit> targets)
        {
            return ReachableFrom(refsColl, refsColl, targets);
        }
    }
}


text:
* [Legal Notice](notice.md)
* [Working with the Code](code.md)
* [IDE Integration](ide.md)
* [Building](building.md)
* [Tests](tests.md)
* [Code Formatting](formatting.md)
* [Notes for Maintainers](maintainers.md)


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

/**
 *

 * Contains the output of DescribeVolumeStatus.
 *

 */
public class DescribeVolumeStatusResult implements Serializable, Cloneable {

    /**
     *

     * A list of volumes.
     *

     */
    private com.amazonaws.internal.SdkInternalList<VolumeStatusItem> volumeStatuses;
    /**
     *

     * The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.
     *

     */
    private String nextToken;

    /**
     *

     * A list of volumes.
     *

     *
     * @return A list of volumes.
     */

    public java.util.List<VolumeStatusItem> getVolumeStatuses() {
        if (volumeStatuses == null) {
            volumeStatuses = new com.amazonaws.internal.SdkInternalList<VolumeStatusItem>();
        }
        return volumeStatuses;
    }

    /**
     *

     * A list of volumes.
     *

     *
     * @param volumeStatuses
     *        A list of volumes.
     */

    public void setVolumeStatuses(
            java.util.Collection<VolumeStatusItem> volumeStatuses) {
        if (volumeStatuses == null) {
            this.volumeStatuses = null;
            return;
        }

        this.volumeStatuses = new com.amazonaws.internal.SdkInternalList<VolumeStatusItem>(
                volumeStatuses);
    }

    /**
     *

     * A list of volumes.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setVolumeStatuses(java.util.Collection)} or
     * {@link #withVolumeStatuses(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param volumeStatuses
     *        A list of volumes.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeVolumeStatusResult withVolumeStatuses(
            VolumeStatusItem... volumeStatuses) {
        if (this.volumeStatuses == null) {
            setVolumeStatuses(new com.amazonaws.internal.SdkInternalList<VolumeStatusItem>(
                    volumeStatuses.length));
        }
        for (VolumeStatusItem ele : volumeStatuses) {
            this.volumeStatuses.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of volumes.
     *

     *
     * @param volumeStatuses
     *        A list of volumes.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeVolumeStatusResult withVolumeStatuses(
            java.util.Collection<VolumeStatusItem> volumeStatuses) {
        setVolumeStatuses(volumeStatuses);
        return this;
    }

    /**
     *

     * The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.
     *

     *
     * @param nextToken
     *        The token to use to retrieve the next page of results. This value
     *        is null when there are no more results to return.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.
     *

     *
     * @return The token to use to retrieve the next page of results. This value
     *         is null when there are no more results to return.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token to use to retrieve the next page of results. This value is
     * null when there are no more results to return.
     *

     *
     * @param nextToken
     *        The token to use to retrieve the next page of results. This value
     *        is null when there are no more results to return.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeVolumeStatusResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getVolumeStatuses() != null)
            sb.append("VolumeStatuses: " + getVolumeStatuses() + ",");
        if (getNextToken() != null)
            sb.append("NextToken: " + getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeVolumeStatusResult == false)
            return false;
        DescribeVolumeStatusResult other = (DescribeVolumeStatusResult) obj;
        if (other.getVolumeStatuses() == null
                ^ this.getVolumeStatuses() == null)
            return false;
        if (other.getVolumeStatuses() != null
                && other.getVolumeStatuses().equals(this.getVolumeStatuses()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null
                && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getVolumeStatuses() == null) ? 0 : getVolumeStatuses()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeVolumeStatusResult clone() {
        try {
            return (DescribeVolumeStatusResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
#region Using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;

#endregion

namespace NFixtureFactory.Util
{
    public static class ReflectionUtils
    {

        public static string GetPropertyName(this LambdaExpression expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            if(memberExpression == null)
            {
                throw new ArgumentOutOfRangeException("expression", "Expected a property/field access expression, not " + expression);
            }
            return memberExpression.Member.Name;
        }

        public static MemberInfo FindProperty(LambdaExpression lambdaExpression)
        {
            Expression expressionToCheck = lambdaExpression;

            bool done = false;

            while (!done)
            {
                switch (expressionToCheck.NodeType)
                {
                    case ExpressionType.Convert:
                        expressionToCheck = ((UnaryExpression) expressionToCheck).Operand;
                        break;
                    case ExpressionType.Lambda:
                        expressionToCheck = ((LambdaExpression) expressionToCheck).Body;
                        break;
                    case ExpressionType.MemberAccess:
                        var memberExpression = ((MemberExpression) expressionToCheck);

                        if (memberExpression.Expression.NodeType != ExpressionType.Parameter &&
                            memberExpression.Expression.NodeType != ExpressionType.Convert)
                        {
                            throw new ArgumentException(String.Format("Expression '{lambdaExpression}' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.", lambdaExpression));
                        }

                        MemberInfo member = memberExpression.Member;

                        return member;
                    default:
                        done = true;
                        break;
                }
            }

            throw new Exception(
                "Custom configuration for members is only supported for top-level individual members on a type.");
        }

        public static Type GetMemberType(this MemberInfo memberInfo)
        {
            if (memberInfo is MethodInfo)
                return ((MethodInfo) memberInfo).ReturnType;
            if (memberInfo is PropertyInfo)
                return ((PropertyInfo) memberInfo).PropertyType;
            if (memberInfo is FieldInfo)
                return ((FieldInfo) memberInfo).FieldType;
            return null;
        }

    }
}


text:
package org.jbox2d.dynamics;

import java.util.List;

import org.jbox2d.common.MathUtils;

public class Profile {
  private static final int LONG_AVG_NUMS = 20;
  private static final float LONG_FRACTION = 1f / LONG_AVG_NUMS;
  private static final int SHORT_AVG_NUMS = 5;
  private static final float SHORT_FRACTION = 1f / SHORT_AVG_NUMS;

  public static class ProfileEntry {
    float longAvg;
    float shortAvg;
    float min;
    float max;
    float accum;

    public ProfileEntry() {
      min = Float.MAX_VALUE;
      max = -Float.MAX_VALUE;
    }

    public void record(float value) {
      longAvg = longAvg * (1 - LONG_FRACTION) + value * LONG_FRACTION;
      shortAvg = shortAvg * (1 - SHORT_FRACTION) + value * SHORT_FRACTION;
      min = MathUtils.min(value, min);
      max = MathUtils.max(value, max);
    }

    public void startAccum() {
      accum = 0;
    }

    public void accum(float value) {
      accum += value;
    }

    public void endAccum() {
      record(accum);
    }

    @Override
    public String toString() {
      return String.format("%.2f (%.2f) [%.2f,%.2f]", shortAvg, longAvg, min, max);
    }
  }

  public final ProfileEntry step = new ProfileEntry();
  public final ProfileEntry stepInit = new ProfileEntry();
  public final ProfileEntry collide = new ProfileEntry();
  public final ProfileEntry solveParticleSystem = new ProfileEntry();
  public final ProfileEntry solve = new ProfileEntry();
  public final ProfileEntry solveInit = new ProfileEntry();
  public final ProfileEntry solveVelocity = new ProfileEntry();
  public final ProfileEntry solvePosition = new ProfileEntry();
  public final ProfileEntry broadphase = new ProfileEntry();
  public final ProfileEntry solveTOI = new ProfileEntry();

  public void toDebugStrings(List<String> strings) {
    strings.add("Profile:");
    strings.add(" step: " + step);
    strings.add("  init: " + stepInit);
    strings.add("  collide: " + collide);
    strings.add("  particles: " + solveParticleSystem);
    strings.add("  solve: " + solve);
    strings.add("   solveInit: " + solveInit);
    strings.add("   solveVelocity: " + solveVelocity);
    strings.add("   solvePosition: " + solvePosition);
    strings.add("   broadphase: " + broadphase);
    strings.add("  solveTOI: " + solveTOI);
  }
}


text:
import invariant from 'invariant';

const checkIndex = (index) => {
  if (!index) {
    return;
  }

  invariant(
    ['name', 'unique', 'composite', 'indexOnly']
      .every((t) => index.hasOwnProperty(t)),
    'An index requires `name`, `unique`, `composite`, and `indexOnly to be ' +
    'specified. Instead got: ' + JSON.stringify(index, null, 2)
  );

  const { indexOnly, ...rest } = index;

  invariant(
    indexOnly === false || typeof indexOnly === 'string',
    '`indexOnly` should either be a label specified as a string or should ' +
    'be set to `false`.'
  );

  if (!indexOnly) {
    return rest;
  }

  return { indexOnly, ...rest };
};

// Take in an Edge and return back the Label and any Index specified on it
const flattenEdge = (edge) => {
  const { name, multiplicity, directed } = edge;

  invariant(
    ['name', 'multiplicity', 'directed'].every((t) => edge.hasOwnProperty(t)),
    'An edge requires `name`, `multiplicity`, and `directed` to be specified. ' +
    'Instead got: ' + JSON.stringify(edge, null, 2)
  );

  return [
    { name, multiplicity, directed }
  ];
};

const flattenEdges = (edges) => edges
  .map(flattenEdge)
  .reduce((acc, [label]) => acc.concat(label), []);

const flattenProperty = (property) => {
  const { name, dataType, cardinality, index } = property;

  invariant(
    ['name', 'dataType', 'cardinality']
      .every((t) => property.hasOwnProperty(t)),
    'A property requires `name`, `dataType`, and `cardinality` to be ' +
    'specified. Instead got: ' + JSON.stringify(property, null, 2)
  );

  let validatedIndex;

  if (index) {
    validatedIndex = {
      propertyKeys: [name],
      ...checkIndex(index)
    };
  }

  return [
    { name, dataType, cardinality },
    validatedIndex
  ];
};

const flattenProperties = (properties, indexType) => properties
  .map(flattenProperty)
  .reduce((acc, [propertyKey, index]) => {
    const { propertyKeys, [indexType]: prevIndexType } = acc;
    const nextIndex = index
      ? prevIndexType.concat(index)
      : prevIndexType;

    return {
      propertyKeys: propertyKeys.concat(propertyKey),
      [indexType]: nextIndex,
    };
  }, {
    propertyKeys: [],
    [indexType]: []
  });

const flattenVertex = (vertex) => {
  const {
    name,
    properties: vertexProperties,
    inEdges,
    outEdges
  } = vertex;
  const allEdges = [...inEdges, ...outEdges];

  const edgeProperties = allEdges
    .filter((e) => e.properties)
    .map((e) => e.properties)
    .reduce((acc, p) => acc.concat(p), []);

  const properties = {
    ...flattenProperties(edgeProperties, 'edgeIndexes'),
    ...flattenProperties(vertexProperties, 'vertexIndexes')
  };

  const edges = flattenEdges(allEdges);

  return {
    vertexLabels: [{ name }],
    edgeLabels: edges,
    ...properties,
  };
};

const flattenVertices = (vertices) => vertices
  .map(flattenVertex)
  .reduce((acc, vertex) => ({
    edgeLabels: acc.edgeLabels.concat(vertex.edgeLabels),
    edgeIndexes: acc.edgeIndexes.concat(vertex.edgeIndexes),
    propertyKeys: acc.propertyKeys.concat(vertex.propertyKeys),
    vertexIndexes: acc.vertexIndexes.concat(vertex.vertexIndexes),
    vertexLabels: acc.vertexLabels.concat(vertex.vertexLabels)
  }), {
    edgeIndexes: [],
    edgeLabels: [],
    propertyKeys: [],
    vertexIndexes: [],
    vertexLabels: []
  });

export { flattenEdges };
export { flattenVertex };
export { flattenProperties };
export { flattenVertices };


text:
<?php

/**
 * The interface definition for a PureMVC View.
 *
 *

 * In PureMVC, IView implementors assume these responsibilities:

 *
 *

 * In PureMVC, the View class assumes these responsibilities:
 *

 *
Maintain a cache of IMediator instances.

 *
Provide methods for registering, retrieving, and removing IMediators.

 *
Managing the observer lists for each INotification in the application.

 *
Providing a method for attaching IObservers to an INotification's observer list.

 *
Providing a method for broadcasting an INotification.

 *
Notifying the IObservers of a given INotification when it broadcast.

 *

 *
 * @see org.puremvc.php.interfaces.IMediator IMediator
 * @see org.puremvc.php.interfaces.IObserver IObserver
 * @see org.puremvc.php.interfaces.INotification INotification
 */
interface IView
{
  /**
   * Register an IObserver to be notified
   * of INotifications with a given name.
   *
   * @param notificationName the name of the INotifications to notify this IObserver of
   * @param observer the IObserver to register
   */
  public function registerObserver ( $noteName, IObserver $observer );

  /**
   * Notify the IObservers for a particular INotification.
   *
   *

   * All previously attached IObservers for this INotification's
   * list are notified and are passed a reference to the INotification in
   * the order in which they were registered.

   *
   * @param notification the INotification to notify IObservers of.
   */
  public function notifyObservers( INotification $note );

  /**
   * Register an IMediator instance with the View.
   *
   *

   * Registers the IMediator so that it can be retrieved by name,
   * and further interrogates the IMediator for its
   * INotification interests.

   *

   * If the IMediator returns any INotification
   * names to be notified about, an Observer is created encapsulating
   * the IMediator instance's handleNotification method
   * and registering it as an Observer for all INotifications the
   * IMediator is interested in.

   *
   * @param mediatorName the name to associate with this IMediator instance
   * @param mediator a reference to the IMediator instance
   */
  public function registerMediator( IMediator $mediator );

  /**
   * Retrieve an IMediator from the View.
   *
   * @param mediatorName the name of the IMediator instance to retrieve.
   * @return the IMediator instance previously registered with the given mediatorName.
   */
  public function retrieveMediator( $mediatorName );

  /**
   * Remove an IMediator from the View.
   *
   * @param mediatorName name of the IMediator instance to be removed.
   */
  public function removeMediator( $mediatorName );

  /**
   * Check to see if a Mediator is registered with the View.
   *
   * @param mediatorName name of the IMediator instance to check for.
   */
  public function hasMediator( $mediatorName );

}
?>


text:
using JuMP
using Ipopt
using CPLEX
#using Gurobi
using Distributions

include("prob.jl")
include("cut.jl")

function master_problem(; file = "../data/nesta_case24_ieee_rts_nk.m", k = 4, solver = IpoptSolver(), model_constructor = SOCWRPowerModel, cut_constructor = "AC", initial_cut_file = "cascades_300/IEEE_300_2.txt")

    initial_cut_branches = []
    (initial_cut_file != "none") && (initial_cut_branches = readdlm(initial_cut_file, ',', Int64))
    data = PowerModels.parse_file(file)
    buses = Dict([(parse(Int, k), v) for (k, v) in data["bus"]])
    num_buses = length(buses)
    buses = filter((i, bus) -> bus["bus_type"] != 4, buses)
    branches = Dict([(parse(Int, k), v) for (k, v) in data["branch"]])
    branches = filter((i, branch) -> branch["br_status"] == 1 && branch["f_bus"] in keys(buses) && branch["t_bus"] in keys(buses), branches)
    branch_indexes = collect(keys(branches))
    loads = Dict([(parse(Int, k), v) for (k, v) in data["load"]])
    loads = filter((i, load) -> load["status"] == 1 && load["load_bus"] in keys(buses), loads)

    log_p = Dict([(i, log(branches[i]["prob"])) for i in branch_indexes])

    totalload = 0.0
    for (i,load) in loads
        totalload += load["pd"]
    end
    # println("total load: $totalload ...")

    quit()
    #master_problem = Model(solver=GurobiSolver(LogToConsole=0))
    master_problem = Model(solver=CplexSolver())
    @variable(master_problem, 1e-6 <= eta <= 1e6)
    @variable(master_problem, x[i in branch_indexes], Bin)
    @variable(master_problem, p <= 0)
    @variable(master_problem, y <= 1e6)

    @constraint(master_problem, sum(x) == k)
    @constraint(master_problem, p == sum(x[i]*log_p[i] for i in branch_indexes))

    # adding cuts to remove some previously found solutions
    for i in 1:size(initial_cut_branches)[1]
        expr = zero(AffExpr)
        for j in initial_cut_branches[i,:]
            append!(expr, x[j])
        end
        @constraint(master_problem, expr <= k-1)
    end

    @objective(master_problem, Max, y)
    # add outer approximation of constraint y ⩽ p + log η using lazy constraint callback:  y ⩽ p + log η₀ + 1/η₀(η - η₀)
    # outer approximation of y ⩽ f(x) at x = xᵏ : y ⩽ f(xᵏ) + ∇f(xᵏ)⋅(x-xᵏ)

    function outer_approximate(cb)
        eta_val = getvalue(eta)
        p_val = getvalue(p)
        if eta_val > 0.0
            inv_eta_val = 1/eta_val
            @lazyconstraint(cb, y <= p + log(eta_val) + inv_eta_val*(eta - eta_val))
        end
    end

    addlazycallback(master_problem, outer_approximate)

    # anonymous function
    x_val = i -> getvalue(x[i])

    zlb = -1e10
    zub = 1e10
    eps = 1e-6

    time_taken = 0
    tic()
    solve(master_problem)

    iteration = 0
    final_xvals = Dict{Any,Any}
    final_lines = Any[]

    if (model_constructor == DCPPowerModel)
        cut_constructor = "DC"
    end

    while (zub - zlb > 0.01)
        iteration += 1
        current_xvals = Dict(i => x_val(i) for i in branch_indexes)
        current_lines = collect(keys(filter( (i, xval) -> xval > 1e-4, current_xvals)))
        p_val = getvalue(p)
        for index in current_lines
            data["branch"][string(index)]["br_status"] = 0
        end
        pm = model_constructor(data; solver = solver)
        post_pfls(pm)
        status, solve_time = solve(pm)
        for index in current_lines
            data["branch"][string(index)]["br_status"] = 1
        end
        result = PowerModels.build_solution(pm, status, solve_time)
        alpha = get_cut_coefficients(pm, cut_constructor = cut_constructor)
        sub_objective = result["objective"]
        sub_lb = p_val + log(sub_objective)
        if (sub_lb - zlb > eps)
            zlb = sub_lb
            final_xvals = current_xvals
            final_lines = current_lines
        end
        expr = zero(AffExpr)
        for i in branch_indexes
            if (current_xvals[i] > 0.9)
                append!(expr, x[i])
            end
        end
        @constraint(master_problem, expr <= k-1)
        @constraint(master_problem, eta <= sub_objective + sum(alpha[i]*x[i] for i in collect(keys(alpha))))
        solve(master_problem)
        zub = getobjectivevalue(master_problem)
        time_taken += toq()

        min_value = eps + abs(zlb)
        rel_gap = abs(zub-zlb)
        rel_gap = (min_value > eps) ? rel_gap/min_value : rel_gap
        print("ub: $zub, lb: $zlb, rel_gap: $((zub-zlb)/(eps+abs(zlb))), abs_gap: $(zub-zlb), ")
        p_val = 0.0
        for i in final_lines
            p_val += log_p[i]
        end
        print("solution: $(collect(final_lines)), ")
        log_eta = zlb - p_val
        actual_prob = exp(p_val)
        eta_val = exp(log_eta)
        print("prob: $actual_prob, ")
        print("load_shed: $eta_val, ")
        print("time_taken: $time_taken. \n")
        tic()

        if time_taken >= 86400
            break
        end

        if rel_gap <= 0.05 && sign(zlb)*sign(zub) > 0
            break
        end
    end

    p_val = 0.0
    for i in final_lines
        p_val += log_p[i]
    end
    println("###################################")
    println("k ... $k")
    println("solution = x* ... $(collect(final_lines))")
    println("model: $(model_constructor), cut_type: $(cut_constructor)")
    println("total number of iterations ... $iteration")
    println("solution cost = logprob(x*) + log(η(x*)) ... $zlb")
    println("probability = logprob(x*) ... $p_val")
    log_eta = zlb - p_val
    actual_prob = exp(p_val)
    eta_val = exp(log_eta)
    println("probability = prob(x*) ... $actual_prob")
    println("load shed = η* ... $eta_val")
    println("expected load shed = prob(x*)⋅η* ... $(actual_prob*eta_val)")
    time_taken += toq()
    println("time ... $time_taken")
    # solving the AC load shed model on the final set of lines
    for index in final_lines
        data["branch"][string(index)]["br_status"] = 0
    end
    pm = ACPPowerModel(data; solver = IpoptSolver(print_level=0))
    post_pfls(pm)
    status, solve_time = solve(pm)
    result = PowerModels.build_solution(pm, status, solve_time)
    println("full AC load shed ... $(result["objective"])")
    println("expected AC load shed ... $(actual_prob*result["objective"])")
    println("###################################")
    solution = Dict{AbstractString,Any}("k" => k, "lines" => collect(final_lines),
                                        "model" => model_constructor, "time" => time_taken,
                                        "cut" => cut_constructor, "prob" => actual_prob,
                                        "load_shed" => eta_val,
                                        "expected_load_shed" => actual_prob*eta_val,
                                        "ac_load_shed" => result["objective"],
                                        "expected_ac_load_shed" => actual_prob*result["objective"],
                                        "iterations" => iteration)
    push!(solution_vector, solution)

    return num_buses
end

# solution_dict = Dict{AbstractString,Any}()
solution_vector = Any[]

args = Dict{Any,Any}()
println(ARGS[1])
args["file"] = String(ARGS[1])
args["initial_nk_cut_file"] = String(ARGS[2])
args["k"] = parse(Int, ARGS[3])
args["nf"] = parse(Int, ARGS[4]) # 0 - all three, 1 - only nf, 2 - no nf, 3 - only soc (hurricane case/uniform case)
(args["initial_nk_cut_file"] == "none") && (assert(args["nf"] == 3))

if args["nf"] == 0
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = NFPowerModel, cut_constructor = "DC")
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = DCPPowerModel, cut_constructor = "DC")
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = SOCWRPowerModel, cut_constructor = "DC")
elseif args["nf"] == 1
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = NFPowerModel, cut_constructor = "DC")
elseif args["nf"] == 3
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = SOCWRPowerModel, cut_constructor = "DC", initial_cut_file=args["initial_nk_cut_file"])
else
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = DCPPowerModel, cut_constructor = "DC")
    num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = SOCWRPowerModel, cut_constructor = "DC")
end
# num_buses = master_problem(file = args["file"], k = args["k"], solver = CplexSolver(), model_constructor = SOCWRPowerModel, cut_constructor = "AC")

println(solution_vector)

#= original n-k Networks paper output-writes
if args["nf"] == 0
    f = open("./output_files/$(num_buses)_$(args["k"])", "w")
elseif args["nf"] == 1
    f = open("./output_files/$(num_buses)_$(args["k"])_nf", "w")
elseif args["nf"] == 3 # only use for probability distribution study where case hi or ui is appended to file name
    a = args["file"]
    if args["file"] != "../data/nesta_case1354_pegase_nk.m"
        case = split(split(a, "_")[length(split(a, "_"))], ".")[1]
        f = open("./output_files/$(num_buses)_$(args["k"])_soc_$(case)", "w")
    else
        f = open("./output_files/$(num_buses)_$(args["k"])_soc", "w")
    end
else
    f = open("./output_files/$(num_buses)_$(args["k"])_nonf", "w")
end

write(f, "case model k time iterations probability load_shed expected_load_shed ac_load_shed expected_ac_load_shed lines\n")
for solution in solution_vector
    if solution["model"] == PowerModels.GenericPowerModel{StandardNFForm}
        write(f, "$(num_buses) nf $(solution["k"]) $(solution["time"]) $(solution["iterations"]) $(solution["prob"]) $(solution["load_shed"]) $(solution["expected_load_shed"]) $(solution["ac_load_shed"]) $(solution["expected_ac_load_shed"]) $(solution["lines"]) \n")
    end
    if solution["model"] == PowerModels.GenericPowerModel{PowerModels.StandardDCPForm}
        write(f, "$(num_buses) dc $(solution["k"]) $(solution["time"]) $(solution["iterations"]) $(solution["prob"]) $(solution["load_shed"]) $(solution["expected_load_shed"]) $(solution["ac_load_shed"]) $(solution["expected_ac_load_shed"]) $(solution["lines"]) \n")
    end
    if solution["model"] == PowerModels.GenericPowerModel{PowerModels.SOCWRForm}
        write(f, "$(num_buses) soc $(solution["k"]) $(solution["time"]) $(solution["iterations"]) $(solution["prob"]) $(solution["load_shed"]) $(solution["expected_load_shed"]) $(solution["ac_load_shed"]) $(solution["expected_ac_load_shed"]) $(solution["lines"]) \n")
    end
end

close(f)
=#

#= Commented out before n-k networks paper final runs
solution_dict["solution"] = solution_vector
json_string = JSON.json(solution_dict)
if endswith(args["file"], "api.m")
    write("./json_files/stoch_$(args["k"])_$(num_buses)_api.json", json_string)
elseif endswith(args["file"], "sad.m")
    write("./json_files/stoch_$(args["k"])_$(num_buses)_sad.json", json_string)
else
    write("./json_files/stoch_$(args["k"])_$(num_buses).json", json_string)
end
=#


text:
//----------------------------------------------------------------------------
//
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  David Burken
//
// Description: Common code for this plugin.
//
//----------------------------------------------------------------------------
// $Id$

#ifndef ossimPluginCommon_HEADER
#define ossimPluginCommon_HEADER 1

#include <string>
#include <vector>
#include <ossim/base/ossimRefPtr.h>

class ossimString;
class ossimXmlDocument;
class ossimXmlNode;

namespace ossimplugins
{

class CivilDateTime;

namespace ossim
{
   /**
    * @note This code was moved out of ossimRadarSat2Model.
    *
    * @brief Converts date string from ISO 8601 format to CivilDateTime.
    *
    * @param dateString Input date string.
    *
    * @param outputDate Output date object to initialize.
    *
    * @return true on success false on error.
    */
   bool iso8601TimeStringToCivilDate(const std::string& dataString,
                                     CivilDateTime& outputDate);

   /**
    * @brief Gets path from doc and initializes string.
    * @param path Xml path to look for.
    * @param xdoc Xml doc to look in.
    * @param s String to initialize.
    * @return true on success and false if path is not found or if there
    * are more than one of path.
    * @note You should call getPath that takes a vector for things that are
    * repetitive.
    */
   bool getPath(const ossimString& path,
                const ossimXmlDocument* xdoc,
                ossimString& s);

   /**
    * @brief Gets path from doc and initializes string.
    * @param path Xml path to look for.
    * @param xdoc Xml doc to look in.
    * @param v Vector to initialize.
    * @return true on success and false if path is not found.
    */
   bool getPath(const ossimString& path,
                const ossimXmlDocument* xdoc,
                std::vector<ossimString>& v);

   /**
    * @brief Finds from node with path from node and initializes string.
    *
    * @param path Xml path to look for.
    *
    * @param node Xml node to look in.
    *
    * @param s String to initialize.
    *
    * @return true on success and false if path is not found or if text is
    * empty from found node..
    */
   bool findFirstNode(const ossimString& path,
                      ossimRefPtr<ossimXmlNode> node,
                      ossimString& s);

} // matches: namespace ossim
}

#endif /* matches: #ifndef ossimPluginCommon_HEADER */


text:
using System.Web;
using System.Web.Optimization;

namespace rpg
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/modaljquery").Include(
                        "~/Scripts/bmodal.js"));

            bundles.Add(new ScriptBundle("~/bundles/Basejquery").Include(
                        "~/Scripts/jquery.validate.js",
                        "~/Scripts/jquery-2.1.3.min.js",
                        "~/Scripts/Uteis.js"));

            bundles.Add(new StyleBundle("~/bundles/Logincss").Include(
                      "~/Content/Login.css"));

            bundles.Add(new StyleBundle("~/bundles/Basecss").Include(
                      "~/Content/Basico.css"));

            bundles.Add(new StyleBundle("~/bundles/gridcss").Include(
                     "~/Content/Grid.css"));

            bundles.Add(new StyleBundle("~/bundles/modalcss").Include(
                     "~/Content/Modal.css"));

            BundleTable.EnableOptimizations = true;
        }
    }
}