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

namespace VkNet.Model.RequestParams
{
	/// <summary>
	/// Параметр для добавления / редактирования товара
	/// </summary>
	public struct MarketProductParams
	{
		/// <summary>
		/// Параметр для добавления / редактирования товара
		/// </summary>
		public MarketProductParams(bool gog = false)
		{
			OwnerId = 0;
			Name = null;
			Description = null;
			CategoryId = 0;
			Price = 0;
			Deleted = false;
			MainPhotoId = 0;
			PhotoIds = null;
			ItemId = null;
		}

		/// <summary>
		/// Идентификатор владельца товара. Обратите внимание, идентификатор сообщества в параметре owner_id необходимо указывать со знаком "-" — например, owner_id=-1 соответствует идентификатору сообщества ВКонтакте API (club1)  целое число, обязательный параметр (целое число, обязательный параметр).
		/// </summary>
		public long OwnerId
		{
			get; set;
		}

		/// <summary>
		/// Идентификатор товара.
		/// </summary>
		public long? ItemId { get; set; }

		/// <summary>
		/// Название товара. строка, минимальная длина 4, максимальная длина 100, обязательный параметр (строка, минимальная длина 4, максимальная длина 100, обязательный параметр).
		/// </summary>
		public string Name
		{
			get; set;
		}

		/// <summary>
		/// Описание товара. строка, минимальная длина 10, обязательный параметр (строка, минимальная длина 10, обязательный параметр).
		/// </summary>
		public string Description
		{
			get; set;
		}

		/// <summary>
		/// Идентификатор категории товара. положительное число, обязательный параметр (положительное число, обязательный параметр).
		/// </summary>
		public long CategoryId
		{
			get; set;
		}

		/// <summary>
		/// Цена товара. дробное число, обязательный параметр, минимальное значение 0.01 (дробное число, обязательный параметр, минимальное значение 0.01).
		/// </summary>
		public decimal Price
		{
			get; set;
		}

		/// <summary>
		/// Статус товара (1 — товар удален, 0 — товар не удален). флаг, может принимать значения 1 или 0 (флаг, может принимать значения 1 или 0).
		/// </summary>
		public bool Deleted
		{
			get; set;
		}

		/// <summary>
		/// Идентификатор фотографии обложки товара. положительное число, обязательный параметр (положительное число, обязательный параметр).
		/// </summary>
		public long MainPhotoId
		{
			get; set;
		}

		/// <summary>
		/// Идентификаторы дополнительных фотографий товара. список положительных чисел, разделенных запятыми, количество элементов должно составлять не более 4 (список положительных чисел, разделенных запятыми, количество элементов должно составлять не более 4).
		/// </summary>
		public IEnumerable<long> PhotoIds
		{
			get; set;
		}

		/// <summary>
		/// Привести к типу VkParameters.
		/// </summary>
		/// <param name="p">Параметры.</param>
		/// <returns></returns>
		internal static VkParameters ToVkParameters(MarketProductParams p)
		{
			var parameters = new VkParameters {
				{ "owner_id", p.OwnerId },
				{ "item_id", p.ItemId},
				{ "name", p.Name },
				{ "description", p.Description },
				{ "category_id", p.CategoryId },
				{ "price", p.Price },
				{ "deleted", p.Deleted },
				{ "main_photo_id", p.MainPhotoId },
				{ "photo_ids", p.PhotoIds }
			};

			return parameters;
		}
	}
}


text:
import React from 'react'
import { cls } from '../../utils/libs.js'
import './styles.less'

export default class Voice extends React.Component {
	// constructor() {
	// 	super();
	// 	this.state = {
	// 		voiceIcon: 'icon-shengyin',
	// 	}
	// }

	changeVoice = (e) => {
		let voiceProgress = this.refs.voiceProgress,
			mousePosition = e.clientX,
			componentLeft = voiceProgress.getBoundingClientRect().left,
			componentWidth = voiceProgress.clientWidth,
			progress = (mousePosition - componentLeft)/componentWidth
			this.props.voiceChangeHandler(progress) && this.props.voiceChangeHandler(progress)
	}
	render() {
		let { progress, voiceIcon, changeVoiceIcon } = this.props
		return (

				<div className= {cls("iconfont", "voiceLogo", `${voiceIcon}`)} onClick = {changeVoiceIcon}>

					<div className="voice" style={{width:`${progress}%` }}>

		)
	}
}

redpajama_set_name: RedPajamaGithub


text:
package utybo.mod.epc2eu.common.utils;

public class EpcTranslators
{
	/**
	 * Returns a full list of translations
	 *
	 * @param i
	 *            Untranslated value
	 * @param el
	 *            The type (EPC, EU or MJ) provided
	 * @return An int array with EPC, EU, and MJ translations
	 * @author utybo
	 */
	public static int[] getTranslationListForValue(int i, EnumEnergyList el)
	{
		if(el == EnumEnergyList.EPC)
		{
			return new int[] {i, Epc2euTranslator.translateEPCToEU(i), Epc2mjTranslator.translateEPCToMJ(i)};
		}
		if(el == EnumEnergyList.EU)
		{
			return new int[] {Epc2euTranslator.translateEUToEPC(i), i, Epc2mjTranslator.translateEPCToMJ(Epc2euTranslator.translateEUToEPC(i))};
		}
		if(el == EnumEnergyList.MJ)
		{
			return new int[] {Epc2euTranslator.translateEPCToEU(Epc2mjTranslator.translateMJToEPC(i)), Epc2mjTranslator.translateMJToEPC(i), i};
		}
		return null;
	}

	/**
	 * (Thanks to the other Energy Transformer devs (sevenno07 &
	 * Superloup10), I was able to make a fair translation!)

	 *

	 * EPC <==> EU
	 *
	 * @author utybo, sevenno07, Superloup10
	 *
	 */
	public static class Epc2euTranslator
	{
		public static int translateEUToEPC(int i)
		{
			return i / 1098;
		}

		public static int translateEPCToEU(int i)
		{
			return i * 1098;
		}
	}

	/**
	 * EPC <==> MJ
	 *
	 * @author utybo
	 *
	 */
	public static class Epc2mjTranslator
	{
		public static int translateMJToEPC(int i)
		{
			return i / 1600;
		}

		public static int translateEPCToMJ(int i)
		{
			return i * 1600;
		}
	}
}


text:
.tasks-view__wrapper {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.tasks-view__tasks-wrapper {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.tasks-view__link-wrapper {
    width: 10%;
    display: flex;
    justify-content: center;
}

.tasks-view__description-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.shmily.tjz.swap.SpecialShowActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFF"
    android:scrollbars="none"
    >

<LinearLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
  >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center"
        android:textColor="#FFF"
        android:background="@color/colorPrimary"
        android:id="@+id/specoal_show_title"
        />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/specoal_show_image"

        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:gravity="center"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textSize="11dp"
        android:layout_marginTop="10dp"
        android:text="Boost technology is everywhere—but we're not complaining. What began as a simple technology for runners quickly became a brand staple for Adidas. Add to your collection and see the latest line of sneakers with Boost technology."
        android:id="@+id/specoal_show_detail"

        />
    <RelativeLayout
        android:layout_marginTop="10dp"

        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
        android:id="@+id/specoal_show_recy"

        >

</android.support.v7.widget.RecyclerView>
    </RelativeLayout>

</LinearLayout>
</ScrollView>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.min.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/styles.css">

Albums

Artists

Genres

Artists


text:
package com.lightbend.lagom.javadsl.api;

import akka.japi.Pair;
import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.transport.RequestHeader;
import com.lightbend.lagom.javadsl.api.transport.ResponseHeader;

import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * A service call for an entity.
 *
 * A service call has a request and a response entity. Either entity may be NotUsed, if there is no entity associated
 * with the call. They may also be an Akka streams Source, in situations where the endpoint serves a stream. In all
 * other cases, the entities will be considered "strict" entities, that is, they will be parsed into memory, eg,
 * using json.
 */
@FunctionalInterface
public interface ServiceCall<Request, Response> {

    /**
     * Invoke the service call.
     *
     * @param request The request entity.
     * @return A future of the response entity.
     */
    CompletionStage<Response> invoke(Request request);

    /**
     * Invoke the service call with unit id argument and a unit request message.
     *
     * This should only be used when the request message is NotUsed.
     *
     * @return A future of the response entity.
     */
    default CompletionStage<Response> invoke() {
        return this.invoke((Request) NotUsed.getInstance());
    }

    /**
     * Make any modifications necessary to the request header.
     *
     * For client service calls, this gives clients an opportunity to add custom headers and/or modify the request in
     * some way before it is made.  The passed in handler is applied before the header transformers
     * configured for the descriptor/endpoint are applied.
     *
     * For server implementations of service calls, this will be invoked by the server in order to supply the request
     * header.  A new service call can then be returned that uses the header.  The header passed in to the handler by
     * the service call can be anything, it will be ignored - {@link RequestHeader#DEFAULT} exists for this
     * purpose.  Generally, server implementations should not implement this method directly, rather, they should use
     * <tt>ServerServiceCall</tt>, which provides an appropriate implementation.
     *
     * @param handler A function that takes in the request header representing the request, and transforms it.
     * @return A service call that will use the given handler.
     */
    default ServiceCall<Request, Response> handleRequestHeader(Function<RequestHeader, RequestHeader> handler) {
        // Default implementation. For client service calls, this is overridden by the implementation to do something
        // with the handler.
        return this;
    }

    /**
     * Transform the response using the given function that takes the response header and the response.
     *
     * For client service calls, this gives clients an opportunity to inspect the response headers and status code.
     * The passed in handler is applied after the header transformers configured for the descriptor/endpoint are
     * applied.
     *
     * For server implementations of service calls, this will be invoked by the server in order to give the service
     * call an opportunity to supply the response header when it supplies the response, but only if the underlying
     * transport supports sending a response header.  Generally, server implementations should not implement this
     * method directly, rather, they should use <tt>ServerServiceCall</tt>, which provides an appropriate
     * implementation.
     *
     * @param handler The handler.
     * @return A service call that uses the given handler.
     */
    default <T> ServiceCall<Request, T> handleResponseHeader(BiFunction<ResponseHeader, Response, T> handler) {
        // Default implementation. For client service calls, this is overridden by the implementation to do something
        // with the handler.
        return request -> invoke(request).thenApply(response -> handler.apply(ResponseHeader.OK, response));
    }

    /**
     * Allow handling of the response header.
     *
     * This converts the service call to one that returns both the response header and the response message.
     *
     * This is simply a convenience method for invoking handleResponseHeader(Pair::create).
     *
     * @return The a service call that returns the response header and the response message.
     */
    default ServiceCall<Request, Pair<ResponseHeader, Response>> withResponseHeader() {
        return handleResponseHeader(Pair::create);
    }
}


text:
import isProjectExportInProgress from './isProjectExportInProgress';

export default function isClassroomExportInProgress(state) {
  return isProjectExportInProgress(state, 'classroom');
}


text:
from flask import (
    Flask,
)
from redis import Redis

app = Flask('microlathe')
redis = Redis()

# stolen from http://stackoverflow.com/questions/10999990/
class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):

        from cStringIO import StringIO
        length = environ.get('CONTENT_LENGTH', '0')
        length = 0 if length == '' else int(length)

        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        environ['wsgi.input'] = StringIO(body)

        # Call the wrapped application
        app_iter = self.application(
            environ, self._sr_callback(start_response))

        # Return modified response
        return app_iter

    def _sr_callback(self, start_response):
        def callback(status, headers, exc_info=None):

            # Call upstream start_response
            start_response(status, headers, exc_info)
        return callback

app.wsgi_app = WSGICopyBody(app.wsgi_app)

import views


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import com.microsoft.azure.arm.collection.SupportsCreating;
import rx.Completable;
import rx.Observable;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationFabricsInner;
import com.microsoft.azure.arm.model.HasInner;

/**
 * Type representing ReplicationFabrics.
 */
public interface ReplicationFabrics extends SupportsCreating<Fabric.DefinitionStages.Blank>, HasInner<ReplicationFabricsInner> {
    /**
     * Checks the consistency of the ASR fabric.
     * The operation to perform a consistency check on the fabric.
     *
     * @param fabricName Fabric name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<Fabric> checkConsistencyAsync(String fabricName);

    /**
     * Migrates the site to AAD.
     * The operation to migrate an Azure Site Recovery fabric to AAD.
     *
     * @param fabricName ASR fabric to migrate.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable migrateToAadAsync(String fabricName);

    /**
     * Perform failover of the process server.
     * The operation to move replications from a process server to another process server.
     *
     * @param fabricName The name of the fabric containing the process server.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<Fabric> reassociateGatewayAsync(String fabricName);

    /**
     * Deletes the site.
     * The operation to delete or remove an Azure Site Recovery fabric.
     *
     * @param fabricName ASR fabric to delete
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable deleteAsync(String fabricName);

    /**
     * Renews certificate for the fabric.
     * Renews the connection certificate for the ASR replication fabric.
     *
     * @param fabricName fabric name to renew certs for.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<Fabric> renewCertificateAsync(String fabricName);

    /**
     * Gets the details of an ASR fabric.
     * Gets the details of an Azure Site Recovery fabric.
     *
     * @param fabricName Fabric name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<Fabric> getAsync(String fabricName);

    /**
     * Gets the list of ASR fabrics.
     * Gets a list of the Azure Site Recovery fabrics in the vault.
     *
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<Fabric> listAsync();

    /**
     * Purges the site.
     * The operation to purge(force delete) an Azure Site Recovery fabric.
     *
     * @param fabricName ASR fabric to purge.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable purgeAsync(String fabricName);

}


text:
package xyz.cafeconleche.web.chica.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;

import xyz.cafeconleche.web.chica.dao.SecurityDao;
import xyz.cafeconleche.web.chica.service.SocialSecurityService;

@Service("socialSecurityService")
public class SocialSecurityServicePojoImpl implements SocialSecurityService {

	@Autowired
	private SecurityDao securityDao;

	@Override
	public SocialUserDetails loadUserByUserId(String username) throws UsernameNotFoundException {
		return securityDao.loadSocialUserByUsername(username);
	}

}


text:
package ace.scorer;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import ace.tf.StopWordSet;
import ace.tf.TFGenerator;
import ace.util.Token;
import ace.util.Concept;

/*
 * TFScorer
 *
 * @author pramirez
 *
*/

public class TFScorer implements IScorer {
   public TFScorer() {}

   public Map score(List tokens, StopWordSet stopWords) {
      TFGenerator tfg = new TFGenerator(tokens, stopWords);
      Map frequencies = tfg.getTF();
      Map terms = new HashMap();
      Map concepts = new HashMap();

      for (Iterator i = tokens.iterator(); i.hasNext();) {
         Token t = (Token) i.next();
         List toks = (List) terms.get(t.getTerm().toUpperCase());
         if (toks == null) {
            toks = new ArrayList();
            terms.put(t.getTerm().toUpperCase(), toks);
         }
         toks.add(t);
      }
      //System.out.println("Frequencies: " + frequencies);
      for (Iterator i = frequencies.keySet().iterator(); i.hasNext();){
         String term = (String) i.next();
         Double ranking = (Double) frequencies.get(term); //Should be upper case Change in algorithm too
         List toks = (List) terms.get(term.toUpperCase());
         concepts.put(term.toUpperCase(), new Concept(term, ranking, toks)); //Changed toUpper
      }

      return concepts;
   }

}


text:
package pcap

import (
	"fmt"
	"io"
	"log"
	"testing"

	"github.com/packetbeat/gopacket"
	"github.com/packetbeat/gopacket/layers"
)

func TestPcapFileRead(t *testing.T) {
	for _, file := range []struct {
		filename       string
		num            int
		expectedLayers []gopacket.LayerType
	}{
		{"test_loopback.pcap",
			24,
			[]gopacket.LayerType{
				layers.LayerTypeLoopback,
				layers.LayerTypeIPv6,
				layers.LayerTypeTCP,
			},
		},
		{"test_ethernet.pcap",
			16,
			[]gopacket.LayerType{
				layers.LayerTypeEthernet,
				layers.LayerTypeIPv4,
				layers.LayerTypeTCP,
			},
		},
		{"test_dns.pcap",
			10,
			[]gopacket.LayerType{
				layers.LayerTypeEthernet,
				layers.LayerTypeIPv4,
				layers.LayerTypeUDP,
				layers.LayerTypeDNS,
			},
		},
	} {
		t.Logf("\n\n\n\nProcessing file %s\n\n\n\n", file.filename)

		packets := []gopacket.Packet{}
		if handle, err := OpenOffline(file.filename); err != nil {
			t.Fatal(err)
		} else {
			packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
			for packet := range packetSource.Packets() {
				packets = append(packets, packet)
			}
		}
		if len(packets) != file.num {
			t.Fatal("Incorrect number of packets, want", file.num, "got", len(packets))
		}
		for i, p := range packets {
			t.Log(p.Dump())
			for _, layertype := range file.expectedLayers {
				if p.Layer(layertype) == nil {
					t.Fatal("Packet", i, "has no layer type\n%s", layertype, p.Dump())
				}
			}
		}
	}
}

func TestBPF(t *testing.T) {
	handle, err := OpenOffline("test_ethernet.pcap")
	if err != nil {
		t.Fatal(err)
	}

	for _, expected := range []struct {
		expr   string
		Error  bool
		Result bool
	}{
		{"foobar", true, false},
		{"tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)", false, true},
		{"tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-ack", false, true},
		{"udp", false, false},
	} {
		data, ci, err := handle.ReadPacketData()
		if err != nil {
			t.Fatal(err)
		}
		t.Log("Testing filter", expected.expr)
		if bpf, err := handle.NewBPF(expected.expr); err != nil {
			if !expected.Error {
				t.Error(err, "while compiling filter was unexpected")
			}
		} else if expected.Error {
			t.Error("expected error but didn't see one")
		} else if matches := bpf.Matches(ci, data); matches != expected.Result {
			t.Error("Filter result was", matches, "but should be", expected.Result)
		}
	}
}

func ExampleBPF() {
	handle, err := OpenOffline("test_ethernet.pcap")
	if err != nil {
		log.Fatal(err)
	}
	synack, err := handle.NewBPF("tcp[tcpflags] & (tcp-syn|tcp-ack) == (tcp-syn|tcp-ack)")
	if err != nil {
		log.Fatal(err)
	}
	syn, err := handle.NewBPF("tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn")
	if err != nil {
		log.Fatal(err)
	}
	for {
		data, ci, err := handle.ReadPacketData()
		switch {
		case err == io.EOF:
			return
		case err != nil:
			log.Fatal(err)
		case synack.Matches(ci, data):
			fmt.Println("SYN/ACK packet")
		case syn.Matches(ci, data):
			fmt.Println("SYN packet")
		default:
			fmt.Println("SYN flag not set")
		}
	}
	// Output:
	// SYN packet
	// SYN/ACK packet
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
	// SYN flag not set
}


text:
<?php

namespace Symfony\Component\PropertyAccess;

/**
 * Traverses a property path and provides additional methods to find out
 * information about the current element.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class PropertyPathIterator extends \ArrayIterator implements PropertyPathIteratorInterface
{
    /**
     * The traversed property path.
     *
     * @var PropertyPathInterface
     */
    protected $path;

    /**
     * @param PropertyPathInterface $path The property path to traverse
     */
    public function __construct(PropertyPathInterface $path)
    {
        parent::__construct($path->getElements());

        $this->path = $path;
    }

    /**
     * {@inheritdoc}
     */
    public function isIndex()
    {
        return $this->path->isIndex($this->key());
    }

    /**
     * {@inheritdoc}
     */
    public function isProperty()
    {
        return $this->path->isProperty($this->key());
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebsitePanel.Portal {

    public partial class ServersEditWebPlatformInstaller {

        /// <summary>
        /// asyncTasks control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;

        /// <summary>
        /// ServerHeaderControl1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.ServerHeaderControl ServerHeaderControl1;

        /// <summary>
        /// CheckLoadUserProfilePanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel CheckLoadUserProfilePanel;

        /// <summary>
        /// EnableLoadUserProfileButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button EnableLoadUserProfileButton;

        /// <summary>
        /// SearchPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel SearchPanel;

        /// <summary>
        /// keywordsList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList keywordsList;

        /// <summary>
        /// searchBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox searchBox;

        /// <summary>
        /// ProductSearchGo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ImageButton ProductSearchGo;

        /// <summary>
        /// InstallButtons2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstallButtons2;

        /// <summary>
        /// btnInstall2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnInstall2;

        /// <summary>
        /// btnCancel2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCancel2;

        /// <summary>
        /// ProductsPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel ProductsPanel;

        /// <summary>
        /// gvWpiProducts control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView gvWpiProducts;

        /// <summary>
        /// InstallButtons1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstallButtons1;

        /// <summary>
        /// btnInstall1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnInstall1;

        /// <summary>
        /// btnCancel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCancel1;

        /// <summary>
        /// NoProductsSelectedPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel NoProductsSelectedPanel;

        /// <summary>
        /// NoProductsBackButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button NoProductsBackButton;

        /// <summary>
        /// InstallPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel InstallPanel;

        /// <summary>
        /// gvWpiInstall control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView gvWpiInstall;

        /// <summary>
        /// AceptDEclineButtons control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl AceptDEclineButtons;

        /// <summary>
        /// btnAccept control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnAccept;

        /// <summary>
        /// btnDecline control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnDecline;

        /// <summary>
        /// btnCancel3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCancel3;

        /// <summary>
        /// ProgressPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel ProgressPanel;

        /// <summary>
        /// ProgressTimer control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.Timer ProgressTimer;

        /// <summary>
        /// ProgressMessagePanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel ProgressMessagePanel;

        /// <summary>
        /// ProgressAnimation control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Image ProgressAnimation;

        /// <summary>
        /// ProgressMessage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label ProgressMessage;

        /// <summary>
        /// CancelInstall control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button CancelInstall;

        /// <summary>
        /// InstallCompletedPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel InstallCompletedPanel;

        /// <summary>
        /// LabelInstallationSuccess control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelInstallationSuccess;

        /// <summary>
        /// InstalledProductsList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.BulletedList InstalledProductsList;

        /// <summary>
        /// LabelInstallationFailed control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelInstallationFailed;

        /// <summary>
        /// ShowLogsButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ShowLogsButton;

        /// <summary>
        /// WpiLogsPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel WpiLogsPanel;

        /// <summary>
        /// WpiLogsPre control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl WpiLogsPre;

        /// <summary>
        /// BackToGalleryButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button BackToGalleryButton;

        /// <summary>
        /// btnBackToServer control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnBackToServer;
    }
}


text:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using Android.Graphics;
using System.Net;
using System.Net.Http;

namespace RealEstateXamarinAndroidDemo
{
    [Activity(Label = "RealEstateXamarinAndroidDemo", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        // Below is a query key as well as a sample search service that you are free to use for demo or learning purposes
        public static string AzureSearchApiKey = "F1F01D9405EF2EE6188891C7298D7390";
        public static string SearchServiceName = "realestate";
        public static string AzureSuggestUrl = "/indexes/listings/docs/suggest?suggesterName=sg&$top=15&search=";
        public static string AzureSearchUrl = "/indexes/listings/docs?search=";
        private static Uri _serviceUri;
        private static HttpClient _httpClient;

        public static List<ListListing> ListingsForList;
        public static string StoredSearchQuery;

        public static int maxPage;
        public static int currentPage;

        public static int filterMinBeds;
        public static int filterMaxBeds;
        public static int filterMinBaths;
        public static int filterMaxBaths;
        public static bool filterShowForSale;
        public static bool filterShowPending;
        public static bool filterShowSold;

        protected async override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            ConfigureMainLayout();

            // Initialize the http client
            _serviceUri = new Uri("https://" + SearchServiceName + ".search.windows.net");
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("api-key", AzureSearchApiKey);

            currentPage = 0;

            // Reset the filters
            filterMinBeds = 0;
            filterMaxBeds = 6;
            filterMinBaths = 0;
            filterMaxBaths = 6;
            filterShowForSale = true;
            filterShowPending = true;
            filterShowSold = true;

            //Perform a test suggest to load HTTP client
            await ExecSuggest("seattle");
        }

        private async void ConfigureMainLayout()
        {
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            FindViewById<Button>(Resource.Id.buttonSearch).Click += SearchButton_Click;

            AutoCompleteTextView SearchText = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteSearchTextView);
            SearchText.TextChanged += SearchText_TextChanged;
            SearchText.AfterTextChanged += SearchText_AfterTextChanged;

        }

        private void SearchText_AfterTextChanged(object sender, Android.Text.AfterTextChangedEventArgs e)
        {
            AutoCompleteTextView SearchText = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteSearchTextView);
            if (!SearchText.IsPopupShowing && SearchText.Text.Length > 0)
            {
                SearchText.ShowDropDown();
            }
        }

        private async void SearchText_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            // As the text changes call Azure Search /suggest to handle typeahead
            try
            {
                // Handle type ahead search by executing /suggest API call to Azure Search
                string q = e.Text.ToString();
                if (q.Length > 2)
                {
                    List<string> execSuggest = await ExecSuggest(q);
                    var autoCompleteOptions = execSuggest.ToArray();
                    ArrayAdapter autoCompleteAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleDropDownItem1Line, autoCompleteOptions);
                    AutoCompleteTextView SearchText = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteSearchTextView);
                    SearchText.Adapter = autoCompleteAdapter;
                }
            }
            catch
            {
            }
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            AutoCompleteTextView SearchText = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteSearchTextView);
            ExecListingsSearch(SearchText.Text);
        }

        private int ExecListingsSearch(string q = null, bool countOnly = false)
        {
            // Execute a search using the supplied text and apply the results to a new listings list page
            string url = _serviceUri + AzureSearchUrl + "*";
            if (q != "")
            {
                url = _serviceUri + AzureSearchUrl + q;
                StoredSearchQuery = q;
            }
            // Append the count request
            url += "&$count=true";
            if (countOnly)  // Don't get results
                url += "&$top=0";
            else
                url += "&$top=10";

            // Set the page
            url += "&$skip=" + currentPage*10;

            // Append the filter
            url += "&$filter=beds ge " + filterMinBeds + " and beds le " + filterMaxBeds +
                " and baths ge " + filterMinBaths + " and baths le " + filterMaxBaths;

            // Determing the status filter
            string statusFilter = string.Empty;
            if ((filterShowForSale) && (filterShowPending) && (filterShowSold))
                statusFilter = " and (status eq 'active' or status eq 'pending' or status eq 'sold')";
            else if (!(filterShowForSale) && (filterShowPending) && (filterShowSold))
                statusFilter = " and (status eq 'pending' or status eq 'sold')";
            else if ((filterShowForSale) && !(filterShowPending) && (filterShowSold))
                statusFilter = " and (status eq 'active' or status eq 'sold')";
            else if ((filterShowForSale) && (filterShowPending) && !(filterShowSold))
                statusFilter = " and (status eq 'active' or status eq 'pending')";
            else if ((filterShowForSale) && !(filterShowPending) && !(filterShowSold))
                statusFilter = " and (status eq 'active')";
            else if (!(filterShowForSale) && !(filterShowPending) && (filterShowSold))
                statusFilter = " and (status eq 'sold')";
            else if (!(filterShowForSale) && (filterShowPending) && !(filterShowSold))
                statusFilter = " and (status eq 'pending')";
            else
                statusFilter = " and status eq 'noresults'";
            url += statusFilter;

            Uri uri = new Uri(url);
            HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
            AzureSearchHelper.EnsureSuccessfulSearchResponse(response);
            dynamic result = AzureSearchHelper.DeserializeJson<dynamic>(response.Content.ReadAsStringAsync().Result);

            JObject jsonObj = JObject.Parse(result.ToString());

            if (countOnly == false)
            {
                ListingsForList = new List<ListListing>(); ;

                foreach (var item in jsonObj["value"])
                {
                    ListListing ll = new ListListing();
                    ll.ImageUrl = item["thumbnail"].ToString();
                    string price = "$" + Convert.ToInt32(item["price"].ToString()).ToString("#,##0");
                    ll.MainText = price + " Beds: " + item["beds"].ToString() +
                        " Baths: " + item["baths"].ToString() +
                        " Sq Ft.: " + Convert.ToInt32(item["sqft"].ToString()).ToString("#,##0");

                    ll.Id = item["listingId"].ToString();
                    // build up the address
                    string address = string.Empty;
                    if (item["number"] != null)
                        address += item["number"].ToString() + " ";
                    if (item["street"] != null)
                        address += item["street"].ToString() + " ";
                    if (item["city"] != null)
                        address += item["city"].ToString() + " ";
                    if (item["region"] != null)
                        address += item["region"].ToString() + " ";

                    ll.SubText = address;
                    ListingsForList.Add(ll);
                }

                // Default to the listings list for search results
                ConfigureListingsLayout();
            }

            int docCount = Convert.ToInt32(jsonObj["@odata.count"].ToString());

            // Update the seek bar with the paging
            maxPage = Convert.ToInt32(docCount / 10) + 1;

            if (countOnly == false)
            {
                SeekBar seekBar = FindViewById<SeekBar>(Resource.Id.seekBarPaging);
                if (maxPage > 20)
                    seekBar.Max = 19;   // Base 0
                else
                    seekBar.Max = maxPage;
            }

            return Convert.ToInt32(docCount.ToString());
        }

        private void ConfigureListingsLayout()
        {
            SetContentView(Resource.Layout.Listings);
            FindViewById<Button>(Resource.Id.btnListBack).Click += ButtonBack_Click;
            FindViewById<Button>(Resource.Id.btnListFilter).Click += ButtonFilter_Click;

            ListView lvListings = FindViewById<ListView>(Resource.Id.lvListings);
            lvListings.Adapter = new LoadListings(this, ListingsForList);

            SeekBar seekBar = FindViewById<SeekBar>(Resource.Id.seekBarPaging);
            seekBar.StopTrackingTouch += SeekBar_StopTrackingTouch;
            seekBar.ProgressChanged += SeekBar_ProgressChanged;
            seekBar.Progress = currentPage;

        }

        private void SeekBar_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
        {
            TextView seekBarText = FindViewById<TextView>(Resource.Id.textPaging);
            seekBarText.Text = "Page " + (Convert.ToInt32(e.SeekBar.Progress) + 1).ToString();
        }

        private void SeekBar_StopTrackingTouch(object sender, SeekBar.StopTrackingTouchEventArgs e)
        {
            currentPage = e.SeekBar.Progress;
            ExecListingsSearch();
        }

        private void ButtonBack_Click(object sender, EventArgs e)
        {
            // Go back to main layout
            ConfigureMainLayout();
        }

        private void ButtonFilter_Click(object sender, EventArgs e)
        {
            // Go to filter page
            ConfigureFilterLayout();
        }

        private void ConfigureFilterLayout()
        {
            SetContentView(Resource.Layout.Filter);
            FindViewById<TextView>(Resource.Id.filterTotalListings).Text = "Total Listings: " + ExecListingsSearch(countOnly: true);

            FindViewById<EditText>(Resource.Id.filterBedsMin).Text = filterMinBeds.ToString();
            FindViewById<EditText>(Resource.Id.filterBedsMax).Text = filterMaxBeds.ToString();
            FindViewById<EditText>(Resource.Id.filterBathsMin).Text = filterMinBaths.ToString();
            FindViewById<EditText>(Resource.Id.filterBedsMax).Text = filterMaxBaths.ToString();
            FindViewById<CheckBox>(Resource.Id.filterForSale).Checked = filterShowForSale;
            FindViewById<CheckBox>(Resource.Id.filterPending).Checked = filterShowPending;
            FindViewById<CheckBox>(Resource.Id.filterSold).Checked = filterShowSold;

            // Handle updates
            FindViewById<EditText>(Resource.Id.filterBedsMin).TextChanged += FilterActivity_TextChanged;
            FindViewById<EditText>(Resource.Id.filterBedsMax).TextChanged += FilterActivity_TextChanged;
            FindViewById<EditText>(Resource.Id.filterBathsMin).TextChanged += FilterActivity_TextChanged;
            FindViewById<EditText>(Resource.Id.filterBedsMax).TextChanged += FilterActivity_TextChanged;
            FindViewById<CheckBox>(Resource.Id.filterForSale).CheckedChange += FilterActivity_CheckedChange;
            FindViewById<CheckBox>(Resource.Id.filterPending).CheckedChange += FilterActivity_CheckedChange;
            FindViewById<CheckBox>(Resource.Id.filterSold).CheckedChange += FilterActivity_CheckedChange;

            Button filterApply = FindViewById<Button>(Resource.Id.filterApply);
            filterApply.Click += FilterApply_Click;
        }

        private void FilterActivity_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            // Store updated filter changes
            try
            {
                filterMinBeds = Convert.ToInt32(FindViewById<EditText>(Resource.Id.filterBedsMin).Text);
                filterMaxBeds = Convert.ToInt32(FindViewById<EditText>(Resource.Id.filterBedsMax).Text);
                filterMinBaths = Convert.ToInt32(FindViewById<EditText>(Resource.Id.filterBathsMin).Text);
                filterMaxBaths = Convert.ToInt32(FindViewById<EditText>(Resource.Id.filterBathsMax).Text);
                FindViewById<TextView>(Resource.Id.filterTotalListings).Text = "Total Listings: " + ExecListingsSearch(countOnly: true);
            }
            catch
            {
                // likely they hit delete and it is empty
            }
        }

        private void FilterActivity_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
        {
            // Store updated filter changes
            filterShowForSale = FindViewById<CheckBox>(Resource.Id.filterForSale).Checked;
            filterShowPending = FindViewById<CheckBox>(Resource.Id.filterPending).Checked;
            filterShowSold = FindViewById<CheckBox>(Resource.Id.filterSold).Checked;
            FindViewById<TextView>(Resource.Id.filterTotalListings).Text = "Total Listings: " + ExecListingsSearch(countOnly: true);
        }

        private void FilterApply_Click(object sender, EventArgs e)
        {
            // Go back to listsings
            ConfigureListingsLayout();
            ExecListingsSearch();
        }

        private async Task<List<string>> ExecSuggest(string q)
        {
            // Execute /suggest API call to Azure Search and parse results
            string url = _serviceUri + AzureSuggestUrl + q;

            Uri uri = new Uri(url);
            HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
            AzureSearchHelper.EnsureSuccessfulSearchResponse(response);
            dynamic result = AzureSearchHelper.DeserializeJson<dynamic>(response.Content.ReadAsStringAsync().Result);

            JObject jsonObj = JObject.Parse(result.ToString());
            List<string> Suggestions = new List<string>();
            // Iterate through the results to get the suggestions
            foreach (var item in jsonObj["value"])
            {
                Suggestions.Add(item["@search.text"].ToString());
            }
            // Limit to unique suggestions and sort
            return Suggestions.Distinct().OrderBy(x => x).ToList();
        }

    }
}


text:
'use strict';

angular
.module('app.controllers')
.controller('TinyMceCtrl', function($scope) {
	$scope.getTinyMceConfiguration = function(field) {
		return tinymceConfig(
			field.validation['allowed-html'],
			field.validation.maxlength || false,
			field.validation['read-only']
		);
	};

	/**
	 * Returns a tinymce.init() compatible configuration object based on the
	 * field's allowed tags and maxlength.
	 *
	 * @TODO: Use tinymce.Editor.addButton() to add buttons for <blockquote> and <q>
	 * that automatically trigger a popup asking for `cite` info, so users can add
	 * attributed notes in the notes field.
	 *
	 * Also add a button for the character counter, which means (probably)figuring
	 * out a property that angular can observe to make falsey when over maxlength.
	 */
	var tinymceConfig = function(allowedTags, charLimit, disabled) {
		var toolbarItems = [];
		var formatsListItems = [];
		var allowsBlockFormatting = false;
		var allowsInlineFormatting = false;

		// Build the items in formatsListItems based on the allowedTags. We do want
		// to add the formats to formatsListItems in the order they're defined in
		// the object literal below, so it's reassuring to know that object member
		// enumeration is in fact deterministic in ES6.
		var tagsToFormats = {
			'h1': {title: 'Heading', format: 'h1'},
			'h2': {title: 'Subheading', format: 'h2'},
			'p': {title: 'Standard Paragraph', format: 'p'},
			'code': {title: 'Code', icon: 'code', format: 'code'},
			'sup': {title: 'Superscript', icon: 'superscript', format: 'superscript'},
			'sub': {title: 'Subscript', icon: 'subscript', format: 'subscript'},
		};

		var tagsToButtonNames = {
			'em': 'italic',
			'strong': 'bold',
			'ul': 'bullist',
			'ol': 'numlist',
			'blockquote': 'blockquote'
		};

		for (var tag in tagsToFormats) {
			if (allowedTags.indexOf(tag) !== -1) {
				formatsListItems.push(tagsToFormats[tag]);
			}
		}

		// Add format picker to the toolbar
		toolbarItems.push('styleselect');
		toolbarItems.push('spacer');

		// Add inline formatting buttons
		['strong','em'].forEach(function(tag) {
			if (allowedTags.indexOf(tag) !== -1) {
				toolbarItems.push(tagsToButtonNames[tag]);
				allowsInlineFormatting = true;
			}
		});

		if (allowsInlineFormatting) {
			toolbarItems.push('spacer');
		}

		// Add Link buttons
		if (allowedTags.indexOf('a') !== -1) {
			toolbarItems.push('link');
			toolbarItems.push('anchor');
			toolbarItems.push('spacer');
		}

		// Add block formatting buttons.
		['ul', 'ol', 'blockquote'].forEach(function(tag) {
			if (allowedTags.indexOf(tag) !== -1) {
				toolbarItems.push(tagsToButtonNames[tag]);
				allowsBlockFormatting = true;
			}
		});

		if (allowsBlockFormatting) {
			toolbarItems.push('spacer');
		}

		// HTML EDITING.
		toolbarItems.push('code');

		// Note: DO NOT include the importcss plugin below,
		// as a bug makes it incompatible with the styleselect button.
		return {
			selector: 'textarea',
			theme: 'modern',
			plugins: [
				'anchor autolink autoresize autosave charmap code contextmenu emoticons',
				'lists link noneditable paste save searchreplace tabfocus table',
				'template textpattern'
			],
			toolbar: toolbarItems.join(' '),
			browser_spellcheck: true,
			fix_list_elements: true,
			image_advtab: true,
			menubar: false,
			statusbar: false,
			object_resizing: false,
			templates: [],
			valid_elements: allowedTags.join(','), // the array from the api
			relative_urls: false,
			style_formats: formatsListItems,
			style_formats_merge: false,
			autoresize_min_height: 175,
			readonly: disabled
		};
	};
});


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * An S3 bucket where you want to store the results of this request.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class S3OutputLocation implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The Amazon Web Services Region of the S3 bucket.
     *

     */
    private String outputS3Region;
    /**
     *

     * The name of the S3 bucket.
     *

     */
    private String outputS3BucketName;
    /**
     *

     * The S3 bucket subfolder.
     *

     */
    private String outputS3KeyPrefix;

    /**
     *

     * The Amazon Web Services Region of the S3 bucket.
     *

     *
     * @param outputS3Region
     *        The Amazon Web Services Region of the S3 bucket.
     */

    public void setOutputS3Region(String outputS3Region) {
        this.outputS3Region = outputS3Region;
    }

    /**
     *

     * The Amazon Web Services Region of the S3 bucket.
     *

     *
     * @return The Amazon Web Services Region of the S3 bucket.
     */

    public String getOutputS3Region() {
        return this.outputS3Region;
    }

    /**
     *

     * The Amazon Web Services Region of the S3 bucket.
     *

     *
     * @param outputS3Region
     *        The Amazon Web Services Region of the S3 bucket.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public S3OutputLocation withOutputS3Region(String outputS3Region) {
        setOutputS3Region(outputS3Region);
        return this;
    }

    /**
     *

     * The name of the S3 bucket.
     *

     *
     * @param outputS3BucketName
     *        The name of the S3 bucket.
     */

    public void setOutputS3BucketName(String outputS3BucketName) {
        this.outputS3BucketName = outputS3BucketName;
    }

    /**
     *

     * The name of the S3 bucket.
     *

     *
     * @return The name of the S3 bucket.
     */

    public String getOutputS3BucketName() {
        return this.outputS3BucketName;
    }

    /**
     *

     * The name of the S3 bucket.
     *

     *
     * @param outputS3BucketName
     *        The name of the S3 bucket.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public S3OutputLocation withOutputS3BucketName(String outputS3BucketName) {
        setOutputS3BucketName(outputS3BucketName);
        return this;
    }

    /**
     *

     * The S3 bucket subfolder.
     *

     *
     * @param outputS3KeyPrefix
     *        The S3 bucket subfolder.
     */

    public void setOutputS3KeyPrefix(String outputS3KeyPrefix) {
        this.outputS3KeyPrefix = outputS3KeyPrefix;
    }

    /**
     *

     * The S3 bucket subfolder.
     *

     *
     * @return The S3 bucket subfolder.
     */

    public String getOutputS3KeyPrefix() {
        return this.outputS3KeyPrefix;
    }

    /**
     *

     * The S3 bucket subfolder.
     *

     *
     * @param outputS3KeyPrefix
     *        The S3 bucket subfolder.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public S3OutputLocation withOutputS3KeyPrefix(String outputS3KeyPrefix) {
        setOutputS3KeyPrefix(outputS3KeyPrefix);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getOutputS3Region() != null)
            sb.append("OutputS3Region: ").append(getOutputS3Region()).append(",");
        if (getOutputS3BucketName() != null)
            sb.append("OutputS3BucketName: ").append(getOutputS3BucketName()).append(",");
        if (getOutputS3KeyPrefix() != null)
            sb.append("OutputS3KeyPrefix: ").append(getOutputS3KeyPrefix());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof S3OutputLocation == false)
            return false;
        S3OutputLocation other = (S3OutputLocation) obj;
        if (other.getOutputS3Region() == null ^ this.getOutputS3Region() == null)
            return false;
        if (other.getOutputS3Region() != null && other.getOutputS3Region().equals(this.getOutputS3Region()) == false)
            return false;
        if (other.getOutputS3BucketName() == null ^ this.getOutputS3BucketName() == null)
            return false;
        if (other.getOutputS3BucketName() != null && other.getOutputS3BucketName().equals(this.getOutputS3BucketName()) == false)
            return false;
        if (other.getOutputS3KeyPrefix() == null ^ this.getOutputS3KeyPrefix() == null)
            return false;
        if (other.getOutputS3KeyPrefix() != null && other.getOutputS3KeyPrefix().equals(this.getOutputS3KeyPrefix()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getOutputS3Region() == null) ? 0 : getOutputS3Region().hashCode());
        hashCode = prime * hashCode + ((getOutputS3BucketName() == null) ? 0 : getOutputS3BucketName().hashCode());
        hashCode = prime * hashCode + ((getOutputS3KeyPrefix() == null) ? 0 : getOutputS3KeyPrefix().hashCode());
        return hashCode;
    }

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

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.simplesystemsmanagement.model.transform.S3OutputLocationMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
set -e

REL_SCRIPT_DIR=`dirname "$0"`
SCRIPT_NAME=`basename "$0"`
SCRIPT_DIR=$(cd "$REL_SCRIPT_DIR" && echo "$(pwd -P)")
MSG_FILTER="$SCRIPT_DIR"/upstream_msg_filter.sed

PATCH_DIR="./patches/"
UPSTREAM="upstream/master"

usage()
{
    cat <<EOF
$SCRIPT_NAME [OPTION]...  [BRANCH]
Format a patch series suitable for upstream consumption.

Options:
  -u BRANCH      Upstream branch
  -d DIR         Patch directory
  -h             Show this help string.

This script creates a series of patches suitable from upstream
consumption from a git branch. By default, the script works on the
currently checked out branch (HEAD). When invoked, the script executes
the following operations in order:

  1. Rebase the patches in the current branch onto the upstream
     branch.
  2. Filter commit messages.
  3. Generate a set of patches in git format.
EOF
}

branch_exists()
{
    git rev-parse --verify -q "$1" > /dev/null
}

while getopts ":u:d:h" OPT; do
    case $OPT in
        d)
            PATCH_DIR="$OPTARG"
            ;;
        u)
            UPSTREAM="$OPTARG"
            ;;
        h)
            usage
            exit 0
            ;;

        \?)
            echo "$0: invalid option --  '$OPTARG'" >&2
            echo "Try '$0 -h' for more information." >&2
            exit 1
            ;;
        :)
            echo "$0: option requires an argument -- '$OPTARG'" >&2
            exit 1
            ;;
        *)
            echo "Unhandled getopt return:" >&2
            echo "OPT: $OPT" >&2
            echo "OPTARG: $OPTARG" >&2
            exit 1
    esac
done

shift $((OPTIND - 1))

BRANCH="${1:-HEAD}"

if ! branch_exists "$BRANCH"; then
    echo "Error: Patch branch '$BRANCH' doesn't exist" 1>&2
    exit 2
fi

if ! branch_exists "$UPSTREAM"; then
    echo "Error: Upstream branch '$UPSTREAM' doesn't exist." 1>&2
    exit 2
fi

SHA_PATCHES=`git rev-parse "$BRANCH"`
OLD_BRANCH=`git symbolic-ref --short -q HEAD`
SHA_UPSTREAM=`git rev-parse "$UPSTREAM"`

echo "Upstream branch: $UPSTREAM"
echo "Patch directory: $PATCH_DIR"

echo "Preparing detached head..."
git checkout -q --detach "$SHA_PATCHES"

# Create an exit trap to checkout the old branch when we're done
exit_trap() {
    git checkout -q "$OLD_BRANCH"
}
trap exit_trap EXIT

echo "Rebasing onto upstream master..."
git rebase "$UPSTREAM"

echo "Filtering commit messages..."
git filter-branch -f \
    --msg-filter "$MSG_FILTER" \
    "$SHA_UPSTREAM"..HEAD > /dev/null

echo "Creating patches..."
git format-patch -p -o "$PATCH_DIR" "$UPSTREAM"


text:
/**
 * @file PhotoService
 * @author peter.szocs
 *
 * Service methods related to user photos.
 */

package com.vh.locker.service;

import java.util.Collection;
import java.util.Date;

import com.vh.locker.ejb.Photo;
import com.vh.locker.ejb.PhotoAlbum;
import com.vh.locker.ejb.RelPhotoAlbum;
import com.vh.locker.service.exception.ServiceException;

/**
 * The VH Corporation
 *
 * Copyright (c) 2005 The VH Corporation.  All rights reserved.
 * Copying or reproduction without prior written approval is prohibited.
 *
 * @author  peter.szocs
 * @version 1.0
 */
public interface PhotoService extends Service {

  /**
   * Photo
   */
  public Photo createPhoto(String desc, String link, Long userId) throws ServiceException;

  public boolean updatePhoto(Long id, String desc, String link) throws ServiceException;

  public Photo findPhotoById(Long id) throws ServiceException;

  public Collection findPhotoByAlbum(Long albumId) throws ServiceException;

  public Collection findPhotoByUser(Long userId) throws ServiceException;

  /**
   * PhotoAlbum
   */
  public PhotoAlbum createPhotoAlbum(String title, String desc, Date dateCreated, long nofVisits, Long userId) throws ServiceException;

  public boolean updatePhotoAlbum(Long id, String title, String desc) throws ServiceException;

  public PhotoAlbum findPhotoAlbumById(Long id) throws ServiceException;

  public Collection findPhotoAlbumByUser(Long userId) throws ServiceException;

  /**
   * RelPhotoAlbum
   */
  public RelPhotoAlbum createRelPhotoAlbum(Long photoId, Long albumId, long orderInAlbum) throws ServiceException;

  public boolean updateRelPhotoAlbum(Long photoId, Long photoAlbumId, long newOrderInAlbum) throws ServiceException;

  public RelPhotoAlbum findRelPhotoAlbumById(Long photoId, Long photoAlbumId) throws ServiceException;

}


text:
using namespace arangodb;
using namespace arangodb::pregel;

template<typename M>
OutCache<M>::OutCache(WorkerConfig* state, MessageFormat<M> const* format)
    : _config(state),
      _format(format),
      _baseUrl(Utils::baseUrl(Utils::workerPrefix)) {}

// ================= ArrayOutCache ==================

template<typename M>
ArrayOutCache<M>::~ArrayOutCache() = default;

template<typename M>
void ArrayOutCache<M>::_removeContainedMessages() {
  for (auto& pair : _shardMap) {
    pair.second.clear();
  }
  this->_containedMessages = 0;
}

template<typename M>
void ArrayOutCache<M>::appendMessage(PregelShard shard,
                                     std::string_view const& key,
                                     M const& data) {
  if (this->_config->isLocalVertexShard(shard)) {
    if (this->_sendToNextGSS) {  // I use the global cache, we need locking
      this->_localCacheNextGSS->storeMessage(shard, key, data);
      this->_sendCountNextGSS++;
    } else {  // the local cache is always thread local
      this->_localCache->storeMessageNoLock(shard, key, data);
      this->_sendCount++;
    }
  } else {
    _shardMap[shard][std::string(key)].push_back(data);
    if (++(this->_containedMessages) >= this->_batchSize) {
      flushMessages();
    }
  }
}

template<typename M>
void ArrayOutCache<M>::flushMessages() {
  if (this->_containedMessages == 0) {
    return;
  }

  // LOG_TOPIC("7af7f", INFO, Logger::PREGEL) << "Beginning to send messages to
  // other machines";
  uint64_t gss = this->_config->globalSuperstep();
  if (this->_sendToNextGSS) {
    gss += 1;
  }
  VPackOptions options = VPackOptions::Defaults;
  options.buildUnindexedArrays = true;
  options.buildUnindexedObjects = true;

  auto& server = this->_config->vocbase()->server();
  auto const& nf = server.template getFeature<arangodb::NetworkFeature>();
  network::ConnectionPool* pool = nf.pool();

  network::RequestOptions reqOpts;
  reqOpts.database = this->_config->database();
  reqOpts.skipScheduler = true;

  std::vector<futures::Future<network::Response>> responses;
  for (auto const& it : _shardMap) {
    PregelShard shard = it.first;
    std::unordered_map<std::string, std::vector<M>> const& vertexMessageMap =
        it.second;
    if (vertexMessageMap.size() == 0) {
      continue;
    }

    VPackBuffer<uint8_t> buffer;
    VPackBuilder data(buffer, &options);
    data.openObject();
    data.add(Utils::senderKey, VPackValue(ServerState::instance()->getId()));
    data.add(Utils::executionNumberKey,
             VPackValue(this->_config->executionNumber()));
    data.add(Utils::globalSuperstepKey, VPackValue(gss));
    data.add(Utils::shardIdKey, VPackValue(shard));
    data.add(Utils::messagesKey, VPackValue(VPackValueType::Array, true));
    for (auto const& vertexMessagePair : vertexMessageMap) {
      data.add(VPackValue(vertexMessagePair.first));      // key
      data.add(VPackValue(VPackValueType::Array, true));  // message array
      for (M const& val : vertexMessagePair.second) {
        this->_format->addValue(data, val);
        if (this->_sendToNextGSS) {
          this->_sendCountNextGSS++;
        } else {
          this->_sendCount++;
        }
      }
      data.close();
    }
    data.close();
    data.close();
    // add a request
    ShardID const& shardId = this->_config->globalShardIDs()[shard];

    responses.emplace_back(network::sendRequest(
        pool, "shard:" + shardId, fuerte::RestVerb::Post,
        this->_baseUrl + Utils::messagesPath, std::move(buffer), reqOpts));
  }

  futures::collectAll(responses).wait();

  this->_removeContainedMessages();
}

// ================= CombiningOutCache ==================

template<typename M>
CombiningOutCache<M>::CombiningOutCache(WorkerConfig* state,
                                        MessageFormat<M> const* format,
                                        MessageCombiner<M> const* combiner)
    : OutCache<M>(state, format), _combiner(combiner) {}

template<typename M>
CombiningOutCache<M>::~CombiningOutCache() = default;

template<typename M>
void CombiningOutCache<M>::_removeContainedMessages() {
  for (auto& pair : _shardMap) {
    pair.second.clear();
  }
  this->_containedMessages = 0;
}

template<typename M>
void CombiningOutCache<M>::appendMessage(PregelShard shard,
                                         std::string_view const& key,
                                         M const& data) {
  if (this->_config->isLocalVertexShard(shard)) {
    if (this->_sendToNextGSS) {
      this->_localCacheNextGSS->storeMessage(shard, key, data);
      this->_sendCountNextGSS++;
    } else {
      this->_localCache->storeMessageNoLock(shard, key, data);
      this->_sendCount++;
    }
  } else {
    std::unordered_map<std::string_view, M>& vertexMap = _shardMap[shard];
    auto it = vertexMap.find(key);
    if (it != vertexMap.end()) {  // more than one message
      auto& ref = (*it).second;   // will be modified by combine(...)
      _combiner->combine(ref, data);
    } else {  // first message for this vertex
      vertexMap.try_emplace(key, data);

      if (++(this->_containedMessages) >= this->_batchSize) {
        // LOG_TOPIC("23bc7", INFO, Logger::PREGEL) << "Hit buffer limit";
        flushMessages();
      }
    }
  }
}

template<typename M>
void CombiningOutCache<M>::flushMessages() {
  if (this->_containedMessages == 0) {
    return;
  }

  uint64_t gss = this->_config->globalSuperstep();
  if (this->_sendToNextGSS && this->_config->asynchronousMode()) {
    gss += 1;
  }
  VPackOptions options = VPackOptions::Defaults;
  options.buildUnindexedArrays = true;
  options.buildUnindexedObjects = true;

  auto& server = this->_config->vocbase()->server();
  auto const& nf = server.template getFeature<arangodb::NetworkFeature>();
  network::ConnectionPool* pool = nf.pool();

  std::vector<futures::Future<network::Response>> responses;
  for (auto const& it : _shardMap) {
    PregelShard shard = it.first;
    std::unordered_map<std::string_view, M> const& vertexMessageMap = it.second;
    if (vertexMessageMap.size() == 0) {
      continue;
    }

    VPackBuffer<uint8_t> buffer;
    VPackBuilder data(buffer, &options);
    data.openObject();
    data.add(Utils::senderKey, VPackValue(ServerState::instance()->getId()));
    data.add(Utils::executionNumberKey,
             VPackValue(this->_config->executionNumber()));
    data.add(Utils::globalSuperstepKey, VPackValue(gss));
    data.add(Utils::shardIdKey, VPackValue(shard));
    data.add(Utils::messagesKey, VPackValue(VPackValueType::Array, true));
    for (auto const& vertexMessagePair : vertexMessageMap) {
      data.add(VPackValuePair(vertexMessagePair.first.data(),
                              vertexMessagePair.first.size(),
                              VPackValueType::String));         // key
      this->_format->addValue(data, vertexMessagePair.second);  // value

      if (this->_sendToNextGSS) {
        this->_sendCountNextGSS++;
      } else {
        this->_sendCount++;
      }
    }
    data.close();
    data.close();
    // add a request
    ShardID const& shardId = this->_config->globalShardIDs()[shard];

    network::RequestOptions reqOpts;
    reqOpts.database = this->_config->database();
    reqOpts.timeout = network::Timeout(180);
    reqOpts.skipScheduler = true;

    responses.emplace_back(network::sendRequest(
        pool, "shard:" + shardId, fuerte::RestVerb::Post,
        this->_baseUrl + Utils::messagesPath, std::move(buffer), reqOpts));
  }

  futures::collectAll(responses).wait();

  _removeContainedMessages();
}

// template types to create
template class arangodb::pregel::OutCache<int64_t>;
template class arangodb::pregel::OutCache<uint64_t>;
template class arangodb::pregel::OutCache<float>;
template class arangodb::pregel::OutCache<double>;
template class arangodb::pregel::ArrayOutCache<int64_t>;
template class arangodb::pregel::ArrayOutCache<uint64_t>;
template class arangodb::pregel::ArrayOutCache<float>;
template class arangodb::pregel::ArrayOutCache<double>;
template class arangodb::pregel::CombiningOutCache<int64_t>;
template class arangodb::pregel::CombiningOutCache<uint64_t>;
template class arangodb::pregel::CombiningOutCache<float>;
template class arangodb::pregel::CombiningOutCache<double>;

// algo specific
template class arangodb::pregel::OutCache<SenderMessage<uint64_t>>;
template class arangodb::pregel::ArrayOutCache<SenderMessage<uint64_t>>;
template class arangodb::pregel::CombiningOutCache<SenderMessage<uint64_t>>;

template class arangodb::pregel::OutCache<SenderMessage<double>>;
template class arangodb::pregel::ArrayOutCache<SenderMessage<double>>;
template class arangodb::pregel::CombiningOutCache<SenderMessage<double>>;

template class arangodb::pregel::OutCache<DMIDMessage>;
template class arangodb::pregel::ArrayOutCache<DMIDMessage>;
template class arangodb::pregel::CombiningOutCache<DMIDMessage>;

template class arangodb::pregel::OutCache<HLLCounter>;
template class arangodb::pregel::ArrayOutCache<HLLCounter>;
template class arangodb::pregel::CombiningOutCache<HLLCounter>;

using namespace arangodb::pregel::algos::accumulators;
template class arangodb::pregel::OutCache<MessageData>;
template class arangodb::pregel::ArrayOutCache<MessageData>;
template class arangodb::pregel::CombiningOutCache<MessageData>;


text:
layout: post
title: Big Titty Starlet Fucked Deep in her Ass
titleinfo: pornvd
desc: Watch Big Titty Starlet Fucked Deep in her Ass. Pornhub is the ultimate xxx porn and sex site.
---

Big Titty Starlet Fucked Deep in her Ass

Watch Big Titty Starlet Fucked Deep in her Ass. Pornhub is the ultimate xxx porn and sex site.


text:
<?php

namespace Hamdrew\AdventOfCode\Day6;

/**
 * Tests for {@link LightInstructionActionBehaviorPart2}
 */
class LightInstructionActionBehaviorPart2Test extends \PHPUnit_Framework_TestCase
{

    /**
     * @test
     * @expectedException \Hamdrew\AdventOfCode\Day6\InvalidLightInstructionActionException
     */
    public function failsIfInvalidAction()
    {
        LightInstructionActionBehaviorPart2::behaviorForAction(999);
    }

    /** @test */
    public function turnOnIncreasesBrightness()
    {
        $this->assertSame(2, call_user_func(
            LightInstructionActionBehaviorPart2::behaviorForAction(LightInstructionAction::TURN_ON),
            1
        ));
    }

    /** @test */
    public function turnOffDecreasesBrightness()
    {
        $this->assertSame(1, call_user_func(
            LightInstructionActionBehaviorPart2::behaviorForAction(
                LightInstructionAction::TURN_OFF
            ),
            2
        ));
    }

    /** @test */
    public function minimumBrightnessIsZero()
    {
        $this->assertSame(0, call_user_func(
            LightInstructionActionBehaviorPart2::behaviorForAction(
                LightInstructionAction::TURN_OFF
            ),
            0
        ));
    }

    /** @test */
    public function toggleIncreasesBrightnessByTwo()
    {
        $this->assertSame(3, call_user_func(
            LightInstructionActionBehaviorPart2::behaviorForAction(
                LightInstructionAction::TOGGLE
            ),
            1
        ));
    }
}


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  needs: 'application',

  currentPath: Ember.computed.alias('controllers.application.currentPath'),

  inWelcome:   Ember.computed.match('currentPath', /^index$/),
  inAccounts:  Ember.computed.match('currentPath', /^account/),
  inTransfers: Ember.computed.match('currentPath', /^transfer/)
});


text:
package org.kuali.rice.kns.datadictionary.exporter;

import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.doctype.DocumentType;
import org.kuali.rice.kns.datadictionary.KNSDocumentEntry;
import org.kuali.rice.kns.service.DocumentHelperService;
import org.kuali.rice.kns.service.KNSServiceLocator;
import org.kuali.rice.krad.datadictionary.DataDictionaryEntryBase;
import org.kuali.rice.krad.datadictionary.exporter.ExportMap;

/**
 * DocumentEntryMapper
 *
 * @deprecated Only used by KNS classes, no replacement.
 */
@Deprecated
public abstract class DocumentEntryMapper {

    protected DocumentType getDocumentType(String documentTypeName) {
        return KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(documentTypeName);
    }

    /**
     * @param entry
     * @return Map containing entries for properties common to all DocumentEntry subclasses
     */
    @SuppressWarnings("unchecked")
	protected ExportMap mapEntry(KNSDocumentEntry entry) {
        if (entry == null) {
            throw new IllegalArgumentException("invalid (null) entry");
        }

        // simple properties
        ExportMap entryMap = new ExportMap(entry.getJstlKey());

        Class businessRulesClass = entry.getBusinessRulesClass();
        if (businessRulesClass != null) {
            entryMap.set("businessRulesClass", businessRulesClass.getName());
        }

        entryMap.set("documentTypeName", entry.getDocumentTypeName());

        DocumentType docType = getDocumentType(entry.getDocumentTypeName());
        entryMap.set("label", docType.getLabel());

        if (docType.getDescription() != null) {
            entryMap.set("description", docType.getDescription());
        }

        DocumentHelperService documentHelperService = KNSServiceLocator.getDocumentHelperService();
        entryMap.set("documentAuthorizerClass", documentHelperService.getDocumentAuthorizer(entry.getDocumentTypeName()).getClass().getName());
        entryMap.set("documentPresentationControllerClass", documentHelperService.getDocumentPresentationController(entry.getDocumentTypeName()).getClass().getName());

        entryMap.set("allowsNoteAttachments", Boolean.toString(entry.getAllowsNoteAttachments()));

        entryMap.set("allowsNoteFYI", Boolean.toString(entry.getAllowsNoteFYI()));

        if (entry.getAttachmentTypesValuesFinderClass() != null) {
            entryMap.set("attachmentTypesValuesFinderClass", entry.getAttachmentTypesValuesFinderClass().getName());
        }

        entryMap.set("displayTopicFieldInNotes", Boolean.toString(entry.getDisplayTopicFieldInNotes()));

        entryMap.set("usePessimisticLocking", Boolean.toString(entry.getUsePessimisticLocking()));
        entryMap.set("useWorkflowPessimisticLocking", Boolean.toString(entry.getUseWorkflowPessimisticLocking()));
        entryMap.set("sessionDocument", Boolean.toString(entry.isSessionDocument()));

        entryMap.set(new AttributesMapBuilder().buildAttributesMap((DataDictionaryEntryBase) entry));
        entryMap.set(new CollectionsMapBuilder().buildCollectionsMap((DataDictionaryEntryBase) entry));

        return entryMap;
    }

}


text:
body {
    -webkit-touch-callout: none;
    -webkit-text-size-adjust: none;
    -webkit-user-select: none;
}


text:
require "braille/version"
require "braille/translator"

module Braille

end


text:
package uk.ac.ed.ph.snuggletex;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;
import java.util.Locale;

/**
 * Implementation of {@link NumberMatcher} that uses a standard Java {@link DecimalFormat} to
 * match numbers.
 *

 * By default, this uses the default {@link DecimalFormat} with the platform default {@link Locale}.
 *

 * You will probably want your {@link DecimalFormat} to have grouping turned off, otherwise
 * something like <tt>1,2</tt> (in UK locale) would be parsed as a number 12.
 *
 * @since 1.3.0
 *
 * @author  David McKain
 * @version $Revision: 742 $
 */
public class DecimalFormatNumberMatcher implements NumberMatcher {

    private static final int READAHEAD_INCREMENT = 4;

    private DecimalFormat decimalFormat;

    public DecimalFormatNumberMatcher() {
        this(Locale.getDefault());
    }

    public DecimalFormatNumberMatcher(Locale locale) {
        this.decimalFormat = new DecimalFormat();
        decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
        decimalFormat.setGroupingUsed(false);
    }

    public DecimalFormatNumberMatcher(DecimalFormat decimalFormat) {
        this.decimalFormat = decimalFormat;
    }

    public DecimalFormat getDecimalFormat() {
        return decimalFormat;
    }

    public void setDecimalFormat(DecimalFormat decimalFormat) {
        this.decimalFormat = decimalFormat;
    }

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

    public int getNumberEnd(InputContext input, int startIndex) {
        decimalFormat.setParseBigDecimal(true);

        /* Since the number can potentially be quite long, we'll analyse a few characters
         * at a time, extending until we have parsed the entire number.
         */
        int maxReadAhead = input.length() - startIndex;
        int readAhead = Math.min(READAHEAD_INCREMENT, maxReadAhead);
        int endIndex = -1;
        if (readAhead > 0) {
            while (true) {
                String candidate = input.extract(startIndex, startIndex + readAhead).toString();
                ParsePosition parsePosition = new ParsePosition(0);
                BigDecimal parsed = (BigDecimal) decimalFormat.parse(candidate, parsePosition);
                if (parsed==null) {
                    /* Not a number */
                    break;
                }
                else if (parsed.compareTo(BigDecimal.ZERO) < 0) {
                    /* Negative numbers are treated separately */
                    break;
                }
                else if (parsePosition.getIndex()==readAhead && readAhead < maxReadAhead) {
                    /* Need to parse a bit more... */
                    readAhead = Math.min(readAhead + READAHEAD_INCREMENT, maxReadAhead);
                    continue;
                }
                else {
                    /* Got end of number */
                    endIndex = startIndex + parsePosition.getIndex();
                    break;
                }
            }
        }
        return endIndex;
    }
}


text:
{-| @benchmark@ contains the logic to be executed on slave nodes.
-}

module FeedGipeda.Slave
  ( benchmark
  ) where

import           Control.Applicative
import           Control.Concurrent.Async (Concurrently (..))
import           Control.Exception        (bracket)
import           Control.Logging          as Logging
import           Data.Conduit             (($$))
import qualified Data.Conduit.List        as CL
import           Data.Conduit.Process     (ClosedStream (..),
                                           CreateProcess (..),
                                           interruptProcessGroupOf, proc,
                                           readCreateProcessWithExitCode, shell,
                                           showCommandForUser, streamingProcess,
                                           streamingProcessHandleRaw,
                                           waitForStreamingProcess)
import           Data.Monoid
import qualified Data.Text                as Text
import qualified Data.Text.Encoding       as Text
import           FeedGipeda.GitShell      (SHA)
import           FeedGipeda.Prelude
import           FeedGipeda.Repo          (Repo)
import qualified FeedGipeda.Repo          as Repo
import           FeedGipeda.Types         (Timeout)
import           System.Exit              (ExitCode (..))
import           System.IO.Temp           (withSystemTempDirectory)
import qualified System.Timeout

-- We have to roll our own, because the provided functions use @terminateProcess@
-- instead of @interruptProcessGroupOf@, so that in case of shelling out we only
-- kill the shell process but not its children.
readCreateProcessGroupWithExitCode :: CreateProcess -> IO (ExitCode, String, String)
readCreateProcessGroupWithExitCode cp =
  bracket
    (streamingProcess cp { create_group = True })
    cleanup
    captureStreams
  where
    cleanup (_, _, _, sph) =
      interruptProcessGroupOf (streamingProcessHandleRaw sph)

    captureStreams (ClosedStream, out, err, sph) =
      runConcurrently $ (,,)
        <$> Concurrently (waitForStreamingProcess sph)
        <*> Concurrently (out $$ stringSink)
        <*> Concurrently (err $$ stringSink)

    stringSink =
      Text.unpack . Text.decodeUtf8 <$> CL.fold (<>) mempty

procReportingError :: Repo -> SHA -> Maybe FilePath -> FilePath -> [String] -> IO String
procReportingError repo commit cwd cmd args = do
  (exitCode, stdout, stderr) <-
    readCreateProcessWithExitCode (proc cmd args) { cwd = cwd } ""
  reportError repo commit (showCommandForUser cmd args) exitCode stderr
  return stdout

shellReportingError :: Repo -> SHA -> Maybe FilePath -> FilePath -> IO String
shellReportingError repo commit cwd cmd = do
  (exitCode, stdout, stderr) <-
    readCreateProcessGroupWithExitCode (shell cmd) { cwd = cwd }
  reportError repo commit cmd exitCode stderr
  return stdout

reportError :: Repo -> SHA -> String -> ExitCode -> String -> IO ()
reportError repo commit cmd code stderr =
  case code of
    ExitSuccess -> return ()
    ExitFailure c ->
      logWarn . unlines $
        [ "Benchmark script error"
        , "At commit " ++ Repo.uri repo ++ "@" ++ commit ++ ":"
        , cmd ++ ": exit code " ++ show c
        , stderr
        ]

cloneRecursiveAndCheckout :: Repo -> SHA -> FilePath -> IO ()
cloneRecursiveAndCheckout repo commit cloneDir = do
  procReportingError repo commit Nothing "git" ["clone", "--quiet", Repo.uri repo, cloneDir]
  procReportingError repo commit (Just cloneDir) "git" ["reset", "--hard", commit]
  shellReportingError repo commit (Just cloneDir) "git submodule update --init --recursive --quiet"
  return ()

{-| Clones the given @repo@ at a specific @commit@ into a temporary directory.
    Then calls the @benchmarkScript@ within that directory and returns its output.

    Will be executed on slave nodes.
-}
benchmark :: String -> Repo -> SHA -> Timeout -> IO String
benchmark benchmarkScript repo commit timeout = do
  clone <- Repo.cloneDir repo
  logInfo ("Benchmarking " ++ Repo.uri repo ++ "@" ++ commit)
  withSystemTempDirectory "feed-gipeda" $ \cloneDir -> do
    cloneRecursiveAndCheckout repo commit cloneDir
    res <- System.Timeout.timeout (ceiling (timeout * 10^6)) $
      shellReportingError repo commit (Just cloneDir) benchmarkScript
    case res of
      Just res -> do
        logInfo "Finished. Output:"
        mapM_ logInfo (lines res)
        return res
      Nothing -> do
        logWarn . unlines $
          [ "Benchmark script timed out (--timeout is " ++ show timeout ++ ")"
          , "At commit " ++ Repo.uri repo ++ "@" ++ commit
          ]
        return "build/timeout;1.0"


text:
namespace tnet
{
    class Address;
    class IOLoop;
    class Process;
    class ConnChecker;

    class TcpServer : public nocopyable
    {
    public:
        TcpServer();
        ~TcpServer();

        int listen(const Address& addr, const ConnEventCallback_t& callback);

        void start(size_t maxProcess = 0);
        void stop();

        IOLoop* getLoop() { return m_loop; }

        void setRunCallback(const ServerRunCallback_t& callback) { m_runCallback = callback; }

        //timeout is second
        void setMaxIdleTimeout(int timeout) { m_maxIdleTimeout = timeout; }

    private:
        void run();
        void onRun();
        void onStop();
        void onSignal(const SignalerPtr_t& signaler, int signum);
        void onIdleConnCheck(const TimingWheelPtr_t& wheel, const WeakConnectionPtr_t& conn);
        void onNewConnection(IOLoop* loop, int fd, const ConnEventCallback_t& callback);

    private:
        IOLoop* m_loop;

        ProcessPtr_t m_process;

        std::vector<AcceptorPtr_t> m_acceptors;

        SignalerPtr_t m_signaler;

        int m_maxIdleTimeout;
        TimingWheelPtr_t m_idleWheel;

        std::set<pid_t> m_workers;
        size_t m_workerNum;

        bool m_workerProc;
        bool m_running;

        ServerRunCallback_t m_runCallback;
    };

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Xml;
using Sidi.Persistence;
using log4net;
using System.Data.Common;
using System.Data.SQLite;
using Sidi.IO;

namespace Sidi.Sammy
{
    public class Account : IDisposable
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        string user;
        string password;
        Settings settings;

        public string User { get { return user; } }
        public string Password { set { password = value; } }

        public string UserFileName
        {
            get{
                return System.Text.RegularExpressions.Regex.Replace(User, @"\W", "_");
            }
        }

        public Collection<Payment> Payments
        {
            get
            {
                return new Collection<Payment>(DbConnection);
            }
        }

        public Collection<PaymentMailBox.ReadFlag> ReadFlags
        {
            get
            {
                return new Collection<PaymentMailBox.ReadFlag>(DbConnection);
            }
        }

        public Settings Settings
        {
            get
            {
                return settings;
            }
        }

        public Account(string user, string password)
        {
            log.InfoFormat("Ctor user={0}", user);
            this.user = user;
            this.password = password;
        }

        public Account()
        {
        }

        public bool Exists
        {
            get
            {
                return File.Exists(DbFile);
            }
        }

        public void Create()
        {
            if (Exists)
            {
                throw new System.IO.IOException("Exists: " + DbConnection);
            }
            log.InfoFormat("Create user={0}", user);
            DbFile.EnsureParentDirectoryExists();
            settings = new Settings();
            Collectors c = new Collectors();
            StringWriter w = new StringWriter();
            c.CreateSampleScript(w);
            settings.Script = w.ToString();
            Write();
        }

        public void Delete()
        {
            if (Exists)
            {
                Close();
                File.Delete(DbFile);
            }
        }

        void Close()
        {
            if (dbConnection != null)
            {
                dbConnection.Close();
                dbConnection = null;
            }
        }

        public static Account DefaultAccount
        {
           get; set;
        }

        public bool PromptForCredentials()
        {
            CredentialsDlg cred = new CredentialsDlg();
            while (true)
            {
                if (cred.ShowDialog() != DialogResult.OK)
                {
                    return false;
                }

                user = cred.textBoxUser.Text;
                password = cred.textBoxPassword.Text;

                if (!Exists || !Read())
                {
                    System.Windows.Forms.MessageBox.Show("Wrong user or password.");
                    continue;
                }

                return true;
            }
        }

        public bool ChangePassword()
        {
            ChangePasswordDlg dlg = new ChangePasswordDlg();
            while (dlg.ShowDialog() == DialogResult.OK)
            {
                Password = dlg.textBoxPassword.Text;
                return true;
            }
            return false;
        }

        public void Write()
        {
            log.InfoFormat("Write user={0}", user);
            MemoryStream m = new MemoryStream();
            Stream s = CryptUtil.EncryptStream(m, password);
            XmlSerializer ser = new XmlSerializer(typeof(Settings));
            XmlTextWriter xmlw = new XmlTextWriter(new StreamWriter(s));
            ser.Serialize(xmlw, settings);
            xmlw.Close();
            s.Close();
            Config<byte[]>()["script"] = m.ToArray();
        }

        public Sidi.Persistence.Dictionary<string, TValue> Config<TValue>()
        {
            return new Sidi.Persistence.Dictionary<string, TValue>(DbConnection, "config");
        }

        public bool Read()
        {
            log.InfoFormat("Read user={0}", user);

            MemoryStream m = new MemoryStream(Config<byte[]>()["script"]);

            Stream s = CryptUtil.DecrytStream(m, password);
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(Settings));
                XmlTextReader xmlr = new XmlTextReader(new StreamReader(s));
                settings = (Settings)ser.Deserialize(xmlr);
                xmlr.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                s.Close();
            }
        }

        DbConnection DbConnection
        {
            get
            {
                if (dbConnection == null)
                {
                    Collection<Payment> c = new Collection<Payment>(DbFile);
                    dbConnection = c.Connection;
                }
                return dbConnection;
            }
        }
        DbConnection dbConnection;

        string DbFile
        {
            get
            {
                string p = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                p = Path.Combine(p, Sammy.ApplicationName);
                return Path.Combine(p, UserFileName + ".sqlite");
            }
        }

        public DateTime NextCollect
        {
            get
            {
                DateTime v;
                if (!Config<DateTime>().TryGetValue("nextCollect", out v))
                {
                    v = DateTime.MinValue;
                }
                return v;
            }

            set
            {
                Config<DateTime>()["nextCollect"] = value;
                log.InfoFormat("Collect time for user {0} is set to {1}", User, value);
            }
        }

        public void CheckCollect()
        {
            DateTime nextCollect = NextCollect;
            log.InfoFormat("Collect time for user {0} is {1}", User, nextCollect);
            if (nextCollect < DateTime.Now)
            {
                NextCollect = DateTime.Now + new TimeSpan(1, 0, 0);
                try
                {
                    Collect();
                }
                catch (Exception e)
                {
                    log.Error("error during account collection", e);
                }
            }
        }

        public void Collect()
        {
            using (ThreadContext.Stacks["NDC"].Push(User))
            {
                log.InfoFormat("Collecting statements for user {0}", User);
                Collectors collector = new Collectors();
                collector.Payments = Payments;
                collector.Exec(Settings.Script);
                log.InfoFormat("Finished collecting statements for user {0}", User);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            Close();
        }

        #endregion
    }
}