text:
using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OAuth2ClientSamples.Controllers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace AspnetWebMvc
{
    public class OAuth2Client
    {
        private Uri uri;
        private string clientId;

        private HttpClient _client;

        public OAuth2Client(string clientId)
        {
            uri = new Uri(ApplicationSettings.Authority);
            this.clientId = clientId;
            this._client = new HttpClient()
            {
                BaseAddress = uri
            };
        }

        internal static string CreateAuthorizationUrl(string authority
                                                        , string clientId
                                                        , string scope
                                                        , string redirectUri
                                                        , string responseType
                                                        , string responseMode
                                                        , string maxAge
                                                        , string codeVerifier
                                                        , string whr
                                                        , string state = null
                                                        , string prompt=null)
        {
            string nonce = Guid.NewGuid().ToString("N");

            var result = OAuth2Client.CreateUrl(GenerateAuthorizeEndpoint(authority), clientId, scope, redirectUri, responseType
                            , responseMode, maxAge, codeVerifier, whr, state, prompt, nonce);
            if (!string.IsNullOrEmpty(ApplicationSettings.IdTokenHint))
            {
                result = string.Format("{0}&id_token_hint={1}", result, ApplicationSettings.IdTokenHint);
            }
            return result;
        }

        public OAuth2TokenResponse RequestAccessTokenCode(string code, Uri redirectUri, string codeVerifier)
        {
            HttpResponseMessage result = this._client.PostAsync(GenerateTokenEndpoint(this.uri.AbsoluteUri), (HttpContent)this.GetTokenPostContent(code, redirectUri, codeVerifier)).Result;
            var response = JsonConvert.DeserializeObject<OAuth2TokenResponse>(result.Content.ReadAsStringAsync().Result);
            return response;
        }

        public OAuth2TokenResponse RequestAccessTokenRefreshToken(string refreshToken)
        {
            HttpResponseMessage result = this._client.PostAsync(GenerateTokenEndpoint(this.uri.AbsoluteUri), (HttpContent)this.ExchangeTokenFormPostContent(refreshToken)).Result;
            return JsonConvert.DeserializeObject<OAuth2TokenResponse>(result.Content.ReadAsStringAsync().Result);
        }

        private static string GenerateAuthorizeEndpoint(string authority)
        {
            return string.Format("{0}/authorize.idp", authority);
        }

        private static string GenerateTokenEndpoint(string authority)
        {
            var endpoint = string.Format("{0}/token.idp", authority);
            return endpoint;
        }

        private static string CreateUrl(string endpoint
                                , string clientId
                                , string scope
                                , string redirectUri
                                , string responseType
                                , string responseMode
                                , string maxAge
                                , string codeVerifier
                                , string whr
                                , string state = null
                                , string prompt = null
                                , string nonce = null)
        {
            string str = string.Format("{0}?client_id={1}&scope={2}&redirect_uri={3}&response_type={4}"
                , endpoint
                , ApplicationSettings.UrlEncode(clientId)
                , ApplicationSettings.UrlEncode(scope)
                , ApplicationSettings.UrlEncode(redirectUri)
                , ApplicationSettings.UrlEncode(responseType));

            var codeChallengeMethod = ApplicationSettings.CodeChallengeMethod;
            if (responseType.Contains("code") && codeChallengeMethod.ToLower() != "none")
            {
                var codeChallenge = codeVerifier;
                if (codeChallengeMethod == "S256")
                {
                    using (var sha256 = SHA256.Create())
                    {
                        var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                        codeChallenge = Base64Url.Encode(challengeBytes);
                    }
                }

                str = string.Format("{0}&code_challenge={1}&code_challenge_method={2}", str,
                    ApplicationSettings.UrlEncode(codeChallenge),
                    ApplicationSettings.UrlEncode(codeChallengeMethod));
            }

            if (ApplicationSettings.UsingRequestObject != "true")
            {
                if (!string.IsNullOrEmpty(maxAge))
                {
                    str = string.Format("{0}&max_age={1}", str, ApplicationSettings.UrlEncode(maxAge));
                }
                if (!string.IsNullOrEmpty(responseMode))
                {
                    str = string.Format("{0}&response_mode={1}", str, ApplicationSettings.UrlEncode(responseMode));
                }
                if (!string.IsNullOrWhiteSpace(state))
                {
                    str = string.Format("{0}&state={1}", str, ApplicationSettings.UrlEncode(state));
                }
                if (!string.IsNullOrWhiteSpace(prompt))
                {
                    str = string.Format("{0}&prompt={1}", str, ApplicationSettings.UrlEncode(prompt));
                }
                if (!string.IsNullOrWhiteSpace(nonce))
                {
                    str = string.Format("{0}&nonce={1}", str, ApplicationSettings.UrlEncode(nonce));
                }
                if (!string.IsNullOrWhiteSpace(whr))
                {
                    str = string.Format("{0}&whr={1}", str, ApplicationSettings.UrlEncode(whr));
                }
            }
            else
            {
                var claimsIdentify = new ClaimsIdentity();
                claimsIdentify.AddClaim(new Claim("client_id", clientId));
                claimsIdentify.AddClaim(new Claim("response_type", responseType));
                claimsIdentify.AddClaim(new Claim("scope", scope));
                claimsIdentify.AddClaim(new Claim("redirect_uri", redirectUri));
                claimsIdentify.AddClaim(new Claim("max_age", maxAge));
                claimsIdentify.AddClaim(new Claim("response_mode", responseMode));
                claimsIdentify.AddClaim(new Claim("state", state));
                claimsIdentify.AddClaim(new Claim("prompt", prompt));
                claimsIdentify.AddClaim(new Claim("nonce", nonce));
                claimsIdentify.AddClaim(new Claim("whr", whr));
                string token;
                if (ApplicationSettings.SignRequestObject == "true")
                {
                    var securityTokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject = claimsIdentify,
                        Issuer = clientId,
                        IssuedAt = DateTime.UtcNow,
                        Expires = DateTime.UtcNow.AddYears(10),
                        Audience = endpoint
                    };
                    var signingCertificate = LoadCertificate(StoreName.My, StoreLocation.LocalMachine, ApplicationSettings.ClientCertificate);
                    securityTokenDescriptor.SigningCredentials = new X509SigningCredentials(signingCertificate, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
                    token = new JwtSecurityTokenHandler().CreateEncodedJwt(securityTokenDescriptor);
                }
                else
                {
                    var jwtSecurityToken = new JwtSecurityTokenHandler().CreateJwtSecurityToken(clientId, endpoint, claimsIdentify, DateTime.UtcNow, DateTime.UtcNow.AddYears(10), DateTime.UtcNow);
                    token = "eyJhbGciOiJub25lIn0" + "." + jwtSecurityToken.EncodedPayload + ".";
                }

                str += "&request=" + token;
            }

            return str;
        }

        protected virtual FormUrlEncodedContent ExchangeTokenFormPostContent(string refreshToken)
        {
            Dictionary<string, string> parameters = GenerateTokenEndpointRequestParameters();
            parameters.Add("grant_type", "refresh_token");
            parameters.Add("refresh_token", refreshToken);
            return OAuth2Client.CreateForm(parameters);
        }

        private Dictionary<string, string> GenerateTokenEndpointRequestParameters()
        {
            var result = new Dictionary<string, string>();
            if (ApplicationSettings.AuthenticationType == "client_secret_post")
            {
                result.Add("client_id", this.clientId);
                result.Add("client_secret", ApplicationSettings.ClientSecret);
            }
            else if (ApplicationSettings.AuthenticationType == "private_key_jwt")
            {
                result.Add("client_assertion", GenerateClientAssertion());
                result.Add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
            }
            else
            {
                var byteArray = new UTF8Encoding().GetBytes(string.Format("{0}:{1}", clientId, ApplicationSettings.ClientSecret));
                _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            }
            return result;
        }

        private string GenerateClientAssertion()
        {
            var signingCertificate = LoadCertificate(StoreName.My, StoreLocation.LocalMachine, ApplicationSettings.ClientCertificate);
            var claimsIdentify = new ClaimsIdentity();
            claimsIdentify.AddClaim(new Claim("sub", this.clientId));
            claimsIdentify.AddClaim(new Claim("aud", ApplicationSettings.Authority + "/token.idp"));
            claimsIdentify.AddClaim(new Claim("exp", DateTime.UtcNow.AddYears(10).ToLongDateString(), ClaimValueTypes.DateTime));
            claimsIdentify.AddClaim(new Claim("jti", Guid.NewGuid().ToString()));

            var token = new JwtSecurityTokenHandler().CreateEncodedJwt(new SecurityTokenDescriptor
            {
                Subject = claimsIdentify,
                Issuer = this.clientId,
                SigningCredentials = new X509SigningCredentials(signingCertificate, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"),
                IssuedAt = DateTime.UtcNow,
                Expires = DateTime.UtcNow.AddYears(10)
            });
            return token;
        }

        protected virtual FormUrlEncodedContent GetTokenPostContent(string code, Uri redirectUri, string codeVerifier, Dictionary<string, string> additionalProperties = null)
        {
            Dictionary<string, string> parameters = GenerateTokenEndpointRequestParameters();
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", redirectUri.AbsoluteUri);
            parameters.Add("code", code);
            parameters.Add("code_verifier", codeVerifier);
            return OAuth2Client.CreateForm(parameters);
        }

        /// <summary>
        /// FormUrlEncodes both Sets of Key Value Pairs into one form object
        ///
        /// </summary>
        /// <param name="explicitProperties"/><param name="additionalProperties"/>
        /// <returns/>
        private static FormUrlEncodedContent CreateForm(Dictionary<string, string> explicitProperties, Dictionary<string, string> additionalProperties = null)
        {
            return new FormUrlEncodedContent((IEnumerable<KeyValuePair<string, string>>)OAuth2Client.MergeAdditionKeyValuePairsIntoExplicitKeyValuePairs(explicitProperties, additionalProperties));
        }

        /// <summary>
         /// Merges additional into explicit properties keeping all explicit properties intact
         ///
         /// </summary>
         /// <param name="explicitProperties"/><param name="additionalProperties"/>
         /// <returns/>
        private static Dictionary<string, string> MergeAdditionKeyValuePairsIntoExplicitKeyValuePairs(Dictionary<string, string> explicitProperties, Dictionary<string, string> additionalProperties = null)
        {
            Dictionary<string, string> dictionary = explicitProperties;
            if (additionalProperties != null)
                dictionary = Enumerable.ToDictionary(Enumerable.Concat(explicitProperties
                    , Enumerable.Where(additionalProperties
                    , (add => !explicitProperties.ContainsKey(add.Key))))
                    , (final => final.Key)
                    , (final => final.Value));
            return dictionary;
        }

        private static X509Certificate2 LoadCertificate(StoreName storename, StoreLocation storelocation, string value)
        {
            var _store = new X509Store(storename, storelocation);
            _store.Open(OpenFlags.ReadOnly);
            var certificate = _store.Certificates.Find(X509FindType.FindByThumbprint, value, false)[0];
            return certificate;
        }
    }
}


text:
cask "app-tamer" do
  version "2.7.5,11617"
  sha256 "0451d3912a157d6cbd43a1462d1fc6b9bcd0de102976fc5d5281656427093ac6"

  url "https://www.stclairsoft.com/download/AppTamer-#{version.csv.first}.dmg"
  name "AppTamer"
  desc "CPU management applicataion"
  homepage "https://www.stclairsoft.com/AppTamer/"

  livecheck do
    url "https://www.stclairsoft.com/cgi-bin/sparkle.cgi?AT"
    strategy :sparkle
  end

  app "App Tamer.app"

  uninstall delete: [
    "/Library/LaunchDaemons/com.stclairsoft.AppTamerAgent.plist",
    "/Library/PrivilegedHelperTools/com.stclairsoft.AppTamerAgent",
  ]

  zap trash: [
    "~/Library/Caches/com.stclairsoft.AppTamer",
    "~/Library/Preferences/com.stclairsoft.AppTamer.plist",
  ]
end

redpajama_set_name: RedPajamaGithub


text:
class Zoo
  include DataMapper::Resource

  property :id,           Serial
  property :name,         String
  property :description,  Text
  property :inception,    DateTime
  property :open,         Boolean,  :default => false
  property :size,         Integer
  property :mission,      Text, :writer => :protected

  has n, :animals

  def to_s
    name
  end
end

class Species
  include DataMapper::Resource

  property :id,             Serial
  property :name,           String
  property :classification, String, :reader => :private

  has n, :animals
end

class Animal
  include DataMapper::Resource

  property :id,   Serial
  property :name, String

  belongs_to :zoo
  belongs_to :species
  belongs_to :keeper
end

class Employee
  include DataMapper::Resource

  property :name, String, :key => true
end

class Keeper < Employee
  has n, :animals
end


text:
package com.shopping.basket.test;

import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.util.Closeable;
import com.shopping.basket.Model.ListModel;
import com.shopping.basket.Service.ListManagerService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static com.shopping.basket.OfyService.ofy;
import static org.junit.Assert.assertEquals;

/**
 * Tests for lists manager
 */
public class ListManagerServiceTest {

    private ListManagerService listManagerService = new ListManagerService();

    private final LocalServiceTestHelper helper =
            new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
    private Closeable closeable;

    public ListManagerServiceTest(){
        ObjectifyService.register(ListModel.class);
    }

    public void initializeData(){
        ListModel l1 = new ListModel(null, "Camping", "Stuff needed for camping.");
        ListModel l2 = new ListModel(null, "Road Trip", "Must haves for the road trip");
        listManagerService.addList(l1);
        listManagerService.addList(l2);
    }

    @Before
    public void setUp() {
        helper.setUp();
        closeable = ObjectifyService.begin();
        this.initializeData();
    }

    @After
    public void tearDown() {
        closeable.close();
        helper.tearDown();
    }

    @Test
    public void getAllTest(){
        List<ListModel> list = this.listManagerService.getAllList();
        assertEquals(2, list.size());
    }

    @Test
    public void addListTest(){
        ListModel l3 = new ListModel(3L, "Trek", "Things you need to survive the trek");
        this.listManagerService.addList(l3);
        ListModel listItem  = ofy().load().key(Key.create(ListModel.class, l3.getListId())).now();
        assertEquals(3, listManagerService.getAllList().size());
        assertEquals(l3, listItem);
    }

    @Test
    public void deleteListTest(){
        this.listManagerService.deleteListEntry(2L);
        assertEquals(1, listManagerService.getAllList().size());
    }

    @Test
    public void updateListTest(){
        ListModel updatedCampingList = new ListModel(1L, "Trek", "Things you need to survive the trek");
        this.listManagerService.update(updatedCampingList);
        ListModel newListModel = ofy().load().key(Key.create(ListModel.class, 1)).now();
        assertEquals("Trek", newListModel.getListName());
    }

}


text:
package com.amazonaws.services.apigateway.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.SdkHttpUtils;
import com.amazonaws.protocol.json.*;

/**
 * DeleteAuthorizerRequest Marshaller
 */
public class DeleteAuthorizerRequestMarshaller implements
        Marshaller<Request<DeleteAuthorizerRequest>, DeleteAuthorizerRequest> {

    private static final String DEFAULT_CONTENT_TYPE = "application/x-amz-json-1.1";

    private final SdkJsonProtocolFactory protocolFactory;

    public DeleteAuthorizerRequestMarshaller(
            SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<DeleteAuthorizerRequest> marshall(
            DeleteAuthorizerRequest deleteAuthorizerRequest) {

        if (deleteAuthorizerRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<DeleteAuthorizerRequest> request = new DefaultRequest<DeleteAuthorizerRequest>(
                deleteAuthorizerRequest, "AmazonApiGateway");

        request.setHttpMethod(HttpMethodName.DELETE);

        String uriResourcePath = "/restapis/{restapi_id}/authorizers/{authorizer_id}";

        uriResourcePath = uriResourcePath.replace(
                "{restapi_id}",
                (deleteAuthorizerRequest.getRestApiId() != null) ? SdkHttpUtils
                        .urlEncode(StringUtils
                                .fromString(deleteAuthorizerRequest
                                        .getRestApiId()), false) : "");
        uriResourcePath = uriResourcePath
                .replace(
                        "{authorizer_id}",
                        (deleteAuthorizerRequest.getAuthorizerId() != null) ? SdkHttpUtils
                                .urlEncode(StringUtils
                                        .fromString(deleteAuthorizerRequest
                                                .getAuthorizerId()), false)
                                : "");
        request.setResourcePath(uriResourcePath);

        request.setContent(new ByteArrayInputStream(new byte[0]));
        if (!request.getHeaders().containsKey("Content-Type")) {
            request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
        }

        return request;
    }

}


text:
<?php
// alright, here we check if this row is in either commited in the database, or
// or already in the unconf pool
// if neither then we add the list to the unconf pool and wait for conf
// if its in unconf and its the same, then we move unconf.

// we also need to do a check auth in here at some point...
// but that requires a login first..

function saveteam($team, $data)
{
	if(!file_exists("./data/teams/".$team.".json"))
	{
		// no team, lets just drop these here.
		$file = new STDClass();
		$file->games = array();
	}
	else
	{
		$file = json_decode(file_get_contents("./data/teams/".$team.".json"));
		if(!isset($file->games)) $file->games = array();
	}
	array_push($file->games, $data);

	file_put_contents("./data/teams/".$team.".json", json_encode($file));
}

if(!isset($_COOKIE['hash']) || !isset($_COOKIE['team']))
{
	echo "ERROR: Must be logged in to complete request";
	die;
}

if(!file_exists("./data/passwd/".$_COOKIE['team'].".json"))
{
	echo "ERROR: Logged in team does not exist.";
	die;
}

$pwd = json_decode(file_get_contents("./data/passwd/".$_COOKIE['team'].".json"));
$check = hash("sha256", $_COOKIE['hash']);

if($check != $pwd->hash)
{
	echo "ERROR: Session variable is incorrect.";
	die;
}

// now the rest;

/*if(!isset($_POST['comp']) || !isset($_POST['match']) || !isset($_POST['red1']) || !isset($_POST['red2']) || !isset($_POST['redscore']) || !isset($_POST['blue1']) || !isset($_POST['blue2']) || !isset($_POST['bluescore']));
{
	echo isset($_POST['bluescore']);
	echo json_encode($_POST);
	echo "ERROR: missing data, cannot complete request";
	die;
}*/

if(!file_exists("./data/unconf/".$_POST['comp'].".json"))
{
	// we have a comp where no unconf data has come in yet
	$unconf = new STDClass();
	$unconf->rows = array();
	$unconf->confed = array();

	// any init logic here...
}
else
{
	$unconf = json_decode(file_get_contents("./data/unconf/".$_POST['comp'].".json"));
}

foreach($unconf->confed as $conf)
{
	if($conf == $_POST['match'])
	{
		echo "ERROR: this match score has already been confirmed";
		die;
	}
}

$obj = new STDClass();
	$obj->comp = $_POST['comp'];
	$obj->match = $_POST['match'];
	$obj->red1 = $_POST['red1'];
	$obj->red2 = $_POST['red2'];
	$obj->redscore = $_POST['redscore'];
	$obj->blue1 = $_POST['blue1'];
	$obj->blue2 = $_POST['blue2'];
	$obj->bluescore = $_POST['bluescore'];
	$obj->contrib = $_COOKIE['team'];

	if(isset($_POST['bluepenalty']) && strlen($_POST['bluepenalty']) != 0)
		$obj->bluepenalty = $_POST['bluepenalty'];
	else
		$obj->bluepenalty = "0";

	if(isset($_POST['redpenalty']) && strlen($_POST['redpenalty']) != 0)
		$obj->redpenalty = $_POST['redpenalty'];
	else
		$obj->redpenalty = "0";

$found = false;
foreach($unconf->rows as $row)
{
	if($row->match == $_POST['match'])
	{
		if((($row->red1 == $_POST['red1'] && $row->red2 == $_POST['red2'])
			|| ($row->red1 == $_POST['red2'] && $row->red2 == $_POST['red1']))
			&& ($row->redscore == $_POST['redscore'])
			&& (($row->blue1 == $_POST['blue1'] && $row->blue2 == $_POST['blue2'])
			|| ($row->blue1 == $_POST['blue2'] && $row->blue2 == $_POST['blue1']))
			&& ($row->bluescore == $_POST['bluescore'])
			&& ($row->bluepenalty == $obj->bluepenalty)
			&& ($row->redpenalty == $obj->redpenalty))
		{
			// this is a match, move it to confirmed and remove from unconf, and check off on confed list.
			if($row->contrib == $_COOKIE['team'])
			{
				echo "ERROR: Data must be validated by a different team";
				continue;
			}
			// ok, we need to credit accounts with points here...
			echo "row confirmed and added";
			$orig = json_decode(file_get_contents("./data/teams/".$row->contrib.".json"));
			$orig->contribution += 3;
			file_put_contents("./data/teams/".$row->contrib.".json", json_encode($orig));

			$supp = json_decode(file_get_contents("./data/teams/".$_COOKIE['team'].".json"));
			$supp->contribution += 2;
			file_put_contents("./data/teams/".$_COOKIE['team'].".json", json_encode($supp));

			$contrib = json_decode(file_get_contents("./data/contrib.json"));
			$onum = (string)$orig->number;
			$snum = (string)$supp->number;
			$contrib->teams->$onum->pts += 3;
			$contrib->teams->$snum->pts += 2;
			file_put_contents("./data/contrib.json", json_encode($contrib));

			array_push($unconf->confed, $_POST['match']);
			$comp = json_decode(file_get_contents("./data/comps/".$_POST['comp'].".json"));
			if(!isset($comp->rows)) $comp->rows = array();
			array_push($comp->rows, $row);
			$comp->rng = rand();

			file_put_contents("./data/comps/".$_POST['comp'].".json", json_encode($comp));

			saveteam($_POST['red1'], $obj);
			saveteam($_POST['red2'], $obj);
			saveteam($_POST['blue1'], $obj);
			saveteam($_POST['blue2'], $obj);

			$found = true;
			break;
		}
	}
}

if(!$found)
{
	array_push($unconf->rows, $obj);
}

file_put_contents("./data/unconf/".$_POST['comp'].".json", json_encode($unconf));

// now lets send some postdata?

echo "<form action='./comp/?".$_POST['comp']."' method='post' name='frm'>";

if($found) echo "<input type='hidden' name='message' value='You have confirmed match data. Row Added.'>";
else echo "<input type='hidden' name='message' value='Match data added. Data must now be confirmed by another team to be valid.'>";
?>

</form>
<script>
document.frm.submit();
</script>


text:
/**
 * Created by yunzhou on 11/12/2016.
 */
import { shallow, mount } from 'enzyme';
import React from 'react';
import { IntlProvider } from 'react-intl';
import { NewsFeedList } from '../newsfeedlist';

describe('<NewsFeedList />', () => {
  const tour1ID = '1011';
  const tour1Newsfeed = [
    {
      user: {
        name: 'Robert Smith',
        src: 'http://dev-175.ugroop.com.au/Content/TourImage/AcountPic_1004.png',
      },
      subject: 'sub1',
      content: 'this is a news feed1',
      publishDate: '01/May/2016',
    },
    {
      user: {
        name: 'Robert Smith',
        src: 'http://dev-175.ugroop.com.au/Content/TourImage/AcountPic_1004.png',
      },
      subject: 'sub2',
      content: 'this is a news 2',
      publishDate: '02/May/2016',
    },
    {
      user: {
        name: 'Robert Smith',
        src: 'http://dev-175.ugroop.com.au/Content/TourImage/AcountPic_1004.png',
      },
      subject: 'sub3',
      content: 'this is a news 3',
      publishDate: '03/May/2016',
    },
  ];
  it('should render newsfeed tour id', () => {
    const renderedComponent = shallow(
      <NewsFeedList tourId={tour1ID} />
    );
    expect(renderedComponent.find('#tourlist1011').length).toEqual(1);
  });
  it('should render 3 newsfeed img', () => {
    const renderedComponent = mount(
      <IntlProvider locale="en">
        <NewsFeedList tourId={tour1ID} items={tour1Newsfeed} />
      </IntlProvider>
    );
    expect(renderedComponent.find('img').length).toEqual(3);
  });

  it('should render 3 newsfeed content', () => {
    const renderedComponent = mount(
      <IntlProvider locale="en">
        <NewsFeedList tourId={tour1ID} items={tour1Newsfeed} />
      </IntlProvider>
    );
    expect(renderedComponent.find('p').length).toEqual(3);
  });

  it('should render newsfeed content correctly', () => {
    const renderedComponent = mount(
      <IntlProvider locale="en">
        <NewsFeedList tourId={tour1ID} items={tour1Newsfeed} />
      </IntlProvider>
    );
    expect(renderedComponent.find('p').nodes[0].innerHTML).toEqual('this is a news feed1');
  });
  it('should render newsfeed date correctly', () => {
    const renderedComponent = mount(
      <IntlProvider locale="en">
        <NewsFeedList tourId={tour1ID} items={tour1Newsfeed} />
      </IntlProvider>
    );
    expect(renderedComponent.find('.date').nodes[2].innerHTML).toEqual('03/May/2016');
  });
});


text:
macro(CTR_DEFINITION var)
  add_definitions(-D${var})
  set(CTR_BUILD_FLAGS "${CTR_BUILD_FLAGS}#ifndef ${var}\n#define ${var}\n#endif\n")
  set(CTR_INFO_FLAGS "${CTR_INFO_FLAGS} ${var}")
endmacro()

macro(CTR_OPTION option value)
  set(${option} ${value} CACHE INTERNAL "" FORCE)
endmacro()


text:
package org.apache.heron.eco;

import java.io.FileInputStream;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito;

import org.apache.heron.api.Config;
import org.apache.heron.api.HeronTopology;
import org.apache.heron.eco.definition.EcoTopologyDefinition;
import org.apache.heron.eco.parser.EcoParser;
import org.apache.heron.eco.submit.EcoSubmitter;
import org.apache.storm.generated.StormTopology;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(MockitoJUnitRunner.class)
public class EcoTest {

  @Mock
  private EcoParser mockEcoParser;
  @Mock
  private EcoSubmitter mockEcoSubmitter;
  @InjectMocks
  private Eco subject;

  @After
  public void ensureNoUnexpectedMockInteractions() {
    Mockito.verifyNoMoreInteractions(mockEcoParser,
        mockEcoSubmitter);
  }

  @Test
  public void testSubmit_StormTopologyType_BehavesAsExpected() throws Exception {
    FileInputStream mockStream = PowerMockito.mock(FileInputStream.class);
    FileInputStream mockPropsStream = PowerMockito.mock(FileInputStream.class);

    final String topologyName = "the name";
    EcoTopologyDefinition topologyDefinition = new EcoTopologyDefinition();
    topologyDefinition.setName(topologyName);

    when(mockEcoParser.parseFromInputStream(eq(mockStream), eq(mockPropsStream), eq(false)))
        .thenReturn(topologyDefinition);

    subject.submit(mockStream, mockPropsStream, false);

    verify(mockEcoParser).parseFromInputStream(same(mockStream),
        same(mockPropsStream), eq(false));

    verify(mockEcoSubmitter).submitStormTopology(any(String.class), any(Config.class),
        any(StormTopology.class));
  }

  @Test
  public void testSubmit_HeronTopologyType_BehavesAsExpected() throws Exception {
    FileInputStream mockStream = PowerMockito.mock(FileInputStream.class);
    FileInputStream mockPropsStream = PowerMockito.mock(FileInputStream.class);

    final String topologyName = "the name";
    EcoTopologyDefinition topologyDefinition = new EcoTopologyDefinition();
    topologyDefinition.setName(topologyName);
    topologyDefinition.setType("heron");

    when(mockEcoParser.parseFromInputStream(eq(mockStream), eq(mockPropsStream), eq(false)))
        .thenReturn(topologyDefinition);

    subject.submit(mockStream, mockPropsStream, false);

    verify(mockEcoParser).parseFromInputStream(same(mockStream),
        same(mockPropsStream), eq(false));

    verify(mockEcoSubmitter).submitHeronTopology(any(String.class), any(Config.class),
        any(HeronTopology.class));
  }
}


text:
package libgolb

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
)

type LogFile struct {
	Folder string
}

type HttpServer struct {
	Hostname string
	Port     string
}

type RedisServer struct {
	Hostname string
	Port     string
	Database int
}

type Configuration struct {
	Name        string
	Log         LogFile
	Server      HttpServer
	BackServers []string
	LogColor    bool
	TTL         uint
	TimeOut     uint
	IpHashLevel uint
	RedisLB     RedisServer
}

var RoundRobin int
var NumberBack int
var Conf Configuration

func ConfLoad(pathconf string) {
	contents, err := ioutil.ReadFile(pathconf)
	if err != nil {
		log.Fatal("The configuration file (" + pathconf + ") doesn't exist.")
		os.Exit(1)
	}
	err = json.Unmarshal([]byte(contents), &Conf)
	if err != nil {
		log.Fatal("The syntax of the configuration file (" + pathconf + ") is incorrect.")
		os.Exit(1)
	}
	RoundRobin = 0
	NumberBack = len(Conf.BackServers)
	if NumberBack == 0 {
		log.Fatal("No Backend Server !!!")
		os.Exit(1)
	}
	if Conf.IpHashLevel < 0 || Conf.IpHashLevel > 5 {
		log.Fatal("Bad Ip Hash Level !!!")
		os.Exit(1)
	}
}


text:
class FunctionBuilderWrapper

  include BuilderWrapper
  include GlobalBuilderWrapper

  def initialize(arguments, return_type, name = "default", host_module = nil, options = {})
    @default_module = host_module
    @current_function = get_function(name, arguments, return_type, options)
    builder.position_at_end(get_block(@current_function, :entry))
    yield self if block_given?
  end

end


text:
package org.apache.derby.impl.drda;

import java.io.InputStream;
import java.io.Reader;
import java.io.OutputStreamWriter;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.derby.iapi.services.sanity.SanityManager;

/**
 *
 * ReEncodedInputStream passes
 * stream from Reader, which is stream of decoded style,
 * to user of this subclass of InputStream, which is stream of encoded style.
 *
 * The encoding of stream passed to user is limited to UTF8.
 *
 * This class will be used to pass stream, which is served as a Reader,
 * as a InputStream of a arbitrary encoding.
 *
 */
public class ReEncodedInputStream extends InputStream {

    private static final int BUFFERED_CHAR_LEN = 1024;

    private Reader reader_;
    private char[] decodedBuffer_;

    private OutputStreamWriter encodedStreamWriter_;
    private PublicBufferOutputStream encodedOutputStream_;

    private ByteArrayInputStream encodedInputStream_;

    public ReEncodedInputStream(Reader reader)
	throws IOException {

	reader_ = reader;
	decodedBuffer_ = new char[BUFFERED_CHAR_LEN];

	encodedOutputStream_ = new PublicBufferOutputStream( BUFFERED_CHAR_LEN * 3 );
	encodedStreamWriter_ = new OutputStreamWriter(encodedOutputStream_,"UTF8");

	encodedInputStream_ = reEncode(reader_);

    }

    private ByteArrayInputStream reEncode(Reader reader)
	throws IOException
    {

		int count;
		do{
			count = reader.read(decodedBuffer_, 0, BUFFERED_CHAR_LEN);

		}while(count == 0);

		if(count < 0)
			return null;

	encodedOutputStream_.reset();
	encodedStreamWriter_.write(decodedBuffer_,0,count);
	encodedStreamWriter_.flush();

	int encodedLength = encodedOutputStream_.size();

	return new ByteArrayInputStream(encodedOutputStream_.getBuffer(),
					0,
					encodedLength);
    }

    public int available()
	throws IOException {

	if(encodedInputStream_ == null){
	    return 0;
	}

	return encodedInputStream_.available();

    }

    public void close()
	throws IOException {

	if(encodedInputStream_ != null ){
	    encodedInputStream_.close();
	    encodedInputStream_ = null;
	}

	if(reader_ != null ){
	    reader_.close();
	    reader_ = null;
	}

	if(encodedStreamWriter_ != null){
	    encodedStreamWriter_.close();
	    encodedStreamWriter_ = null;
	}

    }

    public int read()
	throws IOException {

	if(encodedInputStream_ == null){
	    return -1;
	}

	int c = encodedInputStream_.read();

	if(c > -1){
	    return c;

	}else{
	    encodedInputStream_ = reEncode(reader_);

	    if(encodedInputStream_ == null){
		return -1;
	    }

	    return encodedInputStream_.read();

	}

    }

    protected void finalize() throws IOException {
	close();
    }

    private static class PublicBufferOutputStream extends ByteArrayOutputStream{

	PublicBufferOutputStream(int size){
	    super(size);
	}

	public byte[] getBuffer(){
	    return buf;
	}

    }

}


text:
'use strict';

app.controller('employeesController', [
    '$scope', 'employeesService', '$mdToast', 'messageService', '$mdDialog', '$state', function ($scope, employeesService, $mdToast, messageService, $mdDialog, $state) {

        //COMMON----------------------------------------------
        //options for queries to API and pagination
        $scope.query = {
            order: 'employeeLastname',
            limit: 10,
            page: 1,
            label: {
                of: "из",
                page: 'Текущая',
                rowsPerPage: 'Кол-во на странице'
            },
            filter: ''  //it would be better to refresh the list when filter has 3 chars at least.
        };

        //returns date from string
        $scope.getDate = function (date) {
            var t = new Date(date);
            return new Date(t.getFullYear(), t.getMonth(), t.getDate(), 3);
        }

        //----------------------------------------------------

        //EMPLOYEES-------------------------------------------

        //gets employees with pagination
        $scope.getEmployees = function () {
            $scope.promise = employeesService.employees.getEmployees($scope.query).then(function (response) {
                $scope.employees = response.data;
                $scope.total = response.headers('X-Total-Count');
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //employees list
        $scope.getEmployees();

        //refresh employees list
        $scope.refreshEmployees = function () {
            $scope.promise = $scope.getEmployees();
        }

        //returns $promise with employee by id
        $scope.getEmployeeById = function (id) {
            return employeesService.employees.getEmployeeById(id);
        };

        //deletes the specified employee
        var _deleteEmployee = function (id) {
            $scope.promise = employeesService.employees.deleteEmployeeById(id).then(function (response) {
                $scope.getEmployees();//refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      'Информация о сотруднике была удалена.' +
                                    '
' +
                                '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //opens the dialog window with detailed information about specified employee
        $scope.showDetails = function (ev, id) {
            $scope.getEmployeeById(id).then(function (response) {

                //TODO: set JSON parser for data - date is parsed not correct
                var employee = response.data;
                employee.birthDate = new Date(employee.birthDate);

                employeesService.employees.setActualEmployee(employee);

                $state.go('details');
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        };

        //shows the window with form for adding new employee
        $scope.showAddingView = function (ev) {
            $mdDialog.show({
                controller: 'addEmployeeController',
                templateUrl: 'app/views/addEmployeeView.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true
            }).then(function (answer) {
                $scope.getEmployees();
                console.log('new employee has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        }

        //shows confirmation of employee deletion
        $scope.confirmDeleting = function (ev, id) {
            var confirm = $mdDialog.confirm()
                    .title('Удаление')
                    .textContent('Вы уверены, что хотите удалить информацию о сотруднике? \nВосстановить утерянную информацию будет невозможно!')
                    .ariaLabel('Deleting')
                    .targetEvent(ev)
                    .ok('Удалить')
                    .cancel('Отмена');
            $mdDialog.show(confirm).then(function () {
                //delete the employee
                _deleteEmployee(id);
            }, function () {
                //cancel
            });
        }

        //----------------------------------------------------

    }]).controller('toastController', ['$scope', '$mdDialog', 'messageService', '$mdToast', function ($scope, $mdDialog, messageService, $mdToast) {

        var isDlgOpen = false;

        $scope.closeToast = function () {
            if (isDlgOpen) return;

            $mdToast
                .hide()
                .then(function () {
                    isDlgOpen = false;
                });
        };

        $scope.openMoreInfo = function (e) {
            if (isDlgOpen) return;
            isDlgOpen = true;

            $mdDialog
                .show($mdDialog
                    .alert()
                    .title('Ошибка! ' + messageService.errors.getError().errorTitle)
                    .textContent(messageService.errors.getError().errorText)
                    .ariaLabel('More info')
                    .ok('OK')
                    .targetEvent(e)
                )
                .then(function () {
                    isDlgOpen = false;
                });
        };

    }]).controller('detailsController', ['$scope', '$mdDialog', 'employeesService', 'messageService', '$timeout', '$mdToast', '$state', function ($scope, $mdDialog, employeesService, messageService, $timeout, $mdToast, $state) {

//COMMON----------------------------------------------

        $scope.maxBirthDate = employeesService.common.maxBirthDate;
        $scope.minBirthDate = employeesService.common.minBirthDate;
        $scope.minRetirementDate = '';

        $scope.personalInfoTabConfig = function() {
            $scope.promise = employeesService.activityItems.mesAchievements.getMesAchievements().then(function (response) {//calculating constraint for retirement date
                $scope.mesAchievements = response.data;
                if ($scope.mesAchievements && $scope.mesAchievements.length > 0) {
                    $scope.minRetirementDate = new Date($scope.mesAchievements[0].startDate);
                    $scope.mesAchievements.forEach(function (item) {
                        var date = null;
                        if (item.finishDate)
                            date = new Date(item.finishDate);
                        else
                            date = new Date(Date.now());

                        if (date > $scope.minRetirementDate) {
                            $scope.minRetirementDate = date; //maybe finish date should be here.
                        }
                    });
                }

            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        $scope.hide = function () {
            $mdDialog.hide();
        };

        $scope.cancel = function () {
            $mdDialog.cancel();
        };

        //returns date from string
        $scope.getDate = function (date) {
            if (date) {
                var t = new Date(date);
                return new Date(t.getFullYear(), t.getMonth(), t.getDate(), 3);
            } else
                return null;
        }

        //selected employee
        $scope.employee = employeesService.employees.getActualEmployee();
        //selected for changing
        $scope.changeable = employeesService.common.getClone($scope.employee);

        $scope.uploadFile = function (input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    //Sets the Old Image to new New Image
                    document.getElementById('photo-id').setAttribute('src', e.target.result);

                    //Create a canvas and draw image on Client Side to get the byte[] equivalent
                    var canvas = document.createElement("canvas");
                    var imageElement = document.createElement("img");

                    imageElement.setAttribute('src', e.target.result);
                    canvas.width = imageElement.width;
                    canvas.height = imageElement.height;
                    var context = canvas.getContext("2d");
                    context.drawImage(imageElement, 0, 0);
                    var base64Image = canvas.toDataURL("image/jpeg");

                    //Removes the Data Type Prefix
                    //And set the view model to the new value
                    $scope.changeable.employeePhoto = base64Image.replace(/data:image\/jpeg;base64,/g, '');
                }

                //Renders Image on Page
                reader.readAsDataURL(input.files[0]);
            }
        }

        $scope.upload = function () {
            angular.element(document.getElementById('photo-id')).click();
        };

        //reset all changes
        $scope.resetChanges = function () {
            $scope.changeable = employeesService.common.getClone($scope.employee);
        }

        $scope.isPensioner = function () {
            if ($scope.employee.retirementDate) return true;
            return false;
        }

        //----------------------------------------------------

        //HANDLERS--------------------------------------------

        //shows the window for adding new mes achievement
        $scope.showAddMesView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.mesAchievements.selectedMesAchievement = null;
            else if (mode === 'edit') {
                employeesService.activityItems.mesAchievements.selectedMesAchievement = employeesService.common.getClone(item);
                employeesService.activityItems.mesAchievements.selectedMesAchievement.startDate = $scope.getDate(item.startDate);
                employeesService.activityItems.mesAchievements.selectedMesAchievement.finishDate = $scope.getDate(item.finishDate);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addMesView.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getMesAchievements(); //refresh the list
                console.log('new achievement has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        $scope.showAddMilitaryView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.military.selectedMilitary = null;
            else if (mode === 'edit') {
                employeesService.activityItems.military.selectedMilitary = employeesService.common.getClone(item);
                employeesService.activityItems.military.selectedMilitary.startDate = $scope.getDate(item.startDate);
                employeesService.activityItems.military.selectedMilitary.finishDate = $scope.getDate(item.finishDate);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addMilitaryView.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getMilitary(); //refresh the list
                console.log('new military has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        $scope.showAddDisciplineItemView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.disciplineItems.selectedDisciplineItem = null;
            else if (mode === 'edit') {
                employeesService.activityItems.disciplineItems.selectedDisciplineItem = employeesService.common.getClone(item);
                employeesService.activityItems.disciplineItems.selectedDisciplineItem.date = $scope.getDate(item.date);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addDisciplineItem.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getDisciplineItems(); //refresh the list
                console.log('new discipline item has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        $scope.showAddWorkView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.works.selectedWork = null;
            else if (mode === 'edit') {
                employeesService.activityItems.works.selectedWork = employeesService.common.getClone(item);
                employeesService.activityItems.works.selectedWork.startDate = $scope.getDate(item.startDate);
                employeesService.activityItems.works.selectedWork.finishDate = $scope.getDate(item.finishDate);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addWorkView.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getWorks(); //refresh the list
                console.log('new work has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        $scope.showAddOutFromOfficeView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem = null;
            else if (mode === 'edit') {
                employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem = employeesService.common.getClone(item);
                employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem.startDate = $scope.getDate(item.startDate);
                employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem.finishDate = $scope.getDate(item.finishDate);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addOutFromOfficeItem.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getOutFromOffice(); //refresh the list
                console.log('new "out from office" item has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        $scope.showAddSertificationView = function (ev, mode, item) {
            if (mode === 'add')
                employeesService.activityItems.sertification.selectedSertification = null;
            else if (mode === 'edit') {
                employeesService.activityItems.sertification.selectedSertification = employeesService.common.getClone(item);
                employeesService.activityItems.sertification.selectedSertification.dueDate = $scope.getDate(item.dueDate);
            }

            $mdDialog.show({
                controller: 'addEmployeeItemsController',
                templateUrl: 'app/views/addSertificationView.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                locals: {
                    mode: mode
                }
            }).then(function (answer) {
                $scope.getSertifications(); //refresh the list
                console.log('new sertification item has been added.');
            }, function () {
                console.log('adding view has been closed.');
            });
        };

        //shows confirmation for transferring employee
        $scope.askForTransfer = function (type, ev) {
            var confirm = {};
            if (type === 'P') {
                confirm = {
                    controller: 'transferController',
                    templateUrl: 'app/views/retiredTransferView.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    clickOutsideToClose: true
                };
                $mdDialog.show(confirm).then(function (response) {
                    console.log('');
                    //success
                }, function (error) {
                    //cancel
                });
            } else if (type === 'F') {
                confirm = {
                    controller: 'transferController',
                    templateUrl: 'app/views/dismissalView.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    clickOutsideToClose: true
                }
                $mdDialog.show(confirm).then(function () {
                    //transfer to fired
                }, function () {
                    //cancel
                });
            }
        };

        //confirmation deleting
        $scope.confirmDeleting = function (ev, id, type) { //type: W - works; M - military; A - achievements; D - discipline items; O- 'out from office' items

            var confirm = $mdDialog.confirm()
                .title('Удаление')
                .textContent('Вы уверены, что хотите удалить запись? \nВосстановить утерянную информацию будет невозможно!')
                .ariaLabel('Deleting')
                .targetEvent(ev)
                .ok('Удалить')
                .cancel('Отмена');
            $mdDialog.show(confirm).then(function () {
                //delete the item
                switch (type) {
                    case "W":   //works
                        _deleteWork(id);
                        break;
                    case "M":   //military
                        _deleteMilitary(id);
                        break;
                    case "A":   //MES achievements
                        _deleteMesAchievement(id);
                        break;
                    case "D":   //discipline
                        _deleteDisciplineItem(id);
                    case "O":   //out from office
                        _deleteOutFromOfficeItem(id);
                    case "S":   //sertification
                        _deleteSertification(id);
                    default:
                        break;
                }
            }, function () {
                //cancel
            });
        }

        //save specified changes for the employee
        $scope.saveChanges = function () {
            //save the changes
            employeesService.employees.saveChanges($scope.changeable).then(function (response) {
                if ($scope.isPensioner())
                    $state.go('retirees');
                else
                    $state.go('employees');

                $mdToast.show({
                    hideDelay: 5000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Изменения приняты.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        $scope.getSeniority = function () {
            $scope.promise = employeesService.employees.getSeniorityById($scope.employee.id).then(function (response) {
                $scope.seniority = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }
        //----------------------------------------------------

        //OUT FROM OFFICE-------------------------------------

        $scope.outFromOfficeItems = [];
        $scope.outFromOfficeType = 'S';

        var _deleteOutFromOfficeItem = function (id) {
            $scope.promise = employeesService.activityItems.outFromOffice.deleteOutFromOffice(id).then(function (response) {
                $scope.getOutFromOffice(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        $scope.getOutFromOffice = function () {
            $scope.promise = employeesService.activityItems.outFromOffice.getOutFromOffice($scope.employee.id).then(function (response) { //success
                $scope.outFromOfficeItems = response.data.filter(function (item) { return item.cause === $scope.outFromOfficeType });
                employeesService.activityItems.outFromOffice.actualOutFromOfficeType = $scope.outFromOfficeType;
            }, function (data) { //if error
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //DISCIPLINE------------------------------------------

        $scope.disciplineItems = [];
        $scope.discType = 'G';  //gratitudes by default

        var _deleteDisciplineItem = function (id) {
            $scope.promise = employeesService.activityItems.disciplineItems.deleteDisciplineItem(id).then(function (response) {
                $scope.getDisciplineItems(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        $scope.getDisciplineItems = function () {
            $scope.promise = employeesService.activityItems.disciplineItems.getDisciplineItems($scope.employee.id).then(function (response) { //success
                $scope.disciplineItems = response.data.filter(function (item) { return item.itemType === $scope.discType });
                employeesService.activityItems.disciplineItems.actualDisciplineItemsType = $scope.discType;
            }, function (data) { //if error
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //MES-------------------------------------------------
        $scope.mesAchievements = [];

        //returns MES achievements for employee
        $scope.getMesAchievements = function () {
            $scope.promise = employeesService.activityItems.mesAchievements.getMesAchievements().then(function (response) {
                $scope.mesAchievements = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //deletes mes achievemnt by id
        var _deleteMesAchievement = function (id) {
            $scope.promise = employeesService.activityItems.mesAchievements.deleteMesAchievement(id).then(function (response) {
                $scope.getMesAchievements(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //WORKS-----------------------------------------------
        $scope.works = [];

        //returns works for employee
        $scope.getWorks = function () {
            $scope.promise = employeesService.activityItems.works.getWorks().then(function (response) {
                $scope.works = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //deletes work by id
        var _deleteWork = function (id) {
            $scope.promise = employeesService.activityItems.works.deleteWork(id).then(function (response) {
                $scope.getWorks(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //MILITARY--------------------------------------------
        $scope.military = [];

        //returns military for employee
        $scope.getMilitary = function () {
            $scope.promise = employeesService.activityItems.military.getMilitary().then(function (response) {
                $scope.military = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //deletes military by id
        var _deleteMilitary = function (id) {
            $scope.promise = employeesService.activityItems.military.deleteMilitary(id).then(function (response) {
                $scope.getMilitary(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //SERTIFICATION---------------------------------------

        $scope.sertifications = [];

        //returns sertifications for employee
        $scope.getSertifications = function () {
            $scope.promise = employeesService.activityItems.sertification.getSertifications(employeesService.employees.actualEmployee.id).then(function (response) {
                $scope.sertifications = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //deletes sertifications by id
        var _deleteSertification = function (id) {
            $scope.promise = employeesService.activityItems.sertification.deleteSertification(id).then(function (response) {
                $scope.getSertifications(); //refresh
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                        '
' +
                        'Запись была успешно удалена.' +
                        '
' +
                        '</md-toast>'
                });
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

}]).controller('addEmployeeItemsController', ['$scope', '$mdDialog', 'employeesService', 'messageService', '$mdToast', 'mode', function ($scope, $mdDialog, employeesService, messageService, $mdToast, mode) {

        //COMMON----------------------------------------------
        $scope.hide = function () {
            $mdDialog.hide();
        };

        $scope.cancel = function () {
            $mdDialog.cancel();
        };

        $scope.dtpckrOnFocus = function (item, field) {//when ditetimepicker is focused and the model field is undefined
            if (!item[field])
                item[field] = new Date();
        }

        $scope.minDate = employeesService.activityItems.constants.minDate;
        $scope.maxDate = employeesService.activityItems.constants.maxDate;
        $scope.mode = mode;

        //posts init
        $scope.getPosts = function (serviceId) {
            employeesService.activityItems.getPosts(serviceId).then(function (response) {
                $scope.posts = response.data;
            }, function (data) {
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //ranks init
        employeesService.activityItems.getRanks().then(function (response) {
            $scope.ranks = response.data;
        }, function (data) {
            messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
            $mdToast.show(messageService.errors.errorViewConfig);
        });

        //locations init
        employeesService.activityItems.getLocations().then(function (response) {
            $scope.locations = response.data;
        }, function (data) {
            messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
            $mdToast.show(messageService.errors.errorViewConfig);
        });

        //services init
        employeesService.activityItems.getServices().then(function (response) {
            $scope.services = response.data;
        }, function (data) {
            messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
            $mdToast.show(messageService.errors.errorViewConfig);
        });
        //----------------------------------------------------

        //OUT FROM OFFICE-------------------------------------

        $scope.outFromOffice = employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem == null
            ? { employeeId: employeesService.employees.getActualEmployee().id, cause: employeesService.activityItems.outFromOffice.actualOutFromOfficeType }
            : employeesService.activityItems.outFromOffice.selectedOutFromOfficeItem;

        $scope.saveNewOutFromOffice = function () {
            $scope.promise = employeesService.activityItems.outFromOffice.saveOutFromOffice($scope.outFromOffice).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

        //MES-------------------------------------------------
        $scope.mesAchItem = employeesService.activityItems.mesAchievements.selectedMesAchievement == null
            ? { employeeId: employeesService.employees.getActualEmployee().id }
            : employeesService.activityItems.mesAchievements.selectedMesAchievement;

        if (mode === 'edit') $scope.getPosts($scope.mesAchItem.serviceId);

        //saves new mes achievement
        $scope.saveNewMesAchievement = function () {

            //if strat date is bigger than "today"
            if ($scope.mesAchItem.startDate.withoutTime().startDate > $scope.maxDate.withoutTime()) {
                messageService.errors.setError({ errorText: 'Дата указана неверно: проверьте диапазон дат.', errorTitle: "" });
                $mdToast.show(messageService.errors.errorViewConfig);
                return;
            }

            $scope.promise = employeesService.activityItems.mesAchievements.saveMesAchievement($scope.mesAchItem).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }
        //----------------------------------------------------

        //MILITARY--------------------------------------------
        $scope.military = employeesService.activityItems.military.selectedMilitary == null
            ? { employeeId: employeesService.employees.getActualEmployee().id }
            : employeesService.activityItems.military.selectedMilitary;

        //saves new military
        $scope.saveNewMilitary = function () {
            $scope.promise = employeesService.activityItems.military.saveMilitary($scope.military).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }
        //----------------------------------------------------

        //WORK------------------------------------------------
        $scope.work = employeesService.activityItems.works.selectedWork == null
            ? { employeeId: employeesService.employees.getActualEmployee().id }
            : employeesService.activityItems.works.selectedWork;

        //saves new work
        $scope.saveNewWork = function () {
            $scope.promise = employeesService.activityItems.works.saveWork($scope.work).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }
        //----------------------------------------------------

        //DISCIPLINE------------------------------------------
        $scope.newDisciplineItem = employeesService.activityItems.disciplineItems.selectedDisciplineItem == null
            ? { employeeId: employeesService.employees.getActualEmployee().id, itemType: employeesService.activityItems.disciplineItems.actualDisciplineItemsType }
            : employeesService.activityItems.disciplineItems.selectedDisciplineItem;

        //saves new discipline item
        $scope.saveNewDisciplineItem = function () {
            $scope.promise = employeesService.activityItems.disciplineItems.saveNewDisciplineItem($scope.newDisciplineItem).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }
        //----------------------------------------------------

        //SERTIFICATION---------------------------------------
        $scope.sertification = employeesService.activityItems.sertification.selectedSertification == null
            ? { employeeId: employeesService.employees.getActualEmployee().id }
            : employeesService.activityItems.sertification.selectedSertification;

        //saves new sertification item
        $scope.saveNewSertification = function () {
            $scope.promise = employeesService.activityItems.sertification.saveSertification($scope.sertification).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      (mode === 'edit' ? 'Запись успешно изменена.' : 'Запись успешно добавлена.') +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main controller to refresh or do not the list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        }

        //----------------------------------------------------

}]).controller('addEmployeeController', ['$scope', '$mdDialog', 'employeesService', 'messageService', '$mdToast', function ($scope, $mdDialog, employeesService, messageService, $mdToast) {

        $scope.hide = function () {
            $mdDialog.hide();
        };

        $scope.cancel = function () {
            $mdDialog.cancel();
        };

        $scope.answer = function (answer) {
            $mdDialog.hide(answer);
        };

        $scope.maxBirthDate = employeesService.common.maxBirthDate;
        $scope.minBirthDate = employeesService.common.minBirthDate;

        var employee = {    //testing
            employeeLastname: "Тестовый",
            employeeFirstname: "Тест",
            employeeMiddlename: "Тестович",
            birthDate: new Date(1989, 11, 1),
            description: 'тестовое описание',
            detailedAddress: 'тестовый точный адрес',
            city: 'тестовый город',
            area: 'тестовая область',
            zipCode: '123456',
            passportNumber: 'HB1234567',
            passportOrganization: 'тестовая организация',
            firstPhone: 'первый номер',
            secondPhone: 'второй номер'
        }

        $scope.newEmployee = employee;

        $scope.saveNewEmployee = function () {
            $scope.promise = employeesService.employees.addNewEmployee($scope.newEmployee).then(function (response) {
                $mdToast.show({
                    hideDelay: 3000,
                    position: 'top right',
                    controller: 'toastController',
                    template: '<md-toast class="md-toast-success">' +
                                    '
' +
                                      'Сотрудник успешно зарегистрирован.' +
                                    '
' +
                                '</md-toast>'
                });
                $mdDialog.hide('save'); //throw the 'answer' to the main employee controller to refresh or do not the employee list
            }, function (data) {
                $mdDialog.hide('cancel');
                messageService.errors.setError({ errorText: data.data, errorTitle: 'Статус - ' + data.status + ': ' + data.statusText });
                $mdToast.show(messageService.errors.errorViewConfig);
            });
        };
    }]);


text:
require 'fog/openstack/models/model'

module Fog
  module Identity
    class OpenStack
      class V2
        class Ec2Credential < Fog::OpenStack::Model
          identity :access, :aliases => 'access_key'

          attribute :secret, :aliases => 'secret_key'
          attribute :tenant_id
          attribute :user_id

          def destroy
            requires :access
            requires :user_id
            service.delete_ec2_credential user_id, access
            true
          end

          def save
            raise Fog::Errors::Error, 'Existing credentials cannot be altered' if access

            self.user_id ||= user.id
            self.tenant_id ||= user.tenant_id

            requires :user_id, :tenant_id

            data = service.create_ec2_credential user_id, tenant_id

            merge_attributes(data.body['credential'])

            true
          end
        end
      end
    end
  end
end


text:
from copy import copy
from selection.distributions.discrete_family import discrete_family
import numpy as np
from scipy.stats import norm as ndist
import rpy2.robjects as rpy
import rpy2.robjects.numpy2ri
import matplotlib.pyplot as plt
rpy.r('library(splines)')

def simulate(n=100):

    # description of statistical problem

    truth = np.array([4. , -4]) / np.sqrt(n)

    data = np.random.standard_normal((n, 2)) + np.multiply.outer(np.ones(n), truth)

    def sufficient_stat(data):
        return np.mean(data, 0)

    S = sufficient_stat(data)

    # randomization mechanism

    class normal_sampler(object):

        def __init__(self, center, covariance):
            (self.center,
             self.covariance) = (np.asarray(center),
                                 np.asarray(covariance))
            self.cholT = np.linalg.cholesky(self.covariance).T
            self.shape = self.center.shape

        def __call__(self, scale=1., size=None):

            if type(size) == type(1):
                size = (size,)
            size = size or (1,)
            if self.shape == ():
                _shape = (1,)
            else:
                _shape = self.shape
            return scale * np.squeeze(np.random.standard_normal(size + _shape).dot(self.cholT)) + self.center

        def __copy__(self):
            return normal_sampler(self.center.copy(),
                                  self.covariance.copy())

    observed_sampler = normal_sampler(S, 1/n * np.identity(2))

    def algo_constructor():

        def myalgo(sampler):
            min_success = 1
            ntries = 3
            success = 0
            for _ in range(ntries):
                noisyS = sampler(scale=0.5)
                success += noisyS.sum() > 0.2 / np.sqrt(n)
            return success >= min_success
        return myalgo

    # run selection algorithm

    algo_instance = algo_constructor()
    observed_outcome = algo_instance(observed_sampler)

    # find the target, based on the observed outcome

    def compute_target(observed_outcome, data):
        if observed_outcome: # target is truth[0]
            observed_target, target_cov, cross_cov = sufficient_stat(data)[0], 1/n * np.identity(1), np.array([1., 0.]).reshape((2,1)) / n
        else:
            observed_target, target_cov, cross_cov = sufficient_stat(data)[1], 1/n * np.identity(1), np.array([0., 1.]).reshape((2,1)) / n
        return observed_target, target_cov, cross_cov

    observed_target, target_cov, cross_cov = compute_target(observed_outcome, data)
    direction = cross_cov.dot(np.linalg.inv(target_cov))

    if observed_outcome:
        true_target = truth[0] # natural parameter
    else:
        true_target = truth[1] # natural parameter

    def learning_proposal(n=100):
        scale = np.random.choice([0.5, 1, 1.5, 2], 1)
        return np.random.standard_normal() * scale / np.sqrt(n) + observed_target

    def logit_fit(T, Y):
        rpy2.robjects.numpy2ri.activate()
        rpy.r.assign('T', T)
        rpy.r.assign('Y', Y.astype(np.int))
        rpy.r('''
        Y = as.numeric(Y)
        T = as.numeric(T)
        M = glm(Y ~ ns(T, 10), family=binomial(link='logit'))
        fitfn = function(t) { predict(M, newdata=data.frame(T=t), type='link') }
        ''')
        rpy2.robjects.numpy2ri.deactivate()

        def fitfn(t):
            rpy2.robjects.numpy2ri.activate()
            fitfn_r = rpy.r('fitfn')
            val = fitfn_r(t)
            rpy2.robjects.numpy2ri.deactivate()
            return np.exp(val) / (1 + np.exp(val))

        return fitfn

    def probit_fit(T, Y):
        rpy2.robjects.numpy2ri.activate()
        rpy.r.assign('T', T)
        rpy.r.assign('Y', Y.astype(np.int))
        rpy.r('''
        Y = as.numeric(Y)
        T = as.numeric(T)
        M = glm(Y ~ ns(T, 10), family=binomial(link='probit'))
        fitfn = function(t) { predict(M, newdata=data.frame(T=t), type='link') }
        ''')
        rpy2.robjects.numpy2ri.deactivate()

        def fitfn(t):
            rpy2.robjects.numpy2ri.activate()
            fitfn_r = rpy.r('fitfn')
            val = fitfn_r(t)
            rpy2.robjects.numpy2ri.deactivate()
            return ndist.cdf(val)

        return fitfn

    def learn_weights(algorithm,
                      observed_sampler,
                      learning_proposal,
                      fit_probability,
                      B=15000):

        S = selection_stat = observed_sampler.center
        new_sampler = copy(observed_sampler)

        learning_sample = []
        for _ in range(B):
             T = learning_proposal()      # a guess at informative distribution for learning what we want
             new_sampler = copy(observed_sampler)
             new_sampler.center = S + direction.dot(T - observed_target)
             Y = algorithm(new_sampler) == observed_outcome
             learning_sample.append((T[0], Y))
        learning_sample = np.array(learning_sample)
        T, Y = learning_sample.T
        conditional_law = fit_probability(T, Y)
        return conditional_law

    weight_fn = learn_weights(algo_instance, observed_sampler, learning_proposal, probit_fit)

    # let's form the pivot

    target_val = np.linspace(-1, 1, 1001)
    weight_val = weight_fn(target_val)

    weight_val *= ndist.pdf(target_val / np.sqrt(target_cov[0,0]))

    if observed_outcome:
        plt.plot(target_val, np.log(weight_val), 'k')
    else:
        plt.plot(target_val, np.log(weight_val), 'r')

    # for p == 1 targets this is what we do -- have some code for multidimensional too

    print('(true, observed):', true_target, observed_target)
    exp_family = discrete_family(target_val, weight_val)
    pivot = exp_family.cdf(true_target / target_cov[0, 0], x=observed_target)
    interval = exp_family.equal_tailed_interval(observed_target, alpha=0.1)

    return (pivot,
            (interval[0] * target_cov[0, 0] < true_target) * (interval[1] * target_cov[0, 0] > true_target),
            (interval[1] - interval[0]) * target_cov[0, 0])

if __name__ == "__main__":
    import statsmodels.api as sm
    n = 100
    U = np.linspace(0, 1, 101)
    P = []
    plt.clf()
    coverage = 0
    for i in range(10):
        p, cover, _ = simulate(n=n)
        coverage += cover
        P.append(p)
        print(np.mean(P), np.std(P), coverage / (i+1))

    plt.gca().set_ylim([-5,0])
    plt.show()

    coverage = 0
    L = []
    for i in range(100):
        p, cover, l = simulate()
        L.append(l)
        coverage += cover
        P.append(p)
        print(np.mean(P), np.std(P), np.mean(L) / (2 * 1.65 / np.sqrt(n)), coverage / (i+1))

    plt.clf()
    plt.plot(U, sm.distributions.ECDF(P)(U), 'r', linewidth=3)
    plt.plot([0,1], [0,1], 'k--', linewidth=2)
    plt.show()


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

package de.undercouch.citeproc.helper.json;

/**
 * A {@link JsonBuilderFactory} that always builds {@link StringJsonBuilder}s
 * @author Michel Kraemer
 */
public class StringJsonBuilderFactory implements JsonBuilderFactory {
	@Override
	public JsonBuilder createJsonBuilder() {
		return new StringJsonBuilder(this);
	}
}


text:
package core

import (
	"github.com/apex/log"
	"github.com/tidwall/gjson"
	"strconv"
	"strings"
	"time"
)

// Task reprents a parsed task
type Task struct {
	Name       string
	Desc       string
	Cmd        string
	Before     string
	After      string
	Error      string
	Shell      string
	Retry      int
	RetryDelay time.Duration
}

const defaultDelay = time.Duration(1) * time.Second

func loadTaskJSON(name string, json gjson.Result) Task {
	t := Task{Retry: 0, RetryDelay: defaultDelay}
	t.Name = name

	if j := json.Get("desc"); j.Exists() {
		t.Desc = strings.TrimSpace(j.String())
	}
	if j := json.Get("cmd"); j.Exists() {
		t.Cmd = strings.TrimSpace(j.String())
	}
	if j := json.Get("before"); j.Exists() {
		t.Before = strings.TrimSpace(j.String())
	}
	if j := json.Get("after"); j.Exists() {
		t.After = strings.TrimSpace(j.String())
	}
	if j := json.Get("error"); j.Exists() {
		t.Error = strings.TrimSpace(j.String())
	}
	if j := json.Get("shell"); j.Exists() {
		t.Shell = strings.TrimSpace(j.String())
	}
	if j := json.Get("retry"); j.Exists() {
		if retry, err := strconv.Atoi(strings.TrimSpace(j.String())); err != nil {
			log.WithError(err).Warnf("invalid retry in task %s", name)
		} else {
			t.Retry = retry
		}
	}
	if j := json.Get("retry_delay"); j.Exists() {
		if delay, err := time.ParseDuration(strings.TrimSpace(j.String())); err != nil {
			log.WithError(err).Warnf("invalid retry_delay in task %s", name)
		} else {
			t.RetryDelay = delay
		}
	}
	return t
}

func mixinTask(taskName string, child Task, parent Task) Task {
	child.Name = taskName
	if len(child.Cmd) == 0 {
		child.Cmd = parent.Cmd
	}
	if len(child.Desc) == 0 {
		child.Desc = parent.Desc
	}
	child.Before = strings.TrimSpace(child.Before + "\n" + parent.Before)
	child.After = strings.TrimSpace(child.After + "\n" + parent.After)
	child.Error = strings.TrimSpace(child.Error + "\n" + parent.Error)
	return child
}


text:
// Thanks to: https://coussej.github.io/2016/02/16/Handling-JSONB-in-Go-Structs/

package igor

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
)

// JSON is the Go type used to handle JSON PostgreSQL type
type JSON map[string]interface{}

// Value implements driver.Valuer interface
func (js JSON) Value() (driver.Value, error) {
	return json.Marshal(js)
}

// Scan implements sql.Scanner interface
func (js *JSON) Scan(src interface{}) error {
	if src == nil {
		*js = make(JSON)
		return nil
	}
	source, ok := src.([]byte)
	if !ok {
		return errors.New("Type assertion .([]byte) failed.")
	}

	if err := json.Unmarshal(source, js); err != nil {
		return err
	}
	return nil
}


text:
package kanzhihu.android.utils;

import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import kanzhihu.android.App;
import kanzhihu.android.AppConstant;
import kanzhihu.android.R;

/**
 * Created by Jiahui.wen on 2014/11/6.
 */
public class Preferences {

    private boolean mImageMode = false;
    private SharedPreferences mPreference;

    public Preferences(Application app) {
        mPreference = PreferenceManager.getDefaultSharedPreferences(app);

        setImageMode(mPreference.getBoolean(AppConstant.PREF_KEY_NO_IMAGE, AppConstant.IMAGE_MODE));
    }

    public boolean imageMode() {
        return mImageMode;
    }

    public void setImageMode(boolean mImageMode) {
        this.mImageMode = mImageMode;
    }

    public SharedPreferences getPreference() {
        return mPreference;
    }

    /**
     * 设置保存多少天的文章
     */
    public int getSaveDays() {
        return Integer.parseInt(mPreference.getString(AppConstant.PREF_KEY_SAVE_DAYS,
            App.getAppContext().getResources().getString(R.string.pref_save_days_default_value)));
    }

    /**
     * 配置信息,是否自动更新
     *
     * @return true 自动更新
     */
    public boolean isAutoUpdate() {
        return getPreference().getBoolean(AppConstant.PREF_KEY_AUTO_UPDATE, true);
    }

    /**
     * 是否自动拉取rss数据
     */
    public boolean isAutoFetchRss() {
        return getPreference().getBoolean(AppConstant.PREF_KEY_AUTO_REFRESH, false);
    }

    /**
     * 是否使用外部浏览器查看文章
     */
    public boolean external_open() {
        return getPreference().getBoolean(AppConstant.PREF_KEY_BROWSER, true);
    }

    /**
     * 是否自动加载图片
     */
    public boolean getImageMode() {
        return getPreference().getBoolean(AppConstant.PREF_KEY_NO_IMAGE, AppConstant.IMAGE_MODE);
    }

    public String getString(String key, String defaultValue) {
        return getPreference().getString(key, defaultValue);
    }

    public int getInt(String key, int defaultValue) {
        return getPreference().getInt(key, defaultValue);
    }

    public void setInt(String key, int value) {
        getPreference().edit().putInt(key, value).apply();
    }
}


text:
using Microsoft.VisualStudio.Modeling.Validation;
using NuPattern.Diagnostics;

namespace NuPattern.Runtime.Schema
{
    /// <summary>
    /// Customizations for the CollectionSchema class.
    /// </summary>
    [ValidationState(ValidationState.Enabled)]
    partial class CollectionSchema
    {
        private static readonly ITracer tracer = Tracer.Get<CollectionSchema>();
    }
}


text:
<?php namespace GeneaLabs\LaravelGovernor\Policies;

class Group extends BasePolicy
{
    // use default methods
}


text:
require 'rails_helper'

RSpec.describe Trainer, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
/**
 * @author tim
 *
 */
package uk.co.bluegecko.core.server.filter;