text:
package at.aau.dwaspgui.util.locators;

import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;

import at.aau.dwaspgui.view.AbstractView;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;

/**
 * Locates FXML files according to a naming convention.
 * @author Philip Gasteiger
 */
public class FXMLLocator {
	private static final String FXML_FILE_ENDING = ".fxml";

	/**
	 * Load the view from an .fxml file in the same package and with the same
	 * name of the controller.
	 * @param controller The controller of the loaded view.
	 * @param isRoot true, if control is the root of
	 * the view, false otherwise.
	 * @throws RuntimeException If the .fxml file could not be loaded.
	 */
	public static Parent locateForController(Object controller, boolean isRoot) {
		FXMLLoader fxmlLoader = new FXMLLoader();
		String fxmlFilename = controller.getClass().getSimpleName() + FXML_FILE_ENDING;
		String resourceBaseName = controller.getClass().getCanonicalName();
		URL fxmlResource = controller.getClass().getResource(fxmlFilename);

		fxmlLoader.setLocation(fxmlResource);
		fxmlLoader.setController(controller);
		fxmlLoader.setResources(ResourceBundle.getBundle(resourceBaseName, Locale.ENGLISH));

		if (isRoot)
			fxmlLoader.setRoot(controller);

	    try {
	        return fxmlLoader.load();
	    } catch (IOException exception) {
	        throw new RuntimeException(exception);
	    }
	}

	/**
	 * Load the scene from an .fxml file in the same package and with the same
	 * name of the view.
	 * @param view The view for which the .fxml file should be loaded.
	 * @see FXMLLocator#locateForController(Object, boolean)
	 */
	public static Scene locateForView(AbstractView<?> view) {
		return new Scene(locateForController(view, false));
	}
}


text:
/****
 * variant : yet another POD variant implementation
 ****/

#ifndef HOBBES_UTIL_VARIANT_HPP_INCLUDED
#define HOBBES_UTIL_VARIANT_HPP_INCLUDED

#include <string.h>

namespace hobbes {

// some simple compile-time logic
template <bool f, typename T, typename F>
  struct TIfF { };
template <typename T, typename F>
  struct TIfF<true, T, F> { typedef T type; };
template <typename T, typename F>
  struct TIfF<false, T, F> { typedef F type; };

// sizeof as a type-level function
template <typename T>
  struct TSizeOfF {
    static const size_t value = sizeof(T);
  };

// alignof as a type-level function
template <typename T>
  struct TAlignOfF {
    static const size_t value = alignof(T);
  };

// find a maximum property of a sequence of types
template <template <class> class SzP, typename T0, typename ... Ts>
  struct maximum {
    static const size_t value = SzP<T0>::value;
    typedef T0 type;
  };

template <template <class> class SzP, typename T0, typename T1, typename ... Ts>
  struct maximum<SzP, T0, T1, Ts...> : public maximum<SzP, typename TIfF<SzP<T1>::value < SzP<T0>::value, T0, T1>::type, Ts...> {
  };

// count a number of type arguments
template <typename ... Ts>
  struct CountF {
    static const size_t value = sizeof...(Ts);
  };

// find ctor index by type equality
template <typename T, typename ... Ctors>
  struct CtorIndexOf {
    static const uint32_t value = 0;
  };
template <typename T, typename ... Ctors>
  struct CtorIndexOf<T, T, Ctors...> {
    static const uint32_t value = 0;
  };
template <typename T, typename Ctor, typename ... Ctors>
  struct CtorIndexOf<T, Ctor, Ctors...> {
    static const uint32_t value = 1 + CtorIndexOf<T, Ctors...>::value;
  };

// get the first type in a sequence
template <typename T, typename ... Ts>
  struct First {
    typedef T type;
  };

// a variantSplit-like copy-constructor selector
template <typename ... Ctors>
  struct CCtorAt0 {
    static void invoke(uint32_t,void*,const void*) { } // shouldn't be possible
  };
template <typename Ctor, typename ... Ctors>
  struct CCtorAt0<Ctor, Ctors...> {
    static void invoke(uint32_t t, void* to, const void* from) {
      if (t == 0) {
        new (to) Ctor(*((const Ctor*)from));
      } else {
        CCtorAt0<Ctors...>::invoke(t-1, to, from);
      }
    }
  };

// a variantSplit-like destructor selector
template <typename ... Ctors>
  struct DtorAt0 {
    static void invoke(uint32_t,void*) { } // shouldn't be possible
  };
template <typename Ctor, typename ... Ctors>
  struct DtorAt0<Ctor, Ctors...> {
    static void invoke(uint32_t t, void* p) {
      if (t == 0) {
        ((Ctor*)p)->~Ctor();
      } else {
        DtorAt0<Ctors...>::invoke(t-1, p);
      }
    }
  };

// a simple tagged variant representation
template <typename ... Ctors>
  class variant {
  public:
    static_assert(sizeof...(Ctors) > 0, "Empty variants are impossible to construct");

    variant() : tag(0) {
      new (this->storage) typename First<Ctors...>::type();
    }
    template <typename T>
      variant(const T& t) : tag(CtorIndexOf<T, Ctors...>::value) {
        static_assert(CtorIndexOf<T, Ctors...>::value < sizeof...(Ctors), "Constructor type isn't part of variant");
        new (this->storage) T(t);
      }
    variant(const variant<Ctors...>& rhs) : tag(rhs.tag) {
      CCtorAt0<Ctors...>::invoke(this->tag, this->storage, rhs.storage);
    }

    ~variant() {
      DtorAt0<Ctors...>::invoke(this->tag, this->storage);
    }

    variant<Ctors...>& operator=(const variant<Ctors...>& rhs) {
      if (this != &rhs) {
        DtorAt0<Ctors...>::invoke(this->tag, this->storage);
        this->tag = rhs.tag;
        CCtorAt0<Ctors...>::invoke(this->tag, this->storage, rhs.storage);
      }
      return *this;
    }

    template <typename T>
      T* get() { return findByCtor<T>(); }
    template <typename T>
      const T* get() const { return findByCtor<T>(); }
  private:
    uint32_t tag;
    union {
      char storage[maximum<TSizeOfF, Ctors...>::value];
      typename maximum<TAlignOfF, Ctors...>::type maxAlignedT;
    };

    template <typename T>
      T* findByCtor() const {
        static_assert(CtorIndexOf<T, Ctors...>::value < sizeof...(Ctors), "Constructor type isn't part of variant");

        if (this->tag == CtorIndexOf<T, Ctors...>::value) {
          return (T*)(this->storage);
        } else {
          return 0;
        }
      }
  };

template <typename T, typename ... Ctors>
  T* get(variant<Ctors...>& v) {
    return v.template get<T>();
  }
template <typename T, typename ... Ctors>
  const T* get(const variant<Ctors...>& v) {
    return v.template get<T>();
  }

// the trivially true proposition -- ie: C's "void" with its one value constructible
struct unit { unit() { } };

}

#endif

redpajama_set_name: RedPajamaGithub


text:
Epoch parsing workflow for Alfred

During development, have you ever found yourself copying a epoch timestamp and wasting time converting it to a human readable format for debugging? This is a simple tool that helps you parse an epoch timestamp into ISO format.

###Usage
* Copy any epoch (Example: 1444466714178) to clipboard
* On Alfred, type **epoch**
* Press ENTER to copy the parsed date

![Usage](https://raw.githubusercontent.com/aakn/alfred-epoch-parser/master/screen-shot.png)

###Download
[Download the workflow](https://github.com/aakn/alfred-epoch-parser/blob/master/workflow/epoch-parser.alfredworkflow?raw=true)


text:
/******************************************

        30 Days of Code Submission

        @author Charles Bailey

        Licensed under MIT License

******************************************/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class AdvancedArithmetic{
    public:
          virtual int divisorSum(int n)=0;
};
//Write your code here
class Calculator : public AdvancedArithmetic {

    int divisorSum(int n) {
        if (n == 1) return n;
        int sum = 1 + n;
        int t = 2, sqrtn = sqrt(n);
        while (t <= sqrtn) {
            if (n % t == 0) sum += (t + n/t);
            t++;
        }
        return sum;
    }

};
int main(){
    int n;
    cin>>n;
    AdvancedArithmetic *myCalculator=new Calculator();
    int sum=myCalculator->divisorSum(n);
    cout<<"I implemented: AdvancedArithmetic\n"<<sum;
    return 0;
}


text: * Mod for Tweaking "Nuts & Bolts" modpack pack by the Breakin Blocks Community


text:
/*
 * ProvisioningAPI.PCL
 *
 * This file was automatically generated by APIMATIC BETA v2.0 on 01/26/2015
 */
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net.request;
using ProvisioningAPI.PCL;
using ProvisioningAPI.PCL.Models;

namespace ProvisioningAPI.PCL.Controllers
{
    public class InventoryController
    {

        //private fields for configuration

        //The username to use with basic authentication
        private string basicAuthUserName;

        //The password to use with basic authentication
        private string basicAuthPassword;

        /// <summary>
        /// Constructor with authentication and configuration parameters
        /// </summary>
        public InventoryController(string basicAuthUserName, string basicAuthPassword)
        {
            this.basicAuthUserName = basicAuthUserName;
            this.basicAuthPassword = basicAuthPassword;
        }

        /// <summary>
        /// listCapacityGroup is a method that allows you to get the list of your capacity groups.
        /// </summary>
        /// <param name="pageNumber">Required parameter: The page number, starting at 0.</param>
        /// <param name="pageSize">Required parameter: The page size (max number of entities that are displayed in the response).</param>
        /// <param name="capacityGroupId">Optional parameter: The identifier of the capacity group to search for.</param>
        /// <param name="description">Optional parameter: The description of the capacity group.</param>
        /// <param name="e164">Optional parameter: The e164 bound to the capacity group.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListCapacityGroupAsync(
                string pageNumber,
                string pageSize,
                string capacityGroupId = null,
                string description = null,
                string e164 = null)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/configuration/capacitygroup");

            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "pageNumber", pageNumber },
                    { "pageSize", pageSize },
                    { "capacityGroupId", capacityGroupId },
                    { "description", description },
                    { "e164", e164 }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// The listCountry operation allows you to search for countries available in the Voxbone coverage.
        /// </summary>
        /// <param name="pageNumber">Required parameter: The page number, starting at 0.</param>
        /// <param name="pageSize">Required parameter: The page size (max number of entities that are displayed in the response).</param>
        /// <param name="countryCodeA3">Optional parameter: The three letter identifier of the country.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListCountryAsync(
                string pageNumber,
                string pageSize,
                string countryCodeA3 = null)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/country");

            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "pageNumber", pageNumber },
                    { "pageSize", pageSize },
                    { "countryCodeA3", countryCodeA3 }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listCreditPackage is a method related to Voxbone's inventory. This method is used to retrieve the list of packages that are available for prepaid credits top-ups (e.g. $100 Prepaid Credits package which shows a value multiplied by 100: "Price100=10000").
        /// </summary>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListCreditPackageAsync()
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/creditpackage");

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listDid is a method related to your own inventory. This method allows you to search for DIDs within your own inventory. This method can be useful to get the current configuration of one or multiple DIDs.
        /// </summary>
        /// <param name="pageSize">Required parameter: The page size (max number of entities that are displayed in the response).</param>
        /// <param name="pageNumber">Required parameter: The page number, starting at 0.</param>
        /// <param name="webRtcEnabled">Optional parameter: A boolean flag indicating if the numbers are WebRTC flagged.</param>
        /// <param name="smsOutbound">Optional parameter: A boolean flag indicating if the numbers are SMS Outbound flagged.</param>
        /// <param name="deliveryId">Optional parameter: The identifier of the pop the numbers are mapped to.</param>
        /// <param name="portingReference">Optional parameter: The reference for the numbers' porting request.</param>
        /// <param name="orderReference">Optional parameter: The reference for the numbers' order.</param>
        /// <param name="countryCodeA3">Optional parameter: The three letter identifier of the country the numbers are part of.</param>
        /// <param name="serviceType">Optional parameter: The service type of the numbers.</param>
        /// <param name="smsLinkGroupId">Optional parameter: The identifier of the sms link group the numbers are mapped to.</param>
        /// <param name="faxUriId">Optional parameter: The identifier of the fax uri the numbers are mapped to.</param>
        /// <param name="voiceUriId">Optional parameter: The identifier of the voice uri the numbers are mapped to.</param>
        /// <param name="regulationAddressId">Optional parameter: The identifier of the address the numbers are linked to.</param>
        /// <param name="e164Pattern">Optional parameter: The E164, or part of it. The system will attempt to find any number which E164 contains this string of numbers.</param>
        /// <param name="didGroupIds">Optional parameter: A list of identifiers for the didGroup the numbers are part of.</param>
        /// <param name="needAddressLink">Optional parameter: A boolean flag indicating if the numbers need to be linked to an address for regulation purposes.</param>
        /// <param name="didIds">Optional parameter: A list of number identifiers.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListDidAsync(
                string pageSize,
                string pageNumber,
                string webRtcEnabled = null,
                string smsOutbound = null,
                string deliveryId = null,
                string portingReference = null,
                string orderReference = null,
                string countryCodeA3 = null,
                string serviceType = null,
                string smsLinkGroupId = null,
                string faxUriId = null,
                string voiceUriId = null,
                string regulationAddressId = null,
                string e164Pattern = null,
                string didGroupIds = null,
                string needAddressLink = null,
                string didIds = null)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/did");

            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "pageSize", pageSize },
                    { "pageNumber", pageNumber },
                    { "webRtcEnabled", webRtcEnabled },
                    { "smsOutbound", smsOutbound },
                    { "deliveryId", deliveryId },
                    { "portingReference", portingReference },
                    { "orderReference", orderReference },
                    { "countryCodeA3", countryCodeA3 },
                    { "serviceType", serviceType },
                    { "smsLinkGroupId", smsLinkGroupId },
                    { "faxUriId", faxUriId },
                    { "voiceUriId", voiceUriId },
                    { "regulationAddressId", regulationAddressId },
                    { "e164Pattern", e164Pattern },
                    { "didGroupIds", didGroupIds },
                    { "needAddressLink", needAddressLink },
                    { "didIds", didIds }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listDidGroup is a method related to Voxbone's inventory. It allows you to retrieve the list of DID groups. A DID group can be defined as the smallest set of DIDs which is usually DIDs that share the same city or area code attributes. It is a method which is useful to get pricing info on a DID and to get didGroupIds which is a required parameter when placing a DID order.
        /// </summary>
        /// <param name="countryCodeA3">Required parameter: The three letter identifier for the didGroup's country.</param>
        /// <param name="pageNumber">Required parameter: The page number, starting at 0.</param>
        /// <param name="pageSize">Required parameter: The page size (max number of entities that are displayed in the response).</param>
        /// <param name="didGroupIds">Optional parameter: The list of didGroup identifier.</param>
        /// <param name="stateId">Optional parameter: The numerical identifier for the didGroup's state. Please see the listState operation to retrieve a validstate identifier.</param>
        /// <param name="cityNamePattern">Optional parameter: The name of the didGroup's city. Note that the system will execute a partial match on the city name.</param>
        /// <param name="rateCenter">Optional parameter: The name of the didGroup's ratecenter. Note that the system will execute a partial match on the ratecenter name.</param>
        /// <param name="areaCode">Optional parameter: The didGroup's area code.</param>
        /// <param name="didType">Optional parameter: The didGroup's did type.</param>
        /// <param name="showEmpty">Optional parameter: Set to true if you want to show the didGroups with no stock currently available.</param>
        /// <param name="featureIds">Optional parameter: The list of desired feature. This list should contain the identifier of any desired feature for the didGroup.Please refer to the listFeature operation to retrieve valid feature identifiers.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListDidGroupAsync(
                string countryCodeA3,
                string pageNumber,
                string pageSize,
                string didGroupIds = null,
                string stateId = null,
                string cityNamePattern = null,
                string rateCenter = null,
                string areaCode = null,
                string didType = null,
                string showEmpty = null,
                string featureIds = null)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/didgroup");

            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "countryCodeA3", countryCodeA3 },
                    { "pageNumber", pageNumber },
                    { "pageSize", pageSize },
                    { "didGroupIds", didGroupIds },
                    { "stateId", stateId },
                    { "cityNamePattern", cityNamePattern },
                    { "rateCenter", rateCenter },
                    { "areaCode", areaCode },
                    { "didType", didType },
                    { "showEmpty", showEmpty },
                    { "featureIds", featureIds }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listFeature is a method related to Voxbone's inventory. It allows you to retrieve the list of features (featureID, name and description) that DIDs can have such as VoxFAX or VoxSMS.
        /// </summary>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListFeatureAsync()
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/feature");

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listTrunk is a method related to your own inventory. This method allows you to get the list of the trunks that are available in your account.
        /// </summary>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListTrunkAsync()
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/trunk");

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// The listZone operation allows you to display all the zones currently configured in your account.
        /// </summary>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListZoneAsync()
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/zone");

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// The listCountry operation allows you to search for countries available in the Voxbone coverage.
        /// </summary>
        /// <param name="countryCodeA3">Required parameter: The three letter identifier of the country.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListACountryAsync(
                string countryCodeA3)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/country/{countryCodeA3}");

            //process optional template parameters
            APIHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "countryCodeA3", countryCodeA3 }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listRestriction is a method related to Voxbone's inventory. It allows you to get the list of restrictions per country in a text format.
        /// </summary>
        /// <param name="countryCodeA3">Required parameter: The three letter identifier of the country.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListRestrictionAsync(
                string countryCodeA3)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/country/{countryCodeA3}/restriction");

            //process optional template parameters
            APIHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "countryCodeA3", countryCodeA3 }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

        /// <summary>
        /// listState is a method related to Voxbone's inventory. It allows you to get the list of states for a country that has states such as USA and CAN.
        /// </summary>
        /// <param name="countryCodeA3">Required parameter: The three letter identifier of the country.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task<dynamic> ListStateAsync(
                string countryCodeA3)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);
            queryBuilder.Append("/services/rest/inventory/country/{countryCodeA3}/state");

            //process optional template parameters
            APIHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary<string, object>()
                {
                    { "countryCodeA3", countryCodeA3 }
                });

            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.get(queryUrl)
                //append request with appropriate headers and parameters
                .header("User-Agent", "APIMATIC 2.0")
                .header("Accept", "application/json")
                .basicAuth(basicAuthUserName, basicAuthPassword);

            //invoke request and get response
            HttpResponse<String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
                throw new APIException(@"HTTP Response Not OK", response.Code);

            return APIHelper.JsonDeserialize<dynamic>(response.Body);
        }

    }
}


text:
#include <stdlib.h>
#include <assert.h>
#include "fsl_pit_driver.h"

/*!
 * @addtogroup pit_irq
 * @{
 */

/*******************************************************************************
 * Variables
 ******************************************************************************/

/*!
 * @brief Function table to save PIT isr callback function pointers.
 *
 * Call PIT_DRV_InstallCallback to install isr callback functions.
 */
static pit_isr_callback_t pitIsrCallbackTable[HW_PIT_INSTANCE_COUNT][FSL_FEATURE_PIT_TIMER_COUNT] = {{NULL}};

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * @brief System default IRQ handler defined in startup code.
 *
 * Users can either edit this handler or define a callback function. Furthermore,
 * interrupt manager could be used to re-map the IRQ handler to another function.
 */
#if FSL_FEATURE_PIT_HAS_SHARED_IRQ_HANDLER
void PIT_IRQHandler(void)
{
    uint32_t i;
    for(i=0; i < FSL_FEATURE_PIT_TIMER_COUNT; i++)
    {
        if (PIT_HAL_IsIntPending(g_pitBaseAddr[0], i))
        {
            /* Clear interrupt flag.*/
            PIT_HAL_ClearIntFlag(g_pitBaseAddr[0], i);

            /* Run callback function if it exists.*/
            if (pitIsrCallbackTable[0][i])
            {
                (*pitIsrCallbackTable[0][i])(i);
            }
        }
    }
}
#else

#if (FSL_FEATURE_PIT_TIMER_COUNT > 0U)
void PIT0_IRQHandler(void)
{
    /* Clear interrupt flag.*/
    PIT_HAL_ClearIntFlag(g_pitBaseAddr[0], 0U);

    /* Run callback function if it exists.*/
    if (pitIsrCallbackTable[0][0])
    {
        (*pitIsrCallbackTable[0][0])(0U);
    }
}
#endif

#if (FSL_FEATURE_PIT_TIMER_COUNT > 1U)
void PIT1_IRQHandler(void)
{
    /* Clear interrupt flag.*/
    PIT_HAL_ClearIntFlag(g_pitBaseAddr[0], 1U);

    /* Run callback function if it exists.*/
    if (pitIsrCallbackTable[0][1])
    {
        (*pitIsrCallbackTable[0][1])(1U);
    }
}
#endif

#if (FSL_FEATURE_PIT_TIMER_COUNT > 2U)
void PIT2_IRQHandler(void)
{
    /* Clear interrupt flag.*/
    PIT_HAL_ClearIntFlag(g_pitBaseAddr[0], 2U);

    /* Run callback function if it exists.*/
    if (pitIsrCallbackTable[0][2])
    {
        (*pitIsrCallbackTable[0][2])(2U);
    }
}
#endif

#if (FSL_FEATURE_PIT_TIMER_COUNT > 3U)
void PIT3_IRQHandler(void)
{
    /* Clear interrupt flag.*/
    PIT_HAL_ClearIntFlag(g_pitBaseAddr[0], 3U);

    /* Run callback function if it exists.*/
    if (pitIsrCallbackTable[0][3])
    {
        (*pitIsrCallbackTable[0][3])(3U);
    }
}
#endif

#endif /* FSL_FEATURE_PIT_HAS_SHARED_IRQ_HANDLER */

/*! @} */

/*FUNCTION**********************************************************************
 *
 * Function Name : PIT_DRV_InstallCallback
 * Description   : Register pit isr callback function.
 * System default ISR interfaces are already defined in fsl_pit_irq.c. Users
 * can either edit these ISRs or use this function to register a callback
 * function. The default ISR will run the callback function it there is one
 * installed here.

 *END**************************************************************************/
pit_isr_callback_t  PIT_DRV_InstallCallback(uint32_t instance, uint32_t channel, pit_isr_callback_t function)
{
    assert(channel < FSL_FEATURE_PIT_TIMER_COUNT);

    pit_isr_callback_t retVal = pitIsrCallbackTable[instance][channel];
    pitIsrCallbackTable[instance][channel] = function;
    return retVal;
}

/*******************************************************************************
 * EOF
 ******************************************************************************/


text:
package startup.gbg.augumentedbarcodescanner;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Comparator;
import java.util.List;

/**
 * Created by simonarneson on 2017-05-06.
 */

class PriceListAdapter extends RecyclerView.Adapter<PriceListAdapter.ViewHolder> {
    private List<PriceData> dataset;
    private Context context;
    private View.OnClickListener itemClickListener;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView storeName;
        public TextView price;

        public ViewHolder(View v) {
            super(v);
            storeName = (TextView) v.findViewById(R.id.storeName);
            price = (TextView) v.findViewById(R.id.price);

        }
    }

    public PriceListAdapter(Context context) {
        this.context = context;

        dataset = new SortedList<>(new PriceListComparator());
    }

    public void setPrices(List<PriceData> prices) {
        dataset.clear();
        for (PriceData price : prices) {
            dataset.add(price);
        }
        notifyDataSetChanged();
    }

    @Override
    public PriceListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_price_list, parent, false);
        v.setOnClickListener(itemClickListener);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        PriceData price = dataset.get(position);

        double pricing = price.price.amount / 100.0;
        String formattedPrice = String.format("%.2f", pricing);
        String name = price.store.chain.name().toLowerCase();
        name = name.substring(0, 1).toUpperCase() + name.substring(1);

        holder.storeName.setText(name);
        holder.price.setText("" + formattedPrice + ":-");
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    private static class PriceListComparator implements Comparator<PriceData> {
        @Override
        public int compare(PriceData price, PriceData p1) {
            return Long.compare(price.price.amount, p1.price.amount);
        }
    }

    public void setItemClickListener(View.OnClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }
}


text:
import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-rolodex',
    version='0.1.3.3',
    packages=['rolodex'],
    include_package_data=True,
    license='MIT License',
    description='A Django app for managing relationships between people and organizations.',
    long_description=README,
    url='https://github.com/DallasMorningNews/django-rolodex/',
    author='Jon McClure',
    author_email='jon.r.mcclure@gmail.com',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    install_requires=['Django>=1.9', 'djangorestframework>=2.4.4', 'dj-database-url>=0.3.0', 'networkx>=1.9.1', 'django-taggit>=0.17.1'],
)


text:
var Tccc;
(function (Tccc) {
    var Talk = /** @class */ (function () {
        function Talk(serverObj) {
            angular.copy(serverObj, this);
        }
        Object.defineProperty(Talk.prototype, "pictureUrlOrDefault", {
            get: function () {
                return "/files/getTalkProfileImage?talkId=" + this.id || "../Content/Images/unknown-speaker.jpg";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Talk.prototype, "timeFriendly", {
            get: function () {
                if (this.hour) {
                    return moment()
                        .hour(0)
                        .minute(0)
                        .second(0)
                        .add(this.hour, "hours")
                        .format("h:mm a");
                }
                return "";
            },
            enumerable: true,
            configurable: true
        });
        return Talk;
    }());
    Tccc.Talk = Talk;
})(Tccc || (Tccc = {}));
//# sourceMappingURL=Talk.js.map


text:
<?php
$coverage->stop();

$writer = new PHP_CodeCoverage_Report_HTML;
$writer->process($coverage, '/tmp/coverage');


text:
<!doctype html>

<meta charset="utf-8">
<title>FOSEC</title>
<meta name="description" content="A blog about security">

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@fosec.vn">
<meta name="twitter:creator" content="@fosec.vn">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="FOSEC">
<meta property="og:description" content="A blog about security">
<meta property="og:url" content="http://127.0.0.1:4000/">
<meta property="og:site_name" content="FOSEC">
<meta property="og:image" content="http://127.0.0.1:4000/images/assets/images/logo.png">

<link rel="canonical" href="http://127.0.0.1:4000/">
<link href="http://127.0.0.1:4000/feed.xml" type="application/atom+xml" rel="alternate" title="FOSEC Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>

<link rel="stylesheet" href="http://127.0.0.1:4000/assets/css/main.css">
<link rel="stylesheet" href="http://127.0.0.1:4000/assets/css/jquery.mmenu.all.css">
<link rel="stylesheet" href="http://127.0.0.1:4000/assets/css/jquery.floating-social-share.min.css">

<link href="http://127.0.0.1:4000/assets/fonts/fontLato.css" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://127.0.0.1:4000/assets/images/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://127.0.0.1:4000/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://127.0.0.1:4000/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://127.0.0.1:4000/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://127.0.0.1:4000/images/apple-touch-icon-144x144-precomposed.png">

           FOSEC

Tags

MISC

CTF

Research

Guide

News

News

Guide

Research

CTF

MISC

Tags

What is CTF

Hacking Firmware from Mobile Phone Hacking Company Leaked Online

Massive DDoS Attack Against Dyn DNS Service Knocks Popular Sites Offline

Best Password Manager — For Windows, Linux, Mac, Android, iOS and Enterprise

Latest

		What is CTF
		 26/10/2016  fosec
		The Israeli firm Cellebrite, which provides digital forensics tools and softw...

		Hacking Firmware from Mobile Phone Hacking Company Leaked Online
		 26/10/2016  thehackernews
		The Israeli firm Cellebrite, which provides digital forensics tools and softw...

		Massive DDoS Attack Against Dyn DNS Service Knocks Popular Sites Offline
		 26/10/2016  thehackernews
		Cyber attacks are getting evil and worst nightmare for companies day-by-day, ...

		Best Password Manager — For Windows, Linux, Mac, Android, iOS and Enterprise
		 26/10/2016  thehackernews
		When it comes to safeguarding your Internet security, installing an antivirus...

ctf

			What is CTF
			 26/10/2016  fosec
			The Israeli firm Cellebrite, which provides digital forensics tools and softw...

news

			Hacking Firmware from Mobile Phone Hacking Company Leaked Online
			 26/10/2016  thehackernews
			The Israeli firm Cellebrite, which provides digital forensics tools and softw...

			Massive DDoS Attack Against Dyn DNS Service Knocks Popular Sites Offline
			 26/10/2016  thehackernews
			Cyber attacks are getting evil and worst nightmare for companies day-by-day, ...

			Best Password Manager — For Windows, Linux, Mac, Android, iOS and Enterprise
			 26/10/2016  thehackernews
			When it comes to safeguarding your Internet security, installing an antivirus...

About

		FOSEC is a blog about Security.

Linked Websites

FOSEC

Information

Mailing List

Advertise

Privacy

Connect with Us

Twitter

Facebook

Email

	Copyright © 2016 FOSEC


text:
package auth0;

import play.mvc.*;
import play.data.*;
import static play.mvc.Controller.*;

public class RequestNonceStorage implements NonceStorage {

    public RequestNonceStorage() {

    }

    public String getState () {
        return (String) session("state");
    }

    public void setState(String nonce) {
        session("state", nonce);
    }
}


text:
-[Java 8](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html)

-[Maven](https://maven.apache.org/install.html), which downloads and manages the libraries and APIs needed to get the Grove device working.

-[Git](https://git-scm.com/), which clones a template Maven project with the necessary dependencies already set up.

-[Mosquitto](https://mosquitto.org/download/), which is an MQTT message broker

# Starting your Maven project:
[Starting a mvn project](https://github.com/oci-pronghorn/FogLighter/blob/master/README.md)

# Example project:

The following sketch will demonstrate a basic demo for using an OLED 96 x 96.

Demo code:

```java
package com.ociweb.grove;

import com.ociweb.iot.maker.*;
import static com.ociweb.iot.maker.Port.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OLED96x96 implements FogApp
{
	private static final Logger logger = LoggerFactory.getLogger(OLED96x96.class);

	@Override
	public void declareConnections(Hardware c) {
		c.setTimerPulseRate(2500);
	}
	@Override
	public void declareBehavior(FogRuntime runtime) {
		runtime.registerListener(new OLED_96x96Behavior(runtime));
	}
	public static void main(String[] args){
		FogRuntime.run(new OLED96x96());
	}
}
```

Behavior class:

```java
package com.ociweb.grove;

import com.ociweb.gl.api.TimeListener;
import static com.ociweb.iot.grove.oled.OLEDTwig.*;
import com.ociweb.iot.maker.FogRuntime;
import com.ociweb.iot.grove.oled.OLED_96x96_Transducer;
import static com.ociweb.grove.OCI_Logo.*;
import static com.ociweb.grove.Grumpy.*;
import static com.ociweb.grove.PiLogo.*;
import static com.ociweb.grove.DexterLogo.*;
import static com.ociweb.grove.QR.*;
import static com.ociweb.grove.Huy.*;

public class OLED_96x96Behavior implements TimeListener{

	private final OLED_96x96_Transducer display;
	public OLED_96x96Behavior(FogRuntime rt){
		display = OLED_96x96.newTransducer(rt.newCommandChannel());

	}
	@Override
	public void timeEvent(long time, int iteration) {

		int remainder = iteration % 6;

		switch (remainder){
			case 0:
				display.display(OCI_LOGO);
				break;
			case 1:
				display.display(GRUMPY);
				break;
			case 2:
				display.display(PI_LOGO);
				break;
			case 3:
				display.display(DEX_LOGO);
				break;
			case 4:
				display.display(HUY);
			case 5:
				display.display(OCI_LINK);
			}

		System.out.println("Switching to image " + remainder);

	}
}
```

This is an example use of the OLED 96 x 96. In the behavior class, make sure to an OLED 96x96 transducer. Also included in the class, but while not shown above, are multiple 2-demensional arrays of different images. You can generate your own 2-demensional array of a jpeg or a png file to put the image on the OLED 96x96 by going to AppTest under ./src/test/java/com/ociweb/grove/.


text:
<header>
  <figure class="figure--center">
    <img src="http://placehold.it/1000x200">
  </figure>
</header>


text:
Originally published: 2006-06-23 14:00:51
Last updated: 2006-06-30 00:03:39
Author: Wensheng Wang

I saw a lot of implementations that doesn't work on list with repeated items.
For example: [3,3,"hello","hello"]
This recipe show such function that works on any list.
(update 6/29/06) added generator version permu2(xs).


text:
from telemetry.page import page as page_module
from telemetry import story

from page_sets import webgl_supported_shared_state

class ToughWebglCasesPage(page_module.Page):

  def __init__(self, url, page_set):
    super(ToughWebglCasesPage, self).__init__(
        url=url, page_set=page_set,
        shared_page_state_class=(
            webgl_supported_shared_state.WebGLSupportedSharedState),
        make_javascript_deterministic=False)
    self.archive_data_file = 'data/tough_webgl_cases.json'

  @property
  def skipped_gpus(self):
    # crbug.com/462729
    return ['arm', 'broadcom', 'hisilicon', 'imagination', 'qualcomm',
            'vivante']

  def RunNavigateSteps(self, action_runner):
    super(ToughWebglCasesPage, self).RunNavigateSteps(action_runner)
    action_runner.WaitForJavaScriptCondition(
        'document.readyState == "complete"')
    action_runner.Wait(2)

  def RunPageInteractions(self, action_runner):
    with action_runner.CreateInteraction('WebGLAnimation'):
      action_runner.Wait(5)

class ToughWebglCasesPageSet(story.StorySet):

  """
  Description: Self-driven WebGL animation examples
  """

  def __init__(self):
    super(ToughWebglCasesPageSet, self).__init__(
      archive_data_file='data/tough_webgl_cases.json',
      cloud_storage_bucket=story.PUBLIC_BUCKET)

    urls_list = [
      # pylint: disable=line-too-long
      'http://www.khronos.org/registry/webgl/sdk/demos/google/nvidia-vertex-buffer-object/index.html',
      # pylint: disable=line-too-long
      'http://www.khronos.org/registry/webgl/sdk/demos/google/san-angeles/index.html',
      # pylint: disable=line-too-long
      'http://www.khronos.org/registry/webgl/sdk/demos/google/particles/index.html',
      'http://www.khronos.org/registry/webgl/sdk/demos/webkit/Earth.html',
      # pylint: disable=line-too-long
      'http://www.khronos.org/registry/webgl/sdk/demos/webkit/ManyPlanetsDeep.html',
      'http://webglsamples.org/aquarium/aquarium.html',
      'http://webglsamples.org/blob/blob.html',
      # pylint: disable=line-too-long
      'http://webglsamples.org/dynamic-cubemap/dynamic-cubemap.html',
      # pylint: disable=line-too-long
      'http://kenrussell.github.io/webgl-animometer/Animometer/tests/3d/webgl.html',
    ]
    for url in urls_list:
      self.AddStory(ToughWebglCasesPage(url, self))


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>ukusni stakleni rezanci, samo da je više sadržaja, a manje rezanaca</Text>
  <Rating>4.5</Rating>
  <Source>http://pauza.hr/menu/halo-maksimirski-zmaj</Source>
</CrawlItem>


text:
<?php

use Mockery as m;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

class DatabaseEloquentHasManyThroughTest extends PHPUnit_Framework_TestCase {

	public function tearDown()
	{
		m::close();
	}

	public function testRelationIsProperlyInitialized()
	{
		$relation = $this->getRelation();
		$model = m::mock('Illuminate\Database\Eloquent\Model');
		$relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array = array()) { return new Collection($array); });
		$model->shouldReceive('setRelation')->once()->with('foo', m::type('Illuminate\Database\Eloquent\Collection'));
		$models = $relation->initRelation(array($model), 'foo');

		$this->assertEquals(array($model), $models);
	}

	public function testEagerConstraintsAreProperlyAdded()
	{
		$relation = $this->getRelation();
		$relation->getQuery()->shouldReceive('whereIn')->once()->with('users.country_id', array(1, 2));
		$model1 = new EloquentHasManyThroughModelStub;
		$model1->id = 1;
		$model2 = new EloquentHasManyThroughModelStub;
		$model2->id = 2;
		$relation->addEagerConstraints(array($model1, $model2));
	}

	public function testModelsAreProperlyMatchedToParents()
	{
		$relation = $this->getRelation();

		$result1 = new EloquentHasManyThroughModelStub;
		$result1->country_id = 1;
		$result2 = new EloquentHasManyThroughModelStub;
		$result2->country_id = 2;
		$result3 = new EloquentHasManyThroughModelStub;
		$result3->country_id = 2;

		$model1 = new EloquentHasManyThroughModelStub;
		$model1->id = 1;
		$model2 = new EloquentHasManyThroughModelStub;
		$model2->id = 2;
		$model3 = new EloquentHasManyThroughModelStub;
		$model3->id = 3;

		$relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
		$models = $relation->match(array($model1, $model2, $model3), new Collection(array($result1, $result2, $result3)), 'foo');

		$this->assertEquals(1, $models[0]->foo[0]->country_id);
		$this->assertEquals(1, count($models[0]->foo));
		$this->assertEquals(2, $models[1]->foo[0]->country_id);
		$this->assertEquals(2, $models[1]->foo[1]->country_id);
		$this->assertEquals(2, count($models[1]->foo));
		$this->assertEquals(0, count($models[2]->foo));
	}

	protected function getRelation()
	{
		$builder = m::mock('Illuminate\Database\Eloquent\Builder');
		$builder->shouldReceive('join')->once()->with('users', 'users.id', '=', 'posts.user_id');
		$builder->shouldReceive('where')->with('users.country_id', '=', 1);

		$country = m::mock('Illuminate\Database\Eloquent\Model');
		$country->shouldReceive('getKey')->andReturn(1);
		$country->shouldReceive('getForeignKey')->andReturn('country_id');
		$user = m::mock('Illuminate\Database\Eloquent\Model');
		$user->shouldReceive('getTable')->andReturn('users');
		$user->shouldReceive('getQualifiedKeyName')->andReturn('users.id');
		$post = m::mock('Illuminate\Database\Eloquent\Model');
		$post->shouldReceive('getTable')->andReturn('posts');

		$builder->shouldReceive('getModel')->andReturn($post);

		$user->shouldReceive('getKey')->andReturn(1);
		$user->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
		$user->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
		return new HasManyThrough($builder, $country, $user, 'country_id', 'user_id');
	}

}

class EloquentHasManyThroughModelStub extends Illuminate\Database\Eloquent\Model {
	public $country_id = 'foreign.value';
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/compose_tweet_padding"
    tools:context="com.codepath.apps.allotweets.ui.compose.ComposeTweetFragment">

    <RelativeLayout
        android:id="@+id/top_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/bt_close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:src="@drawable/ic_close"
            tools:ignore="ContentDescription" />

        <ImageView
            android:id="@+id/iv_profile"
            android:layout_width="@dimen/avatar_size"
            android:layout_height="@dimen/avatar_size"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            tools:ignore="ContentDescription" />

    </RelativeLayout>

    <com.codepath.apps.allotweets.ui.base.TextView
        android:id="@+id/tv_in_reply"
        style="@style/tweet_alias"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top_container"
        android:text="@string/in_reply_to" />

    <com.codepath.apps.allotweets.ui.base.EditText
        android:id="@+id/et_status"
        style="@style/input_status"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_toolbar"
        android:layout_below="@+id/tv_in_reply"
        android:layout_marginBottom="@dimen/activity_vertical_margin_half"
        android:layout_marginTop="@dimen/activity_vertical_margin_half" />

    <RelativeLayout
        android:id="@+id/bottom_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">

        <com.codepath.apps.allotweets.ui.base.TextView
            android:id="@+id/tv_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginEnd="5dp"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/bt_tweet"
            android:layout_toStartOf="@+id/bt_tweet"
            tools:text="160" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/bt_tweet"
            style="@style/tweet_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="@string/tweet" />

    </RelativeLayout>

</RelativeLayout>


text:
<?php

namespace Gabrielqs\Boleto\Block\Checkout\Success;

use \Magento\Framework\View\Element\Template;
use \Magento\Sales\Model\Order;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Checkout\Model\Session as CheckoutSession;
use \Gabrielqs\Boleto\Helper\Boleto\Data as BoletoHelper;

class PrintBoleto extends Template
{
    /**
     * Boleto Helper
     * @var BoletoHelper
     */
    protected $_boletoHelper;

    /**
     * Checkout Session
     * @var CheckoutSession
     */
    protected $_checkoutSession;

    /**
     * PrintBoleto constructor.
     * @param Context $context
     * @param CheckoutSession $checkoutSession
     * @param BoletoHelper $boletoHelper
     * @param array $data
     */
    public function __construct(
        Context $context,
        CheckoutSession $checkoutSession,
        BoletoHelper $boletoHelper,
        array $data
    ) {
        $this->_checkoutSession = $checkoutSession;
        $this->_boletoHelper = $boletoHelper;
        parent::__construct($context, $data);
    }

    /**
     * Retrieves last order from checkout session
     * @return Order
     */
    protected function _getOrder()
    {
        return $this->_checkoutSession->getLastRealOrder();
    }

    /**
     * Should we show the print boleto button on the success page?
     * @return bool
     */
    public function isShow()
    {
        $order = $this->_getOrder();
        return ($order->getPayment() && ($order->getPayment()->getMethod() == $this->_boletoHelper->getMethodCode()));
    }

    /**
     * Returns URL for boleto printing, using the last order placed
     * This function is to be used in the success page
     * @return string
     */
    public function getPrintUrl()
    {
        return $this->_boletoHelper->getPrintBoletoUrl($this->_getOrder());
    }
}


text:
Recently Google decided to update Gmail's interface to [Material Design 2](https://9to5google.com/2018/04/26/what-is-material-design-2-examples-launch-io/), with cool rounded buttons and a new logo.

![Gmail's new UI features more rounded things](/images/010/newui.png)

Unfortunately, there are two problems with this redesign that make it not work for me. One of them is that the new interface is much more **animation-heavy**; it significantly raises the minimum system requirements for a quick and responsive e-mail experience, and one of the PCs I use Gmail on can no longer keep up. Even on a good computer, it now takes two or three seconds more on the critical path from navigating to https://mail.google.com to getting a new message window in response to your "Compose" button click

The other major problem with the new Gmail is the inclusion of **"Confidential Mode"**.

## Confidential Mode

![Confidential mode tries to make e-mail do things that e-mail cannot do](/images/010/confidentialmode.png)

Confidential Mode replaces e-mails that you send from Gmail with links back to Google, so that Google can choose to dispense or not dispense the content of your messages to the recipients. After a certain date, or when you ask Google to rescind the message, Google will stop handing over the message contents and the message will be "expired".

### Not a Mode

That's all well and good, but that's not what this feature is being sold as. It's being marketed by Google as a "mode" that ordinary e-mail can be in, but it's really more akin to an e-mail substitute. Gmail users get a message rendered in-line, but the thing actually sent by e-mail is a *link* to the message, and that isn't made clear. They don't advertise that recipients are going to have to agree to Google's terms of service and privacy policy, for example, before being allowed to read your message. The way it is treated makes me think that **Google is quite happy to have people conflate Gmail and e-mail**, and I don't like that at all.

### Not Confidential

What Google does talk about is the advanced security features that Confidential Mode messages come with, which prevent the recipient from saving or printing the messages they receive. These security measures are, naturally, implemented client-side in the untrusted recipient's web browser. Less naturally, they are implemented in CSS, and are [trivially defeatable with the Firefox Style Editor](https://grokprivacy.org/2018/06/24/archiving-self-destructing-gmail-with-firefox/). Although I haven't found one yet, a browser extension could do it even more easily. How does Google disclose this shortcoming to Confidential Mode users?

> Recipients who have malicious programs on their computer may still be able to copy or download your messages or attachments.

You heard it here first, folks! Firefox, along with every other piece of software that is willing to put the interests of its immediate user first, is a **malicious program**! If you don't view the content we sent you in the way we told you to view it, you're doing Bad Hacker Crimes and should be sent to jail! This is because we are Google, the makers of e-mail.

## Alternatives

Between the poor performance of the new web interface, and the apparent preparation for a hostile takeover of the federated e-mail network, I decided that I would rather not use the new Gmail. So I went and fired up Ubuntu's default e-mail client, Thunderbird, and logged it into my Gmail account. Presto! A new, fully-spec-compliant e-mail client for Gmail, right?

Well, not so much.

### Thunderbird

![Thunderbird deals poorly with this much mail](/images/010/thunderbird.png)

Thunderbird was my e-mail client of choice back in the pre-Gmail days of the early-to-mid 2000s. It's the same basic program today, and it isn't designed for the **210,487 e-mails** that 11 years of archiving everything have left me with. It wants to download headers for all of them and display them all in a big list with a tiny scrollbar, and has no concept of pagination. Note how, in the screenshot, it seems to have gotten stuck on message 9 of the 182,302 messages that it still hasn't managed to get headers for.

Also, in the last decade I've worked out that [it's not really OK to murder a bunch of people, steal their continent, and then borrow cool stuff from their religion to name your software](http://ohwitchplease.ca/2016/12/episode-18-roaring-anachronisms-and-where-to-find-them/), so it bothers me every time I look at the title bar now.

### RainLoop

[RainLoop](https://www.rainloop.net/) is an AGPLv3-licensed web-based e-mail client. You run the client on your web server, and you interact with it through your browser. You "log in" to RainLoop with your e-mail account credentials, and it logs in to the actual IMAP server behind the scenes and presents you with a view of your e-mail in your browser.

Because it's a web-based client, it doesn't suffer from the same shortcomings that Thunderbird has with regard to immediately trying to download and display massive amounts of mail. And because the interface is in the browser, while the backend is running as its own program, if it does have to sit around thuinking about hundreds of thousands of messages, it has a limited impact on UI responsiveness.

Here's a screenshot from RainLoop's official online demo, to which people are happily uploading potentially malicious .exe files.

![RainLoop has a sidebar, a message list, and a message view](/images/010/rainloop.png)

Note the support for pagination of the message list, and for large numbers of pages. There's also a handy "Mark all as read" feature for dealing with unread messages in huge folders.

I decided that RainLoop looked interesting, but it's not as simple to install as Thunderbird, because it needs a web server. Moreover, if I'm going to go through all the trouble of setting up a web server, I want to be able to get to my e-mail from the Internet.

## Installing RainLoop

Luckily, there's a nice Docker image of RainLoop available: [hardware/rainloop](https://hub.docker.com/r/hardware/rainloop/).

To use it, you will need Docker installed. For Ubuntu, that looks like:

```
sudo apt install docker
```

You can then get RainLoop going right away with:

```
mkdir webmail-host
cd webmail-host
mkdir rainloop
docker run --name rainloop -e LOG_TO_STDOUT='true' -v ./rainloop:/rainloop/data hardware/rainloop
```

This sets up a container running an Nginx web server with RainLoop installed on it, listening on the container's port 8888. You can stop it with `Ctrl+C`.

### Docker and VPNs

Note that, if you are using a VPN or otherwise have routes covering a lot of the IP space, Docker will be upset that it can't find a block of un-routeable IP addresses to use for its `docker0` virtual bridge network, and the `docker` daemon will refuse to start up. In that case, you will have to make the bridge manually, with something like [this](https://github.com/moby/moby/issues/31546#issuecomment-284263284):

```
sudo brctl addbr docker0
sudo ip addr add 192.168.42.1/24 dev docker0
sudo ip link set dev docker0 up
ip addr show docker0
sudo systemctl restart docker
```

### Configuring RainLoop

When we started RainLoop, we didn't expose the container's port 8888 to the world; you can only access it from the computer it is running on. To do that, get ahold of the container's IP address:

```
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' rainloop
```

I got `172.17.0.3`, but you may get something different. You can then go to http://172.17.0.3:8888/?admin (substituting in the address you got), log in with the default credentials of `admin` and `12345`, and configure your new e-mail client:

1. Go to "Security" on the left and **set a new admin password**. Make sure to remember it.
2. Also under "Security", make sure to enable "Require verification of SSL certificate used (IMAP/SMTP)". I have no idea why this is off by default; it is essential that you not just hand your e-mail password over to people with self-signed certificates.
3. Under "Domains", make sure that your e-mail domain appears in the list of domains that can use RainLoop. By default, `gmail.com` is enabled already. Also, go into "Whitelist" and put your username (without `@gmail.com`) on the whitelist. This will mean that only you (and not every Gmail user) can use your RainLoop instance.
4. Under "Contacts", you should check "Enable contacts" and also "Allow contacts sync (with external CardDAV server)". This will allow you to have your Google contacts pre-populate when composing e-mail.

Once you've done the initial configuration, you can sign in on the main login page, http://172.17.0.3:8888/ (again substituting your container's IP if it is different), with your Gmail e-mail address and password. (If you are using 2-factor authentication, you will need an [app password](https://support.google.com/accounts/answer/185833?hl=en).) Then, once logged in, click on the person icon in the upper right, and select "Settings", so you can configure your user settings:

1. Under "Folders" on the left, hit "System Folders", and set "Spam" to "Do not use". This will prevent RainLoop nagging you about how many unread spam messages you have with a little badge.
2. Under "contacts" on the left, check "Enable remote synchronization". Enter `https://google.com` as the "Addressbook URL", and use your Gmail e-mail address and password as the "User" and "Password". This will make RainLoop periodically download and update your Google address book.

**Congratulations!** You now have a working e-mail client. If that is all you want, you can stop now. But if you want your client to start on boot and be accessible from anywhere, you can move on to...

## Using Docker Compose

[Docker Compose](https://docs.docker.com/compose/overview/) is a feature of Docker that allows multiple containers to be run together as an application, coordinated by a `docker-compose.yml` file. That file lists what container images to run as part of the application, what volume paths they should use, what ports each should expose, and how they should interact with each other. It also makes setting up Docker virtual networks pretty easy. Perhaps most importantly, **Docker Compose takes care of starting up all the containers on boot**; anything you set up will persist across reboots automatically, with no need for a systemd service or anything in `/etc/rc.local`.

If you don't have it already, you can install it on Ubuntu with:
```
sudo apt install docker-compose
```
The command will then be accessible as `docker-compose`.

If we want RainLoop to be accessible from the Internet, we're going to have to secure it with an SSL certificate. So in addition to the RainLoop container, we're going to add [Traefik](https://traefik.io/), a proxy which can sit in front of RainLoop and receive SSL connections. Traefik also has built-in support for automatically obtaining SSL certificates from [Let's Encrypt](https://letsencrypt.org/), without you having to do anything. The Docker image name is just `traefik`.

To get the SSL certificate and to make access from the Internet practical, we need a DNS name. You could go out and register a whole domain name, or you could use  For this I recommend [Affraid.org's FreeDNS service](https://freedns.afraid.org/), an alternative to commercial services like DynDNS, which has a wide selection of domains whose owners are willing to hand out free subdomains. To interface with it, we can use [ddclient](https://sourceforge.net/p/ddclient/wiki/Home/), a dynamic DNS client that supports several services. There are a few different Docker images for this tool, but I have selected `rycus86/ddclient`.

### Setting Up the Application

1. If you have been following along with the tutorial, Ctrl+C out of the running RainLoop that we started earlier.
2. Get your hostname set up at https://freedns.afraid.org/, or from wherever else you plan to obtain it.
3. If you are behind a firewall router, set up [port forwarding](https://superuser.com/questions/284051/what-is-port-forwarding-and-what-is-it-used-for) for ports 80 and 443 to the machine that will be hosting your application. Also make sure to open the ports in your system's firewall.
4. In the `webmail-host` directory, create two more folders to hold configuration and runtime data for the Traefik and ddclient containers:
    ```
    mkdir traefik
    mkdir ddclient
    ```
5. Make a file `ddclient/ddclient.conf` based on the following template:
    ```
    daemon=5m
    use=web, web=dyndns
    timeout=10
    syslog=no
    pid=/var/run/ddclient.pid
    ssl=yes

    server=freedns.afraid.org
    protocol=freedns
    login=YOUR_USER_HERE
    password=YOUR_PASSWORD_HERE
    YOUR_DOMAIN_HERE
    ```
Make sure to fill in `YOUR_USER_HERE`, `YOUR_PASSWORD_HERE`, and `YOUR_DOMAIN_HERE` with the information for the domain you are using, and change the `server` and `protocol` if you are using another dynamic DNS provider.
6. Mostly, Traefik is intended to Just Work without any configuration, and a lot of the things you can do with the config file can also be done with labels on Docker containers, if you start it with `--docker`. But we're going to make a config file for it anyway, in `traefik/traefik.toml`, using this template:
    ```
    debug = false

    logLevel = "ERROR"
    defaultEntryPoints = ["https","http"]

    [entryPoints]
      [entryPoints.http]
      address = ":80"
        [entryPoints.http.redirect]
        entryPoint = "https" # Redirect HTTP traffic to HTTPS
      [entryPoints.https]
      address = ":443"
      [entryPoints.https.tls]

    [retry]

    [docker]
    # Talk to Docker and set up proxying for containers we find
    endpoint = "unix:///var/run/docker.sock"
    domain = "YOUR_DOMAIN_HERE"
    watch = true
    exposedByDefault = false # But only containers that ask for it

    [acme]
    email = "YOUR_EMAIL_HERE"
    storage = "/etc/traefik/acme.json"
    entryPoint = "https"
    onHostRule = true
    [acme.httpChallenge]
      entryPoint = "http"
    ```
Make sure to replace `YOUR_DOMAIN_HERE` with the domain name that you are using, and `YOUR_EMAIL_HERE` with the e-mail you want Let's Encrypt to associate with your certificate.
7. Finally, make the `docker-compose.yml` file, using this template:
    ```
    version: '2'

    services:
      reverse-proxy:
        image: traefik
        ports:
          - "80:80"
          - "443:443"
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock:ro
          - ./traefik:/etc/traefik
        networks:
          - webmail-net
        depends_on:
          - ddclient
        restart: always # Restart even after underlying Docker host reboots

      rainloop:
        image: hardware/rainloop
        labels:
          - "traefik.enable=true"
          - "traefik.port=8888"
          - "traefik.frontend.rule=Host:YOUR_DOMAIN_HERE"
        volumes:
          - ./rainloop:/rainloop/data
        environment:
          - UID=1000
          - GID=1000
          - LOG_TO_STDOUT=true
        networks:
          - webmail-net
        restart: always

      ddclient:
        image: rycus86/ddclient
        command: --daemon=300 --ssl --debug
        volumes:
          - ./ddclient/ddclient.conf:/etc/ddclient.conf
        networks:
          - webmail-net
        restart: always

    networks:
      webmail-net:
        ipam:
          config:
            - subnet: 172.16.238.0/24
              gateway: 172.16.238.1
    ```
Make sure to replace `YOUR_DOMAIN_HERE` in the `traefik.frontend.rule` label on the `rainloop` container with the domain that you are using.

The `docker-compose.yml` file defines how the application fits together. Each "service" describes one of the containers we want, including the image it should be started from, the "volumes" (which expose host files to the container) that it should have access to, and the virtual network that it should be attached to. There are also "labels", which is how Traefik does most of its configuration, and which it reads via its access to `/var/run/docker.sock`. (Note that this access also means that the Traefik container isn't *really* contained; it can [escape its container](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/) even with the read-only access we give it.)

#### Adventures in Networking

We use compose file format version 2, and define explicitly the subnet that we want our virtual network to use (as only compose file version 2 allows), because if you are on a VPN or otherwise have routes covering private IP space, Docker can't come up with a free block of private IP addresses to use on its own for the virtual network. So we have to tell Docker explicitly that we want it to use this subnet, even if the system thinks it has a route to it elsewhere.

Because I want my Docker containers to send their outbound traffic over my eth0 interface, instead of through any tunnels, I had to create an alternative routing table and direct traffic from the virtual network to use it. Also, because Linux blocks any traffic that isn't coming *from* where it would route traffic *to* for that traffic's source address, I had to turn down the [reverse path filter](https://www.slashroot.in/linux-kernel-rpfilter-settings-reverse-path-filtering). I added the following to /etc/rc.local:

```
# Set up this one Docker subnet as exempt from VPN tunneling, and use the router at 10.1.0.1
ip route add default dev eth0 via 10.1.0.1 table 1001
ip rule add fwmark 1001 lookup 1001
iptables --wait -t mangle -A PREROUTING -s 172.16.238.0/24 -j MARK --set-mark 1001
# And don't require packets to come back from the best route for them, to make that work both ways
echo 2 >/proc/sys/net/ipv4/conf/eth0/rp_filter
```

This works by using the `iptables` firewall to "mark" traffic from the Docker subnet with a number (1001), setting up an additional routing table (table number 1001) with just a default route in it, and saying that we want to use table 1001 to route traffic with mark 1001. Then we turn down the reverse path filter, so that traffic arriving at eth0 from the Internet will be accepted, even if we have a better route to the Internet over another interface.

If you aren't using a VPN or tunnel, or your incoming traffic comes over that tunnel, you won't have to mess around with any of this.

### Running the Application

Once you have your `webmail-host/docker-compose.yml` written, and the new `webmail-host/ddclient/` and  `webmail-host/traefik/` directories (along with a `webmail-host/rainloop/` directory if you don't have one from the first part of the tutorial), you can start up your application from the `webmail-host/` directory with:

```
docker-compose up
```

This will bring up all the containers in the application, in dependency order, and keep you attached to their output, so you can see if any of them complain. If everything goes right, you should see something like:

```
Creating network "webmailhost_webmail-net" with the default driver
Creating webmailhost_rainloop_1 ...
Creating webmailhost_ddclient_1 ...
Creating webmailhost_rainloop_1
Creating webmailhost_ddclient_1 ... done
Creating webmailhost_reverse-proxy_1 ...
Creating webmailhost_reverse-proxy_1 ... done
Attaching to webmailhost_rainloop_1, webmailhost_ddclient_1, webmailhost_reverse-proxy_1
rainloop_1       | [INFO] Logging to stdout activated
```

If things go wrong (for example, because an SSL certificate can't be obtained for your domain), you will see other messages in the console.

Check to make sure that your service is available at the domain you are using, and that it is using a valid SSL certificate. Note that it can take a couple minutes for the certificate to be issued.

Whether you are happy or unhappy with the results, the next step is to stop the application with `Ctrl+C`, either to tinker with the configuration or to set it up to run on its own.

#### Set and Forget

Once you are happy with your configuration, you will want to start up your application in "detached" mode, so you can have it run without your terminal window. To do this, just run (from the `webmail-host/` directory):

```
docker-compose up -d
```

After the application starts up, it will run in the background forever, restarting itself after reboots. To stop it again, in order to change the configuration or because you no longer want to have it, you have to run (again from the `webmail-host/` directory):

```
docker-compose down
```

## Conclusion

By assembling RainLoop, Traefik, and ddclient using Docker Compose, you can create a modern webmail solution that can replace both the Gmail web interface and Mozilla Thunderbird while combining the best aspects of both. Moreover, since Traefik supports [routing requests for many services presented at different hostnames and paths](https://docs.traefik.io/basics/), and Docker is the current standard for server software distribution, it would be easy to extend this basic structure with additional self-hosted services.

![A diagram showing the three containers, their presence in the virtual network, and how traffic goes from the Internet through Traefik to Rainloop, and then back the way it came. Also shown is ddclient making its DNS updates, and the fact that traffic between the Internet and Traefik is secure.](/images/010/diagram.png)


text:
package org.jboss.resteasy.test.providers.plain;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.logging.Logger;
import org.jboss.resteasy.test.providers.plain.resource.DefaultNumberWriterCustom;
import org.jboss.resteasy.test.providers.plain.resource.DefaultNumberWriterResource;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

/**
 * @tpSubChapter Plain provider
 * @tpChapter Integration tests
 * @tpTestCaseDetails Test for DefaultNumberWriter provider.
 *                    Regression test for partial fix for JBEAP-2847.
 * @tpSince RESTEasy 3.0.16
 */
@RunWith(Arquillian.class)
public class DefaultNumberWriterTest {
    private static Logger logger = Logger.getLogger(DefaultNumberWriterTest.class);
    private static final String WRONG_RESPONSE_ERROR_MSG = "Response contains wrong response";
    private static final String WRONG_PROVIDER_USED_ERROR_MSG = "Wrong provider was used";

    @Deployment
    public static Archive<?> deploy() {
        WebArchive war = TestUtil.prepareArchive(DefaultNumberWriterTest.class.getSimpleName());
        war.addClasses(TestUtil.class, PortProviderUtil.class);
        return TestUtil.finishContainerPrepare(war, null, DefaultNumberWriterResource.class,
                DefaultNumberWriterCustom.class);
    }

    private String generateURL(String path) {
        return PortProviderUtil.generateURL(path, DefaultNumberWriterTest.class.getSimpleName());
    }

    /**
     * @tpTestDetails Tests Byte object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testByte() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Byte")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests byte primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testBytePrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/byte")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests Double object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testDouble() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Double")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123.4", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests double primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testDoublePrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/double")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123.4", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests Float object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testFloat() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Float")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123.4", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests float primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testFloatPrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/float")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123.4", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests Integer object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testInteger() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Integer")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests integer primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testIntegerPrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/integer")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests Long object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testLong() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Long")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests long primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testLongPrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/long")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests Short object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testShort() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/Short")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests short primitive
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testShortPrimitive() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/short")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests BigDecimal object
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testBigDecimal() throws Exception {
        Client client = ClientBuilder.newClient();
        Response response = client.target(generateURL("/test/bigDecimal")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }

    /**
     * @tpTestDetails Tests BigDecimal object with register custom provider on client
     * @tpSince RESTEasy 3.0.16
     */
    @Test
    public void testProviderGetsUsed() throws Exception {
        Client client = ClientBuilder.newClient();
        client.register(DefaultNumberWriterCustom.class);
        Response response = client.target(generateURL("/test/bigDecimal")).request().get();
        response.bufferEntity();
        logger.info(response.readEntity(String.class));
        Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
        Assert.assertEquals(WRONG_RESPONSE_ERROR_MSG, "123", response.getEntity());
        Assert.assertTrue(WRONG_PROVIDER_USED_ERROR_MSG, DefaultNumberWriterCustom.used);
    }
}


text:
The EventDispatcherExtensions provides a Bridge to the [Symfony EventDispatcher Component](http://symfony.com/doc/current/components/event_dispatcher/index.html). The EventDispatcherComponent allows you to add behaviour without changing Payum.

## Enable the EventDispatcherExtension

```php
use Payum\Core\Bridge\Symfony\Extension\EventDispatcherExtension;

$gateway->addExtension(
    new EventDispatcherExtension($eventDispatcher)
);
```

## Listen to an Event

```php
use Payum\Core\Bridge\Symfony\Event\ExecuteEvent;
use Payum\Core\Bridge\Symfony\PayumEvents;

$eventDispatcher->addListener(
    PayumEvents::GATEWAY_EXECUTE,
    function(ExecuteEvent $event) {
        // do something
    }
);
```

| Name | `PayumEvents` Constant | Argument passed to the listener |
| --- | --- | ---|
| payum.gateway.pre_execute | `PayumEvents::GATEWAY_PRE_EXECUTE` | `ExecuteEvent` |
| payum.gateway.execute | `PayumEvents::GATEWAY_EXECUTE` | `ExecuteEvent` |
| payum.gateway.post_execute | `PayumEvents::GATEWAY_POST_EXECUTE` | `ExecuteEvent` |

## Benefit with PayumBundle

If you use Symfony Full-Stack Framework and the PayumBundle you can add the EventDispatcherExtension via Configuration:

```yaml
services:
    app.payum.extension.event_dispatcher:
        class: Payum\Core\Bridge\Symfony\Extension\EventDispatcherExtension
        arguments: ["@event_dispatcher"]
        tags:
            - { name: payum.extension, all: true, prepend: false }
```

And add the listener:

```yaml
services:
    app.payum.listener.render_template:
        class: AppBundle\EventListener\RenderTemplateListener
        tags:
            - { name: kernel.event_listener, event: payum.gateway.execute }
```


text:
"""Sweep definition for umbrella_distract experiment."""

from bsuite.experiments.umbrella_length import sweep as umbrella_length_sweep

NUM_EPISODES = umbrella_length_sweep.NUM_EPISODES

_log_spaced = []
_log_spaced.extend(range(1, 11))
_log_spaced.extend([12, 14, 17, 20, 25])
_log_spaced.extend(range(30, 105, 10))

SETTINGS = tuple({'n_distractor': n} for n in _log_spaced)
TAGS = ('credit_assignment', 'noise')